php銜接MySQL的兩種方法比較。本站提示廣大學習愛好者:(php銜接MySQL的兩種方法比較)文章只能為提供參考,不一定能成為您想要的結果。以下是php銜接MySQL的兩種方法比較正文
記載一下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有所贊助。