一些简单的PHP连接数据库例子详解
连接MySQL数据库的两种方法:
(1)利用PHP的数据库函数连接
此方式是最常用的一种方式,这里主要用到四个数据库函数:
mysql_connect () 建立与MySQL服务器的连接。
mysql_select_db ():选择MySQL服务器中的数据库供以后的数据查询操作query处理。
mysql_query ():送出query字符串以帮助MySQL做相关的处理或执行。
mysql_fetch_row ():用来将查询结果result单行移到数组变量中,数组的索引是数字
(2)通过ODBC连接
PHP通过ODBC连接MySQL数据库主要用到四个函数:
Odbc_connect ():用来同ODBC数据源建立连接.
Odbc_do ():用来在建立连接之后执行数据库查询.
Odbc_result():用于取得当前记录行中某个字段的值.
Odbc_fetch_row ():用来把查询结果保存到数组,每个数组元素对应一条记录.
我们先来看PHP的数据库函数连接,方法实例,连接到一个 MySQL 数据库,在您能够访问并处理数据库中的数据之前,您必须创建到达数据库的连接,在 PHP 中,这个任务通过 mysql_connect() 函数完成.
语法:mysql_connect(servername,username,password);
参数 描述
servername 可选。规定要连接的服务器。默认是 "localhost:3306"。
username 可选。规定登录所使用的用户名。默认值是拥有服务器进程的用户的名称。
password 可选。规定登录所用的密码。默认是 ""。
PHP实例代码如下:
<?php $con = mysql_connect("localhost","root",""); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_close($con);
面向对象mysqli,代码如下:
<?php $mysqli = new mysqli('localhost','root','','volunteer'); if (mysqli_connect_errno()){ die('Unable to connect!'). mysqli_connect_error(); }
pdo连接mysql,代码如下:
<?php $db = new PDO('mysql:host=localhost;dbname=test', 'root', ''); try { foreach ($db->query('select * from user') as $row){ print_r($row); } $db = null; //关闭数据库 } catch (PDOException $e) { echo $e->getMessage(); }
然后我们还可以使用ODBC连接数据库,代码如下:
<?php require_once './adodb5/adodb.inc.php'; $conn = &ADONewConnection('mysql'); $conn->connect('localhost','root','','test'); $conn->Execute("set names utf8"); $res = $conn->Execute("select * from user"); if (!$res){ echo $conn->ErrorMsg(); }else{ var_dump($res); }
mysql数据连接类,代码如下:
<?php //------------------------------------------------------------------------------------------ // ※Database() 构造函数,数据库初始参数 // ※Select() 查询 // ※GetRows() 返回查询的记录总数 // ※Insert() 插入记录 // ※Update() 更新 // ※Delete() 删除 // ※Halt() 中断并显示错误信息*/ //------------------------------------------------------------------------------------------ define("DATABASETYPE", "1"); //定义数据库类型:1为MySql;2为SQL Server;3为Oracle;4为Odbc define("SERVER", "localhost"); //Host name or IP address of the database server define("DATABASE", "dbName"); //要连接的数据库名 define("USER", "tableName"); //用于连接数据库的用户名 define("PASSWORD", "paswd"); //用于连接数据库的密码 class Database { var $dbLink; //连接句柄 var $result; //查询句柄 var $insId; //Insert()成功返回AUTO_INCREMENT列的值 var $rows; //返回数据数组 var $numRows; //返回数据数目 var $dbHost, $dbUser, $userPassword, $database; var $dbType = DATABASETYPE; var $msgFlag = "yes"; //yes:show the Mysql message ; no: die by show "Halted." function Database($dbHost = SERVER, $dbUser = USER, $userPassword = PASSWORD, $database = DATABASE) { switch ($this->dbType) { case 1: $this->dbLink = @mysql_pconnect($dbHost, $dbUser, $userPassword); // or die("Can't Connect to Remote Host!"); @mysql_select_db($database, $this->dbLink); // or die ("Can't Connect to Remote Host!"); break; case 2: break; } return true; } /* SQL:Select() 返回为false无结果 */ function Select($table, $columns, $condition = 1) { $sql = "select $columns from $table where $condition "; $this->result = @mysql_query($sql, $this->dbLink); unset($this->rows); if ($this->result) { $i = 0; if (!($this->rows = array("$i" => @mysql_fetch_array($this->result)))) return false; if (($this->numRows = @mysql_num_rows($this->result)) == 0) return false; while ($tempRows = @mysql_fetch_array($this->result)) { array_push($this->rows, $tempRows); } } else { $this->Halt($sql); return false; } return true; } /* SQL:GetRows() 返回查询的记录总数 */ function GetRows($table, $condition = 1) { $sql = "select count(1) as count from $table where $condition"; $this->result = @mysql_query($sql, $this->dbLink); if ($this->result) { $temp = @mysql_fetch_array($this->result); $this->numRows = $temp[count]; } else { $this->Halt($sql); return false; } return $this->numRows; } /* SQL:Insert() */ function Insert($table, $columns, $values) { $sql = "insert into $table ($columns) values ($values)"; $this->result = @mysql_query($sql, $this->dbLink); if ($this->result) $this->insId = @mysql_insert_id($this->dbLink); else { $this->Halt($sql); return false; } return true; } /* SQL:Update() */ function Update($table, $setings, $condition) { $sql = "update $table set $setings where $condition"; $this->result = @mysql_query($sql, $this->dbLink); if ($this->result) $this->numRows = @mysql_affected_rows($this->result); else { $this->Halt($sql); return false; } return true; } /* SQL:Delete */ function Delete($table, $condition) { $sql = "delete from $table where $condition"; $this->result = @mysql_query($sql, $this->dbLink); if ($this->result) $this->numRows = @mysql_affected_rows($this->result); else { $this->Halt($sql); return false; } return true; } /* Halt():error message */ function Halt($msg) { if ($this->msgFlag == "yes") { printf("<b>Database Query Error:</b> %s<br>n", $msg); printf("<b>MySql Error:</b> %s<br>n", mysql_error()); }else echo "<META HTTP-EQUIV=REFRESH CONTENT='0;URL=../include/error.htm'>"; //自定一个出错提示文件 return false;//开源代码phprm.com } } switch ($db->dbType) { case 1: @mysql_close(); break; case 2: break; } $db = new Database();
友情提示:如果出现连接mysql数据库中文乱码我们可以在连接数据库查询之前加上mysql_query("set names utf8"); 如果你是gbk就使用gbk编编码了.
本文地址:http://www.phprm.com/develop/fs5250.html
转载随意,但请附上文章地址:-)