差异是PHP \ SQL返回

时间:2013-04-26 01:22:12

标签: php mysql sql

所以我有两个功能:

    function display_name1($s){
        global $db;
        $query1 = "SELECT Taken From Alcohol where P_Key = $s";
        $r = $db->prepare($query1);
        $r->execute();
        $result = $r->fetchColumn();
        return $result;

}

    function write_Recipe($s){
        global $db;
        $query1 = "SELECT Taken From Alcohol where Name = $s";
        $r = $db->prepare($query1);
        $r->execute();
        $result = $r->fetchColumn();
        return $result;

    }

唯一的区别是我在第一个例子中将输入“$ s”与“P_Key”匹配,在后者中匹配“Name”。当我为第一个函数输入一个数字时,我得到了适当的回报。当我输入一个至少匹配一个“名字”的字符串时,我什么也得不到。由于某种原因,似乎不匹配字符串。有什么想法吗?

3 个答案:

答案 0 :(得分:5)

SQL查询中存在语法错误。您在第二个查询中缺少表名:

"SELECT Taken From where Name = '$s'"

应该是这样的:

"SELECT Taken FROM `tablename` WHERE  `Name` = '$s'"

进一步注意,如果您已经使用了预准备语句,则应该将变量绑定到查询,而不是使用字符串连接来构建查询。此外,global的使用并不适合OOP设计。以下是一个如何更好地完成工作的示例:

// extend a class from PDO
class CustomPDO extends PDO {


   public function display_name($s){

       // use placeholder :p_key in query
       $query1 = "SELECT Taken FROM `Alcohol` WHERE `P_Key` = :p_key";
       $r = $this->prepare($query1);

       // bind value to prepared statement
       $r->execute(array(
           ':p_key' => $s
       ));
       $result = $r->fetchColumn();
       return $result;
   }

   public function write_recipe($s){

       // use placeholder :name in query
       $query1 = "SELECT Taken FROM `tablename` WHERE  `Name` = :name";

       // use $this as we are extended from PDO
       $r = $this->prepare($query1);

       // bind value to prepared statement
       $r->execute(array(
           ':name' => $s
       ));

       $result = $r->fetchColumn();
       return $result;
   }
}

然后像普通的PDO对象一样使用该类:

$db = new CustomPDO($connection_string, $user, $password);

但还有两种方法:

$result = $db->display_name('foo');
$result = $db->write_recipe('foo');

答案 1 :(得分:2)

查询字符串时,应该用引号括起变量,如下所示:

"SELECT Taken From where Name = '$s'"

此外,您的第二个查询缺少表名。

"SELECT Taken From表名where Name = '$s'"

答案 2 :(得分:1)

需要引用字符串(如果还没有,则可能会被转义)。您似乎在使用PDO,为什么不添加占位符?并执行execute(array($s));,让PDO为您完成工作?

function display_name1($s){
    global $db;
    $query1 = "SELECT Taken From Alcohol where P_Key = ?";
    $r = $db->prepare($query1);
    $r->execute(array($s));
    $result = $r->fetchColumn();
    return $result;
}

function write_Recipe($s){
    global $db;
    $query1 = "SELECT Taken From Alcohol where Name = ?";
    $r = $db->prepare($query1);
    $r->execute(array($s));
    $result = $r->fetchColumn();
    return $result;

}