PHP Prepared Statement for Database Updates
This discussion centers around the proper utilization of prepared statements in PHP to prevent vulnerabilities like SQL injections. The purpose of the code block in question is to update a database table with a single field using a prepared statement.
In the provided code, the update() method in the class.Scripts.inc file employs a prepared statement in an attempt to update the datadump table. However, the execution is unsuccessful due to an incorrect parameter order during the bind_param() method. The current code binds the parameters in the order of $id and $content, while the SQL statement expects them in the opposite order, leading to incorrect record identification and zero rows being affected.
The corrected code below rectifies this error by binding the parameters in the correct order and providing additional error handling:
$stmt = $this->mysqli->prepare("UPDATE datadump SET content=? WHERE id=?");
/* Always check whether the prepare() succeeded */
if ($stmt === false) {
trigger_error($this->mysqli->error, E_USER_ERROR);
return;
}
$id = 1;
/* Bind our params */
/* Bind variables in the same order as SQL params */
$stmt->bind_param('si', $content, $id);
/* Set our params */
/* No escaping needed when using prepared statements */
$content = $_POST['content'] ?: '';
/* Execute the prepared Statement */
$status = $stmt->execute();
/* Always check whether the execute() succeeded */
if ($status === false) {
trigger_error($stmt->error, E_USER_ERROR);
}
printf("%d Row inserted.\n", $stmt->affected_rows);
Regarding your specific inquiries:
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3