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:
<code class="php">$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);</code>
Regarding your specific inquiries:
The above is the detailed content of How to Resolve Incorrect Parameter Order in PHP Prepared Statement Database Updates?. For more information, please follow other related articles on the PHP Chinese website!