如何在sql查询中使用Arraylist?

时间:2014-02-07 07:22:05

标签: php mysql

  

我想要产品表中的产品详细信息。所以我从tbl_product_color获得了productid   现在我想要产品的所有细节都存储在product_id的tbl_product表中   并在数组$ data product_id存储但我的下面的代码不起作用:    还有一个问题是,每次存储此页面刷新color_id = 0时都存在    tbl_user_color,我真的不想存储,甚至那里没有记录    tbl_color中的color_id = 0。           

    $query="select * from tbl_user_color where color_session_id='".$sid."'";
    //echo $query;

    $resultset=mysql_query($query);
    $query="SELECT DISTINCT (product_id) FROM tbl_product_color";

    $cnt=0;

    while($row=mysql_fetch_assoc($resultset))
    {
        extract($row);
        if($cnt==0)
        {
            $query=$query." where color_id=".$color_id."";
        }
        else
        {
            $query=$query." or color_id=".$color_id."";
        }
        $cnt++;
            //  echo $color_id."<br>";
    }

     //echo $query;

    $resultset=mysql_query($query);

    echo "<div id='productdiv'>";
    $data = array();
    while($row=mysql_fetch_assoc($resultset))
    {

        $data[]=$row;
    }
    echo "<pre>";
    print_r($data); /* here i get an array with product_id list */
    echo "</pre>";
    echo "</div>";
    echo "<br>";
    echo "<br>";

    //$idStr = implode(',', $data); 
    /* here i want product details using $data array */
    $sql = "SELECT * FROM tbl_product WHERE product_id =".$data;
    $res=mysql_query($query);
    while($r=mysql_fetch_assoc($res))
    {
            extract($r);
        echo "   ".$product_name;
    }

    ?>

1 个答案:

答案 0 :(得分:1)

使用 IN子句

"SELECT * FROM tbl_product WHERE product_id IN (" . implode(",",$data). ")";

注意: Please, don't use mysql_* functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial