PHP mysqli_prepare() 函式



定義和用法

mysqli_prepare() 函式準備一條SQL語句以供執行,你可以在查詢中使用引數標記(“?”),為其指定值,然後稍後執行。

語法

mysqli_prepare($con, $str);

引數

序號 引數及描述
1

con(必填)

這是一個表示與MySQL伺服器連線的物件。

2

str(必填)

這是一個字串值,指定所需的查詢。

返回值

如果成功,此函式返回一個語句物件;如果失敗,則返回false

PHP 版本

此函式首次在PHP 5版本中引入,並在所有後續版本中均有效。

示例

以下示例演示了mysqli_prepare()函式的用法(過程式風格)−

<?php
   $con = mysqli_connect("localhost", "root", "password", "mydb");

   $query = "CREATE TABLE Test(Name VARCHAR(255), AGE INT)"; 
   mysqli_query($con, $query);
   print("Table Created.....\n");

   $stmt = mysqli_prepare($con, "INSERT INTO Test values(?, ?)");
   mysqli_stmt_bind_param($stmt, "si", $Name, $Age);
   $Name = 'Raju';
   $Age = 25;
   print("Record Inserted.....");

   //Executing the statement
   mysqli_stmt_execute($stmt);

   //Closing the statement
   mysqli_stmt_close($stmt);

   //Closing the connection
   mysqli_close($con);
?>

這將產生以下結果 −

Table Created.....
Record Inserted.....

如果你驗證表的內容如下所示 $minus;

mysql> select * from test;
+------+------+
| Name | AGE  |
+------+------+
| Raju |   25 |
+------+------+
1 row in set (0.00 sec)

示例

在面向物件風格中,此函式的語法為$con->prepare();以下是此函式在面向物件風格中的示例 $minus;

<?php
   //Creating a connection
   $con = new mysqli("localhost", "root", "password", "mydb");

   $query = "CREATE TABLE Test(Name VARCHAR(255), AGE INT)"; 
   $con -> query($query);
   print("Table Created.....\n");

   $stmt = $con -> prepare( "INSERT INTO Test values(?, ?)");
   $stmt -> bind_param("si", $Name, $Age);
   $Name = 'Raju';
   $Age = 25;
   print("Record Inserted.....");

   //Executing the statement
   $stmt->execute();

   //Closing the statement
   $stmt->close();

   //Closing the connection
   $con->close();
?>

這將產生以下結果 −

Table Created.....
Record Inserted.....
php_function_reference.htm
廣告