mysqli_stmt_prepare()函數(shù)為執(zhí)行準(zhǔn)備一個 SQL 語句
mysqli_stmt_prepare()函數(shù)準(zhǔn)備執(zhí)行一條SQL語句,您可以使用參數(shù)標(biāo)記(“?”)。 在此查詢中,為它們指定值,并在以后執(zhí)行。
mysqli_stmt_prepare($stmt, $str);
序號 | 參數(shù)及說明 |
---|---|
1 | stmt(必需) 這是一個表示語句的對象(由mysqli_stmt_init()函數(shù)返回)。 |
2 | str(必需) 這是指定所需查詢的字符串值。 |
此函數(shù)返回布爾值,如果成功,則返回true;如果失敗,則返回false。
此函數(shù)最初是在PHP版本5中引入的,并且可以在所有更高版本中使用。
以下示例演示了mysqli_stmt_prepare()函數(shù)的用法(面向過程風(fēng)格)-
<?php $con = mysqli_connect("localhost", "root", "password", "mydb"); $query = "CREATE TABLE Test(Name VARCHAR(255), AGE INT)"; mysqli_query($con, $query); print("創(chuàng)建表.....\n"); //初始化語句 $stmt = mysqli_stmt_init($con); mysqli_stmt_prepare($stmt, "INSERT INTO Test values(?, ?)"); mysqli_stmt_bind_param($stmt, "si", $Name, $Age); $Name = 'Raju'; $Age = 25; print("插入記錄....."); //執(zhí)行語句 mysqli_stmt_execute($stmt); //結(jié)束語句 mysqli_stmt_close($stmt); //關(guān)閉連接 mysqli_close($con); ?>
輸出結(jié)果
創(chuàng)建表..... 插入記錄.....
在面向?qū)ο箫L(fēng)格中,此函數(shù)的語法為$stmt-> prepare();。以下是面向?qū)ο箫L(fēng)格中此函數(shù)的示例;
<?php $con = new mysqli("localhost", "root", "password", "mydb"); $query = "CREATE TABLE Test(Name VARCHAR(255), AGE INT)"; $con->query($query); print("創(chuàng)建表.....\n"); //初始化語句 $stmt = $con->stmt_init(); $stmt->prepare("INSERT INTO Test values(?, ?)"); $stmt->bind_param("si", $Name, $Age); $Name = 'Raju'; $Age = 25; print("插入記錄....."); //執(zhí)行語句 $stmt->execute(); //結(jié)束語句 $stmt->close(); //關(guān)閉連接 $con->close(); ?>
輸出結(jié)果
創(chuàng)建表..... 插入記錄.....
讓我們看看是此函數(shù)使用SELECT查詢(面向?qū)ο箫L(fēng)格)的另一個示例-
<?php //建立連接 $con = new mysqli("localhost", "root", "password", "mydb"); $con -> query("CREATE TABLE myplayers(ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Place_Of_Birth VARCHAR(255), Country VARCHAR(255))"); print("創(chuàng)建表.....\n"); $con -> query("INSERT INTO myplayers values(1, 'Sikhar', 'Dhawan', 'Delhi', 'India')"); $con -> query("INSERT INTO myplayers values(2, 'Jonathan', 'Trott', 'CapeTown', 'SouthAfrica')"); $con -> query("INSERT INTO myplayers values(3, 'Kumara', 'Sangakkara', 'Matale', 'Srilanka')"); $con -> query("INSERT INTO myplayers values(4, 'Virat', 'Kohli', 'Delhi', 'India')"); print("插入記錄.....\n"); //初始化語句對象 $stmt = $con->stmt_init(); $stmt -> prepare("SELECT * FROM myplayers WHERE country=?"); $stmt -> bind_param("s", $country); $country = "India"; //執(zhí)行語句 $stmt->execute(); //結(jié)束語句 $stmt->close(); //關(guān)閉連接 $con->close(); ?>
輸出結(jié)果
創(chuàng)建表..... 插入記錄.....