我目前有一个Get varible
$name = $_GET['user'];
Run Code Online (Sandbox Code Playgroud)
我试图将它添加到我的sql语句中,如下所示:
$sql = "SELECT * FROM uc_users WHERE user_name = ". $name;
Run Code Online (Sandbox Code Playgroud)
并运行
$result = $pdo -> query($sql);
Run Code Online (Sandbox Code Playgroud)
我收到一个无效的列名.但这没有意义,因为如果我手动提出这样的请求
$sql = "SELECT * FROM uc_users WHERE user_name = 'jeff'";
Run Code Online (Sandbox Code Playgroud)
我得到列数据,而不是当我将其作为get变量输入时.我究竟做错了什么.我对pdo比较新.
更新:现在我有以下内容:
$name = $_GET['user'];
Run Code Online (Sandbox Code Playgroud)
和
$sql = "SELECT * FROM uc_users WHERE user_name = :name";
//run the query and save the data to the $bio variable
$result = $pdo -> query($sql);
$result->bindParam( ":name", $name, PDO::PARAM_STR );
$result->execute();
Run Code Online (Sandbox Code Playgroud)
但我得到了
> SQLSTATE[42000]: Syntax error or access violation: 1064 You have an
> error in your SQL syntax; check the manual that corresponds to your
> MySQL server version for the right syntax to use near ':name' at line
> 1
Run Code Online (Sandbox Code Playgroud)
对于使用变量工作的查询,就像没有变量的变量一样,您需要在变量周围加上引号,因此请将查询更改为:
$sql = "SELECT * FROM uc_users WHERE user_name = '$name'";
Run Code Online (Sandbox Code Playgroud)
但是,这很容易受到SQL注入的影响,所以你真正想要的是使用占位符,如下所示:
$sql = "SELECT * FROM uc_users WHERE user_name = :name";
Run Code Online (Sandbox Code Playgroud)
然后像你一样准备它:
$result = $pdo->prepare( $sql );
Run Code Online (Sandbox Code Playgroud)
接下来,绑定参数:
$result->bindParam( ":name", $name, PDO::PARAM_STR );
Run Code Online (Sandbox Code Playgroud)
最后,执行它:
$result->execute();
Run Code Online (Sandbox Code Playgroud)