簡體   English   中英

為什么這個PHP腳本不能在MySQL數據庫中插入表單數據?

[英]Why won't this PHP script insert form data in MySQL db?

在提交表單時,我得到一個空白頁(insert.php),沒有錯誤,也沒有成功消息。

形式如下:

<form action="insert.php" method="post">
Firstname: <input type="text" name="first_name" id="first_name" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>

這是腳本:

mysql_select_db("my_db", $con);


$stmt = $db->prepare('INSERT INTO my_table (first_name) VALUES (:first_name)');

$stmt->execute(':first_name', $first_name);


if (!mysql_query($stmt,$con))
  {
  die('Error: ' . mysql_error());
  }
echo "1 record added";

mysql_close($con)
?>

您嘗試同時使用2個不同的MySQL接口。 mysql_*系列函數使用ext/mysql擴展... 准備好的語句PDO 您需要選擇一個。 由於PDO確實是個病態,因此請舉一個例子:

$db = new PDO($dsn, $user, $password);

try {
   $stmt = $db->prepare('INSERT INTO my_table (first_name) VALUES (:first_name)');
   if($stmt->execute(array(':first_name' => $first_name))) {
      echo "1 record added";
   }

} catch (PDOException $e) {
  die('Error: ' . $e->getMessage());

}

可以在此處找到Mysql DSN上的文檔( PDO構造函數的第一個參數)。

您需要創建一個PDO對象才能使用准備好的語句。 相反,您已經使用mysql_connect()打開了一個連接。 兩者不要混用,在它們之間最好使用PDO,因為通過使用准備好的語句(除其他原因外)更容易確保PDO的安全。

PDO文檔:

// This establishes your connection using PDO.
// The PDO connection object is $db

/* Connect to an ODBC database using driver invocation */
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';

try {
    $db = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}

將關聯數組傳遞給execute() ,而不是代表占位符的參數列表。

// Now that the PDO object is successfully created, prepare your statement
$stmt = $db->prepare('INSERT INTO my_table (first_name) VALUES (:first_name)');

// Arg to execute() should be an associative array
$stmt->execute(array(':first_name' => $first_name));

不需要對mysql_query()以下調用,因為您已經使用PDO執行了prepared語句。

// Don't do this
// mysql_select_db("my_db", $con);

// Or this...
//if (!mysql_query($stmt,$con))
//{
//  die('Error: ' . mysql_error());
//}

// Or this...
// mysql_close($con)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM