Home >Backend Development >PHP Tutorial >Four ways to connect to the database in php

Four ways to connect to the database in php

WBOY
WBOYOriginal
2016-07-25 08:57:531496browse
  1. $conn = new Com("ADODB.Connection"); //Instantiate a Connection object

  2. $connstr = "provider=sqloledb;datasource=.;uid= Username;pwd=password;database=database;";
  3. $conn->Open($connstr);
  4. $rs = new Com("ADODB.Recordset"); //Instantiate a Recordcount object
  5. /*Use Example*/
  6. $rs->Open('select * from News where bigclassid = 59 And LeadPostil is null', $conn, 1, 1);
  7. $count = $rs->RecordCount; // bbs.it -home.org
  8. echo "Total {$count} records
    ";
  9. for($i = 0; $i < $count ; $i++){

  10. Fields('Title')->Value);//Title
  11. $arr_result[$i]['Color'] = addslashes( $rs->Fields('titlecolor')->Value?$rs->Fields('titlecolor')->Value:'');//Title color
  12. $arr_result[$i]['WenHao '] = addslashes($rs->Fields('OtherText')->Value);//Document number
  13. }

Copy code

Method 2, odbc connection database

  1. $dbhost = '';
  2. $dbuser = ''; //Your mssql username
  3. $dbpass = ''; //Your mssql password
  4. $dbname = ''; //Your mssql library name

  5. $connect=odbc_connect("Driver={SQL Server};Server=$dbhost;Database=$dbname","$dbuser ","$dbpass");

  6. /*Example test*/
  7. $sql="select * from content";
  8. $exec=odbc_exec($connect,$sql);
  9. while($row = (odbc_fetch_array($exec )))
  10. {
  11. $row['id'] //Get field value
  12. ...
  13. }

Copy code

Method 3, PHP built-in function connection: Open the php.ini file on the server with php5 and apache. Remove the semicolon ";" in front of ;extension=php_mysql.dll. Restart the apache server.

  1. $dbh=mysql_connect("hostname","user","password");
  2. mssql_select_db("mydb", $dbh);
  3. ?>
Copy code

Method 4, connect Access data method

  1. $db=$_SERVER['DOCUMENT_ROOT']."/PHP_ACCESS/include/#mydb.mdb"; //It is best to use $_SERVER['DOCUMENT_ROOT'] to get the path here
  2. $conn = new COM('ADODB.Connection') or die('can not start Active X Data Objects');
  3. $conn->Open("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ= $db");
  4. $rs = $conn->Execute('SELECT * FROM contents order by id desc');
  5. while(!$rs->EOF)
  6. {
  7. echo $rs->Fields[ 'name']->Value;
  8. $rs->MoveNext();
  9. }
  10. /*Release resources*/
  11. $rs->Close();
  12. $conn->Close();
  13. $ rs = null;
  14. $conn = null;
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn