php串連MySQL的兩種方式對比_Mysql

來源:互聯網
上載者:User

記錄一下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有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.