當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


PHP mysqli_prepare()用法及代碼示例


定義和用法

這個mysqli_prepare()函數準備執行的 SQL 語句,您可以在此查詢中使用參數標記 ("?"),為其指定值,並稍後執行。

用法

mysqli_prepare($con, $str);

參數

Sr.No 參數及說明
1

con(Mandatory)

這是一個表示與 MySQL 服務器的連接的對象。

2

str(Mandatory)

這是指定所需查詢的字符串值。

返回值

此函數在成功時返回一個語句對象,在失敗時返回 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 mysqli_prepare() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。