php連接MySQL的兩種方式對比
更新時間:2015年04月07日 12:04:24 投稿:hebedich
這篇文章主要介紹了php連接MySQL的兩種方式對比,一種是原生的鏈接方式另外一種是PDO方式,附上示例,推薦給大家,有需要的小伙伴可以參考下
記錄一下PHP連接MySQL的兩種方式。
先mock一下數(shù)據(jù),可以執(zhí)行一下sql。
/*創(chuàng)建數(shù)據(jù)庫*/
CREATE DATABASE IF NOT EXISTS `test`;
/*選擇數(shù)據(jù)庫*/
USE `test`;
/*創(chuàng)建表*/
CREATE TABLE IF NOT EXISTS `user` (
name varchar(50),
age int
);
/*插入測試數(shù)據(jù)*/
INSERT INTO `user` (name, age) VALUES('harry', 20), ('tony', 23), ('harry', 24);
第一種是使用PHP原生的方式去連接數(shù)據(jù)庫。代碼如下:
<?php
$host = 'localhost';
$database = 'test';
$username = 'root';
$password = 'root';
$selectName = 'harry';//要查找的用戶名,一般是用戶輸入的信息
$connection = mysql_connect($host, $username, $password);//連接到數(shù)據(jù)庫
mysql_query("set names 'utf8'");//編碼轉(zhuǎn)化
if (!$connection) {
die("could not connect to the database.\n" . mysql_error());//診斷連接錯誤
}
$selectedDb = mysql_select_db($database);//選擇數(shù)據(jù)庫
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);//執(zhí)行查詢
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的方式去連接數(shù)據(jù)庫,代碼如下:
<?php
$host = 'localhost';
$database = 'test';
$username = 'root';
$password = 'root';
$selectName = 'harry';//要查找的用戶名,一般是用戶輸入的信息
$pdo = new PDO("mysql:host=$host;dbname=$database", $username, $password);//創(chuàng)建一個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 關聯(lián)數(shù)組形式
// PDO::FETCH_NUM 數(shù)字索引數(shù)組形式
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$name = $row['name'];
$age = $row['age'];
echo "Name: $name ";
echo "Age: $age ";
echo "\n";
}
}
$pdo = null;//關閉連接
其結果與第一種相同。
以上所述就是本文的全部內(nèi)容了,希望能夠?qū)Υ蠹沂炀氄莆誱ysql有所幫助。
相關文章
MySQL中datetime和timestamp的區(qū)別及使用詳解
這篇文章主要介紹了MySQL中datetime和timestamp的區(qū)別及使用詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-11-11
Mysql BinLog存儲機制與數(shù)據(jù)恢復方式
這篇文章主要介紹了Mysql BinLog存儲機制與數(shù)據(jù)恢復方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-06-06
MySQL加減間隔時間函數(shù)DATE_ADD和DATE_SUB的實現(xiàn)
mysql中內(nèi)置函數(shù)date_add 和 date_sub能對指定的時間進行增加或減少一個指定的時間間隔,本文主要介紹了MySQLDATE_ADD和DATE_SUB的實現(xiàn),感興趣的可以了解一下2024-09-09

