选择查询有问题

时间:2016-08-09 17:13:31

标签: php mysql sql

我有一个问题,我确定是正确的,但唉,它不是。而且据说我对导致这个问题的原因感到不知所措。这是我的PHP脚本。

$con = mysqli_connect($DB_HOST,$DB_USER,$DB_PASSWORD,$DB_DATABASE);
if(!$con){
echo "Connection Error...".mysqli_connect_error();
}
else
{
 echo "Database connection Success...";
}

$user_name = $_POST["login_name"];
$user_pass = $_POST["login_pass"];

$sql_query = "SELECT name from user_info where user_name like '$user_name'
and user_pass like '$user_pass'";
$result = mysqli_query($con,$sql_query);

if(mysqli_num_rows($result)>0)
{
$row = mysqli_fetch_assoc($result);
$name = $row ["name"];
echo "Hello welcome".$name;

}

 else {
 echo "No user found";

 }




 ?>

3 个答案:

答案 0 :(得分:2)

你还没有报价!记住$query是一个字符串!

$con = mysqli_connect($DB_HOST,$DB_USER,$DB_PASSWORD,$DB_DATABASE);

if(!$con) {
echo "Connection Error...".mysqli_connect_error();
} else {
 echo "Database connection Success...";
}

$user_name = $_POST["login_name"];
$user_pass = $_POST["login_pass"];

$sql_query = "SELECT name from user_info WHERE user_name like '$user_name'
and user_pass like '$user_pass'";
$result = mysqli_query($con,$sql_query);

if(mysqli_num_rows($result)>0) {
  $row = mysqli_fetch_assoc($result);
  $name = $row ["name"];
  echo "Hello welcome".$name; 
} else {
  echo "No user found";
}

答案 1 :(得分:0)

您忘记将查询字符串包装在引号中。 您正在PHP变量中编写查询,因此必须用引号括起来。

$sql_query = "SELECT name from user_info where user_name like '{$user_name}' and user_pass like '{$user_pass'}";

答案 2 :(得分:0)

您遇到了什么样的错误?

您的查询应该是一个字符串,这意味着您在分配时需要用引号括起来:

$sql_query = "SELECT name from user_info where user_name like '" . $user_name
. "' and user_pass like '" . $user_pass . "'";

您也可以使用以下语法:

$sql_query = "SELECT name from user_info where user_name like '{$user_name}' and user_pass like '{$user_pass}'";

然而,这将使您对SQL注入攻击持开放态度。 有关详情,请参阅this part of the PHP documentation