国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數(shù)據(jù)庫 > MySQL > 正文

php連接MySQL的兩種方式對比

2024-07-24 12:46:18
字體:
供稿:網(wǎng)友

記錄一下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());//診斷連接錯(cuò)誤}$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";}

其運(yùn)行結(jié)構(gòu)如下:

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)建一個(gè)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)閉連接

其結(jié)果與第一種相同。

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

您可能感興趣的文章:

在php和MySql中計(jì)算時(shí)間差的方法詳解在php和MySql中計(jì)算時(shí)間差的方法利用php+mysql來做一個(gè)功能強(qiáng)大的在線計(jì)算器php實(shí)現(xiàn)只保留mysql中最新1000條記錄php實(shí)現(xiàn)mysql數(shù)據(jù)庫分表分段備份php使用MySQL保存session會話的方法php 在線導(dǎo)入mysql大數(shù)據(jù)程序PHP中常用的幾個(gè) mysql操作php簡單操作mysql數(shù)據(jù)庫的類php計(jì)算整個(gè)mysql數(shù)據(jù)庫大小的方法
發(fā)表評論 共有條評論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 偃师市| 鹤山市| 陵川县| 湘乡市| 且末县| 建湖县| 莎车县| 孝义市| 松溪县| 玛曲县| 桦川县| 文登市| 繁昌县| 河南省| 张掖市| 张家川| 射洪县| 湖口县| 乌拉特后旗| 黄骅市| 南岸区| 慈利县| 威远县| 遵义县| 忻州市| 区。| 舟曲县| 凤庆县| 喜德县| 武冈市| 汝阳县| 西乌珠穆沁旗| 耒阳市| 大洼县| 麟游县| 常州市| 安吉县| 莱阳市| 扶风县| 湟中县| 云龙县|