准备好的声明
这将是最安全的方法。查看此链接了解更多信息:如何防止 PHP 中的 SQL 注入?
您可能还需要关闭魔术引号,具体取决于您正在运行的 PHP 版本。
<?php
if( isset($_POST['text']) && isset($_GET['id']) &&
is_int($_GET['id']) && $_GET['id']>0 ){
$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = 'UPDATE table SET text = ? WHERE id = ?';
/* prepare your statement safely */
$stmt = $mysqli->prepare($query);
/* bindes variables after statement is prepared */
$stmt->bind_param('si', $_POST['text'], $_GET['id']);
/* execute prepared statement */
$stmt->execute();
/* close statement */
$stmt->close();
/* close connection */
$mysqli->close();
}else
echo 'Error: ID and/or Text are invalid';
?>