Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
559 views
in Technique[技术] by (71.8m points)

php - How to bind parameters in mysql query?

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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Here's an example using PDO

$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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...