English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
mysqli_stmt_prepare()函数为执行准备一个 SQL 语句
mysqli_stmt_prepare()函数准备执行一条SQL语句,您可以使用参数标记(“?”)。在此查询中,为它们指定值,并在以后执行。
mysqli_stmt_prepare($stmt, $str);
序号 | 参数及说明 |
---|---|
1 | stmt(必需) 这是一个表示语句的对象(由mysqli_stmt_init()函数返回)。 |
2 | str(必需) 这是指定所需查询的字符串值。 |
此函数返回布尔值,如果成功,则返回true;如果失败,则返回false。
此函数最初是在PHP版本5中引入的,并且可以在所有更高版本中使用。
以下示例演示了mysqli_stmt_prepare()函数的用法(面向过程风格)-
<?php $con = mysqli_connect("localhost", "root", "password", "mydb"); $query = "CREATE TABLE Test(Name VARCHAR(255), AGE INT)"; mysqli_query($con, $query); print("Creating table.....\n"); //Initialize statement $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("Inserting records....."); //Execute statement mysqli_stmt_execute($stmt); //End statement mysqli_stmt_close($stmt); //Close connection mysqli_close($con); ?>
Output results
Creating table..... Inserting records.....
在面向对象风格中,此函数的语法为$stmt-> prepare();。以下是对面向对象风格中此函数的示例;
<?php $con = new mysqli("localhost", "root", "password", "mydb"); $query = "CREATE TABLE Test(Name VARCHAR(255), AGE INT)"; $con->query($query); print("Creating table.....\n"); //Initialize statement $stmt = $con->stmt_init(); $stmt->prepare("INSERT INTO Test values(?, ?)"); $stmt->bind_param("si", $Name, $Age); $Name = 'Raju'; $Age = 25; print("Inserting records....."); //Execute statement $stmt->execute(); //End statement $stmt->close(); //Close connection $con->close(); ?>
Output results
Creating table..... Inserting records.....
Let's see another example of using this function with SELECT query (object-oriented style)-
<?php //Establish connection $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("Creating table.....\n"); $con -> query("INSERT INTO myplayers values(1, 'Sikhar', 'Dhawan', 'Delhi', 'India')"); $con -> query("INSERT INTO myplayers values(2, 'Jonathan', 'Trott', 'Cape Town', 'South Africa')"); $con -> query("INSERT INTO myplayers values(3, 'Kumara', 'Sangakkara', 'Matale', 'Sri Lanka')"); $con -> query("INSERT INTO myplayers values(4, 'Virat', 'Kohli', 'Delhi', 'India')"); print("Inserting records.....\n"); //Initialize statement object $stmt = $con->stmt_init(); $stmt -> prepare("SELECT * FROM myplayers WHERE country=?); $stmt -> bind_param("s", $country); $country = "India"; //Execute statement $stmt->execute(); //End statement $stmt->close(); //Close connection $con->close(); ?>
Output results
Creating table..... Inserting records.....