如何在mysql查询中绑定参数? [英] How to bind parameters in mysql query?

查看:378
本文介绍了如何在mysql查询中绑定参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在搜索绑定参数.但这让我感到困惑.我真的是php和mysql的初学者.

I have search for bind parameters. But it just getting me confused. I'm really a beginner in php and mysql.

这是代码:

$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();

推荐答案

在编写查询时,请将值( $_POST变量)保留在SQL代码之外,并代替其使用一个占位符.根据您在PHP中使用哪种接口与MySQL数据库进行通讯(有 MySQLi PDO ),则可以代替使用已命名或未命名的占位符.

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);

我们在这里所做的是使用 PDO :: prepare将SQL代码发送到MySQL( 方法)以获取 PDOStatement 对象(由在上面的示例中).然后,我们可以使用

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.

这篇关于如何在mysql查询中绑定参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆