将PHP变量放在SQL中

时间:2015-10-23 12:40:27

标签: mysql

我正在尝试将城市从一个页面发送到另一个页面,然后显示来自数据库的项目,其中city是所提及的城市,但此代码不会返回任何结果。请指导。我相信其他所有代码都没问题。

$city = $_POST["city"];
$sql = "SELECT id,full_name, email, password,full_address,city,age,contact_number,gender,education FROM users WHERE city=$city";

2 个答案:

答案 0 :(得分:0)

实际上,你甚至没有在你的mysql服务器上执行请求,但是如果你正在使用PDO(你应该做什么),那就做这样的事情:

<?php
$bdd = new PDO(etc);
$req = $bdd->prepare("SELECT id,full_name, email, password,full_address,city,age,contact_number,gender,education FROM users WHERE city=?");
$req->execute(array($_POST['city']));
print_r($req->fetchAll());
?>

在这里,$ req-&gt; fetchAll()将返回一个数组,其中包含您的请求返回的每个元素,最好的部分是prepare将阻止您进入每个SQLi

编辑:你可以使用数组[$ _POST ['city']]的短语法或旧的和完整的语法:array($ _ POST ['city'])

答案 1 :(得分:0)

// strip tags from the input
$city = strip_tags($_POST["city"]);

// escape the input to prevent sql injection (assuming you are using mysqli() as your connection method...)
$city = mysqli_real_escape_string($city);

// your query does not work because you need to put strings inside single quotes
$sql = "SELECT id,full_name, email, password,full_address,city,age,contact_number,gender,education FROM users WHERE city='$city'";