传递数组到SQL查询不起作用

时间:2014-02-06 06:54:40

标签: php mysql sql

<?php
require_once("dbdata.php");
if(mysql_connect($server_name,$Db_user,$Db_pass))
 {
if(mysql_select_db($Database_name))
   {
     $display_scores = "SELECT DISTINCT User_id, Quiz_id, Parent_Category,Category_Name, Score FROM custom_question_details where User_id = 3";
     $results = mysql_query($display_scores);
     $scores = array();
     $s_p = array();
     while($rows = mysql_fetch_assoc($results))
     {
        $scores[] = $rows; 
        $s_p [] = $rows['Parent_Category'];
     }
     $imp = implode(',',$s_p);
     $child_sql = "SELECT DISTINCT Category_Name FROM custom_question_details WHERE Parent_Category IN (".$imp.")";
     $child_result = mysql_query($child_sql);
     $child_array = array();
     while($fetch_child_results = mysql_fetch_assoc($child_result))
     {
         $child_array[] = $fetch_child_results;
     }
     print_r($child_array);
   }
 }
?>

我收到此错误

  

警告:mysql_fetch_assoc()期望参数1是资源,在行中给出布尔值...

$imp传递给$child_sql查询。但是,如果我静态地给出一些像'Sample'这样的字符串,而不是$imp变量,我会得到结果。在传递查询时传递$imp变量有什么问题。

5 个答案:

答案 0 :(得分:1)

将您的sql查询更改为:

$child_sql = "SELECT DISTINCT Category_Name FROM custom_question_details WHERE Parent_Category IN ('".$imp."')";

答案 1 :(得分:1)

试试这个......

替换代码..

$child_sql = "SELECT DISTINCT Category_Name FROM custom_question_details WHERE   Parent_Category IN ( $imp )";

答案 2 :(得分:1)

验证很重要。

$child_result = mysql_query($child_sql);之后

输入if(!$child_result) die(mysql_error());

注意:die();不是更好的选择。只是这样说,你知道你的查询有什么问题。

答案 3 :(得分:1)

您必须在IN子句

中引用值

试试这个

$s_p [] = "'".$rows['Parent_Category']."'";

而不是

$s_p [] = $rows['Parent_Category'];

现在使用它

$imp = implode(',',$s_p);
     $child_sql = "SELECT DISTINCT Category_Name FROM custom_question_details WHERE Parent_Category IN (".$imp.")";

答案 4 :(得分:1)

$imp ='';
while($rows = mysql_fetch_assoc($results))
     {
        $scores[] = $rows; 
        $imp = "'".$rows['Parent_Category']."', ";
     }
    // $imp = implode(',',$s_p);

$imp=rtrim($imp, ", ");
$child_sql = "SELECT DISTINCT Category_Name FROM custom_question_details WHERE Parent_Category IN (".$imp.")";
----
-----