日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

php mysql 连接方法 对比_Mysql实例php连接MySQL的两种方式对比

發(fā)布時間:2024/4/11 数据库 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 php mysql 连接方法 对比_Mysql实例php连接MySQL的两种方式对比 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

《Mysql實例php連接MySQL的兩種方式對比》要點:

本文介紹了Mysql實例php連接MySQL的兩種方式對比,希望對您有用。如果有疑問,可以聯(lián)系我們。

MYSQL數(shù)據(jù)庫記錄一下PHP連接MySQL的兩種方式.

MYSQL數(shù)據(jù)庫先mock一下數(shù)據(jù),可以執(zhí)行一下sql.

MYSQL數(shù)據(jù)庫

/*創(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);

MYSQL數(shù)據(jù)庫第一種是使用PHP原生的方式去連接數(shù)據(jù)庫.代碼如下:

MYSQL數(shù)據(jù)庫

$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'";//構(gòu)建查詢語句

$result = mysql_query($query);//執(zhí)行查詢

if (!$result) {

die("could not to the database\n" . mysql_error());

}

while ($row = mysql_fetch_row($result)) {

//取出結(jié)果并顯示

$name = $row[0];

$age = $row[1];

echo "Name: $name ";

echo "Age: $age ";

echo "\n";

}

MYSQL數(shù)據(jù)庫其運行結(jié)構(gòu)如下:

MYSQL數(shù)據(jù)庫Name: harry Age: 20

Name: tony Age: 23

第二種是使用PDO的方式去連接數(shù)據(jù)庫,代碼如下:

MYSQL數(shù)據(jù)庫

$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 關(guān)聯(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;//關(guān)閉連接

MYSQL數(shù)據(jù)庫其結(jié)果與第一種相同.

MYSQL數(shù)據(jù)庫以上所述就是本文的全部內(nèi)容了,希望能夠?qū)Υ蠹沂炀氄莆誱ysql有所幫助.

總結(jié)

以上是生活随笔為你收集整理的php mysql 连接方法 对比_Mysql实例php连接MySQL的两种方式对比的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。