PHP mysqli 预处理

创建数据库test和对应的表test,通过预处理向test表中插入多条数据。
代码如下:


    //  使用预处理操作数据库
    $dbServer = "localhost:3306";
    $dbUser = "root";
    $dbPass = "";
    $dbName = "test";

    //  创建连接
    $conn = new mysqli($dbServer, $dbUser, $dbPass, $dbName);
    if ($conn->connect_error)
        die("连接失败:" . $conn->connect_error);
    else
        echo "连接成功!
"
; // 创建表 $sql = "CREATE TABLE test ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, age int(8) UNSIGNED NOT NULL, email VARCHAR(50) )"; if ($conn->query($sql) == TRUE) echo "数据表创建成功。
"
; else echo "数据表创建失败:" . $conn->error . "
"
; // 创建预处理对象 $sql = "INSERT INTO test (firstname, lastname, age, email) VALUES (?, ?, ?, ?)"; $info = array(1 => array('firstname'=>'kobe', 'lastname'=>'bryant', 'age'=>30, 'email'=>"[email protected]"), 2 => array('firstname'=>'yao', 'lastname'=>'ming', 'age'=>20, 'email'=>"[email protected]")); $stmt = $conn->prepare($sql) or die($conn->error); foreach ($info as $num => $value) { // 参数绑定: ssis代表,第一个、第二个、第三个参数是string类型,第四个参数是int类型 $stmt->bind_param('ssis', $value['firstname'], $value['lastname'], $value['age'], $value['email']); if (!$stmt->execute()) die("插入失败:" . $conn->error . "
"
); } echo "插入成功
"
; $stmt->close(); $sql = "SELECT * FROM test"; $result = $conn->query($sql); if ($result->num_rows > 0){ // 输出每行数据 echo "查询结果 :
"
; while($row = $result->fetch_assoc()){ echo "id: " . $row["id"] . " ; firstname: " . $row["firstname"] . " ; lastname : " . $row["lastname"] . " ; age : " . $row["age"] . " ; email : " . $row["email"] . "
"
; } } else echo "0个结果"; // 关闭连接 $conn->close(); ?>

运行结果如下:
PHP mysqli 预处理_第1张图片

你可能感兴趣的:(PHP,数据库)