記錄一下PHP串連MySQL的兩種方式。
先mock一下資料,可以執行一下sql。
/*建立資料庫*/CREATE DATABASE IF NOT EXISTS `test`;/*選擇資料庫*/USE `test`;/*建立表*/CREATE TABLE IF NOT EXISTS `user` ( name varchar(50), age int);/*插入測試資料*/INSERT INTO `user` (name, age) VALUES('harry', 20), ('tony', 23), ('harry', 24);
第一種是使用PHP原生的方式去串連資料庫。代碼如下:
<?php$host = 'localhost';$database = 'test';$username = 'root';$password = 'root';$selectName = 'harry';//要尋找的使用者名稱,一般是使用者輸入的資訊$connection = mysql_connect($host, $username, $password);//串連到資料庫mysql_query("set names 'utf8'");//編碼轉化if (!$connection) { die("could not connect to the database.\n" . mysql_error());//診斷串連錯誤}$selectedDb = mysql_select_db($database);//選擇資料庫if (!$selectedDb) { die("could not to the database\n" . mysql_error());}$selectName = mysql_real_escape_string($selectName);//防止SQL注入$query = "select * from user where name = '$selectName'";//構建查詢語句$result = mysql_query($query);//執行查詢if (!$result) { die("could not to the database\n" . mysql_error());}while ($row = mysql_fetch_row($result)) { //取出結果並顯示 $name = $row[0]; $age = $row[1]; echo "Name: $name "; echo "Age: $age "; echo "\n";}
其運行結構如下:
Name: harry Age: 20
Name: tony Age: 23
第二種是使用PDO的方式去串連資料庫,代碼如下:
<?php$host = 'localhost';$database = 'test';$username = 'root';$password = 'root';$selectName = 'harry';//要尋找的使用者名稱,一般是使用者輸入的資訊$pdo = new PDO("mysql:host=$host;dbname=$database", $username, $password);//建立一個pdo對象$pdo->exec("set names 'utf8'");$sql = "select * from user where name = ?";$stmt = $pdo->prepare($sql);$rs = $stmt->execute(array($selectName));if ($rs) { // PDO::FETCH_ASSOC 關聯陣列形式 // PDO::FETCH_NUM 數字索引數組形式 while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { $name = $row['name']; $age = $row['age']; echo "Name: $name "; echo "Age: $age "; echo "\n"; }}$pdo = null;//關閉串連
其結果與第一種相同。
以上所述就是本文的全部內容了,希望能夠對大家熟練掌握mysql有所協助。