Reputation: 73
I have search for bind parameters. But it just getting me confused. I'm really a beginner in php and mysql.
here is code:
$query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' where rating_id='".$_POST['id']."'";
$result = $conn->query($query);
I wonder if how can i apply the bind parameters method in this sample query. Thanks for you response.
Thanks for all the responses. My code works
update.php
$sql = "UPDATE table_user_skills SET rating=? WHERE rating_id=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param('sd', $myrate, $myrateid);
$stmt->execute();
if ($stmt->errno) {
echo "Error" . $stmt->error;
}
else print 'Your rate is accepted.';
$stmt->close();
Upvotes: 2
Views: 18614
Reputation: 11943
When you write the query, leave the values (the $_POST
variables) out of the SQL code and in their place use a placeholder. Depending on which interface you're using in PHP to talk to your MySQL database (there's MySQLi and PDO), you can use named or unnamed place holders in their stead.
$query = "UPDATE table_user_skills SET rating= :ratings where rating_id= :id";
$stmt = $conn->prepare($query);
$stmt->execute($_POST);
What we've done here is send the SQL code to MySQL (using the PDO::prepare method) to get back a PDOStatement object (denoted by $stmt
in the above example). We can then send the data (your $_POST
variables) to MySQL down a separate path using PDOStatement::execute. Notice how the placeholders in the SQL query are named as you expect your $_POST
variables. So this way the SQL code can never be confused with data and there is no chance of SQL injection.
Please see the manuals for more detailed information on using prepared statements.
Upvotes: 2