在sql语句中声明的变量但无法获取要显示的数据

时间:2014-12-19 18:03:35

标签: php sql-server pdo

我遇到的问题是数据没有显示出来。当我在它上面放一个OR它确实显示但是或者说因为user2拥有与user1相同的数据。

<?php
      include 'users.php';
      require_once("db_connect.php");

     //prepared statement with PDO to query the database
     $stmt = $db->prepare("SELECT * FROM requests WHERE User='.$user1.' AND status='Received' ORDER BY id DESC);
     $stmt->execute();  
    ?>

users.php

<?php 

$user1 = xxxx;
$user2 = zzzz;

?>

2 个答案:

答案 0 :(得分:2)

$stmt = $db->prepare("SELECT * FROM requests WHERE User='.$user1.' AND status='Received' ORDER BY id DESC);

如果$user1 = 1,则您的SQL将是:

SELECT * FROM requests WHERE User='.1.'.

你在外部字符串上有双引号,所以你没有转义字符串并连接,这些将是字面点,并且你永远不会在最后关闭你的外部字符串。另外,如果您要将变量直接注入字符串中,我不确定使用prepare的意义......?

看起来应该更像这样:

$stmt = $db->prepare("SELECT * FROM requests WHERE User=:user AND status='Received' ORDER BY id DESC");
$stmt->execute(array(':user' => $user1));

如果您想按照自己的方式进行操作,可以使用以下方法修复拼写错误:

$stmt = $db->prepare("SELECT * FROM requests WHERE User='".$user1."' AND status='Received' ORDER BY id DESC");

OR

$stmt = $db->prepare("SELECT * FROM requests WHERE User='{$user1}' AND status='Received' ORDER BY id DESC");

但是,这两种方法都不安全。他们面临SQL注入攻击的风险。您应该使用预处理语句,因为我在注入字符串之前首先清理了PDO首先清理的:user变量。

为了得到你的计数:

$stmt = $db->prepare("SELECT COUNT(*) AS rows_cnt FROM requests WHERE status='Received' AND User=:user");  
$stmt->execute(array(':user'=>$user1));
if( false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC)) ) { 
    echo $row['rows_cnt'];  
}

答案 1 :(得分:0)

可能是一个拼写错误,但似乎你没有在该行的末尾关闭"

 $stmt = $db->prepare("SELECT * FROM requests WHERE User='.$user1.' AND status='Received' ORDER BY id DESC);

所以试试这个:

 $stmt = $db->prepare("SELECT * FROM requests WHERE User='.$user1.' AND status='Received' ORDER BY id DESC");