[英]PHP Update doesn't Update
該查詢在mysql中運行,提交時沒有捕獲,但數據未更新。 有什么建議為什么不起作用甚至如何調試呢?
<?php
if( $_SERVER['REQUEST_METHOD'] == "POST" )
{
// var_dump($_POST["first_name"]);
try
{
// this needs to be a lot more secure!
// read PDO manual
$id = $_GET['id'];
// $description = $_POST["description"];
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$description = $_POST["description"];
$sql = $db->prepare("UPDATE `exhibitors` SET first_name = '$first_name' WHERE id = '52'");
$update = $db->query($sql);
}
catch ( Exception $e )
{
echo " Data could not be updated from the database.";
}
}
和連接:
<?php
try
{
$db = new PDO("mysql:host=localhost;dbname=openstudios;port=8889","root","root");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
// var_dump($db);
}
catch ( Exception $e )
{
echo "Could not connect to the database.";
exit;
}
您在此處未正確使用prepare()
(或query()
)。 prepare()
用於創建與execute()
一起運行的“ prepared statement”,而query()
用於運行SQL查詢字符串。
不要將$_POST
值連接到查詢字符串中,這是您進行SQL注入的方式。 您將忽略使用准備好的語句的全部要點 。
這是針對MySQLi的:
$id = $_GET['id'];
// $description = $_POST["description"];
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$description = $_POST["description"];
$sql = $db->prepare("UPDATE `exhibitors` SET first_name = ? WHERE id = ?");
$sql->bind_param('sd', $first_name, $id);
$sql->execute();
參見文檔: http : //php.net/manual/en/mysqli.prepare.php
如果您使用的是PDO,語法會有所不同
$id = $_GET['id'];
// $description = $_POST["description"];
$first_name = $_POST["first_name"];
$last_name = $_POST["last_name"];
$description = $_POST["description"];
$sql = $db->prepare("UPDATE `exhibitors` SET first_name = :first_name WHERE id = :id");
$sql->execute(array(
'first_name' => $first_name,
'id' => $id
));
對於准備好的語句,您應該使用這樣的內容
$sql = $db->prepare('UPDATE exhibitors SET first_name = :first_name WHERE id = :id');
$sql->execute(array('first_name' => $first_name,'id' => 52));
萬一您只想使用查詢語句(不應該使用此語句,可以接受SQL注入)
$db->query("UPDATE exhibitors SET first_name = '$first_name' WHERE id = 52");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.