1. 程式人生 > >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';//要查詢的使用者名稱,一般是使用者輸入的資訊
$insertName = 'testname';

$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 Age: $age \n";
}

//新增記錄
$insertName = mysql_real_escape_string($insertName);//防止SQL注入
$insertSql = "insert into user(name, age) values('$insertName', 18)";
$result = mysql_query($insertSql);
echo $result . "\n";


//更新記錄
$updateSql = "update user set age = 19 where name='$insertName'";
$result = mysql_query($updateSql);
echo $result . "\n";

//刪除記錄
$deleteSql = "delete from user where age = 19";
$result = mysql_query($deleteSql);
echo $result . "\n";

mysql_close($connection);//關閉連線

複製程式碼

其執行結構如下:

Name: harry Age: 20 
Name: harry Age: 24 
1
1
1

第二種時使用mysqli擴充套件去連結資料庫,程式碼如下:

複製程式碼

<?php
$host = 'localhost';
$database = 'test';
$username = 'root';
$password = 'root';
$selectName = 'harry';//要查詢的使用者名稱,一般是使用者輸入的資訊
$insertName = 'testname';

// 建立物件並開啟連線,最後一個引數是選擇的資料庫名稱
$mysqli = new mysqli($host, $username, $password, $database);

// 編碼轉化為 utf8
if (!$mysqli->set_charset("utf8")) {
    printf("Error loading character set utf8: %s\n", $mysqli->error);
} else {
    printf("Current character set: %s\n", $mysqli->character_set_name());
}

if (mysqli_connect_errno()) {
    // 診斷連線錯誤
    die("could not connect to the database.\n" . mysqli_connect_error());
}

$selectedDb = $mysqli->select_db($database);//選擇資料庫
if (!$selectedDb) {
    die("could not to the database\n" . mysql_error());
}

if ($stmt = $mysqli->prepare("select * from user where name = ?")) {
    /* bind parameters for markers */
    $stmt->bind_param("s", $selectName);
    /* execute query */
    $stmt->execute();
    /* bind result variables */
    $stmt->bind_result($name, $age);

    /* fetch values */
    while ($stmt->fetch()) {
        echo "Name: $name Age: $age \n";
    }
    /* close statement */
    $stmt->close();
}

//新增記錄
if ($insertStmt = $mysqli->prepare("insert into user(name, age) values(?, 18)")) {
    /* bind parameters for markers */
    $insertStmt->bind_param("s", $insertName);
    /* execute query */
    $insertStmt->execute();
    echo $insertStmt->affected_rows . "\n";
    /* close statement */
    $insertStmt->close();
}

//更新記錄
if ($updateStmt = $mysqli->prepare("update user set age = 19 where name=?")) {
    /* bind parameters for markers */
    $updateStmt->bind_param("s", $insertName);
    /* execute query */
    $updateStmt->execute();
    echo $updateStmt->affected_rows . "\n";
    /* close statement */
    $updateStmt->close();
}

//刪除記錄
$result = $mysqli->query("delete from user where age = 19");
echo $result . "\n";

$mysqli->close();//關閉連線

複製程式碼

其結果與第一種相同。

其實mysqli提供了兩種方式連結資料庫,一種是面向物件的方式,就是如上的程式碼,另一種是面向過程的方式。可以參考MySQLi擴充套件功能概述學習。

第三種是使用PDO的方式去連線資料庫,程式碼如下:

複製程式碼

<?php
$host = 'localhost';
$database = 'test';
$username = 'root';
$password = 'root';
$selectName = 'harry';//要查詢的使用者名稱,一般是使用者輸入的資訊
$insertName = 'testname';

$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 Age: $age \n";
    }
}

$oldAge = 18;
$insert = $pdo->prepare('insert into user(name, age) values(:name, :age)');
$insert->bindParam(':name', $insertName, PDO::PARAM_STR);
$insert->bindParam(':age', $oldAge, PDO::PARAM_INT);
$result = $insert->execute();
echo $result . "\n";

$newAge = 19;
$update = $pdo->prepare('update user set age = ? where name = ?');
$update->bindParam(1, $newAge, PDO::PARAM_INT);
$update->bindParam(2, $insertName, PDO::PARAM_STR);
$result = $update->execute();
echo $result . "\n";

$delete = $pdo->prepare('delete from user where age = ?');
$result = $delete->execute(array($newAge));
echo $result . "\n";

$pdo = null;//關閉連線

複製程式碼

其結果與第一種相同。

pdo::query()方法
當執行返回結果集的select查詢時,或者所影響的行數無關緊要時,應當使用pdo物件中的query()方法.
如果該方法成功執行指定的查詢,則返回一個PDOStatement物件.
如果使用了query()方法,並想了解獲取資料行總數,可以使用PDOStatement物件中的rowCount()方法獲取.

pdo::exec()方法
當執行insert,update,delete沒有結果集的查詢時,使用pdo物件中的exec()方法去執行.
該方法成功執行時,將返回受影響的行數.注意,該方法不能用於select查詢.

PDO事務:

$pdo->beginTransaction();//開啟事務處理

try{
    //PDO預處理以及執行語句...
    
    $pdo->commit();//提交事務
}catch(PDOException $e){
    $pdo->rollBack();//事務回滾
    
    //相關錯誤處理
    throw $e;
}