选择查询是不是通过Where IN子句工作?

时间:2013-04-18 23:02:37

标签: php mysql

需要帮助来解决选择查询问题,但问题是我无法通过ids从数据库中获取WHERE IN (pid) clause行。从ids选择从数据库中获取所有IN (pid)的查询?

1)if session pid is 29 then it should be select only 27 id为什么如果ids显示所有session pid is 29

2)如何通过两个不同的PID选择多个id?

Page1创建会话Pid的位置

$_SESSION['pid']=array();   
$_SESSION['pid'][]= implode (",",$_POST['pid']);

Page2我想在哪里使用选择查询

$pid = join(',',$_SESSION['pid']); 
$result=mysql_query("SELECT id AS wid FROM mywishlist where pid IN (pid)")
while($row=mysql_fetch_array($result)){
    <input type="text" name="wid[]" value="<?php echo $row['wid']//[$j]; ?>" />
<?php  }?>

Page3我想使用Wid的地方

$max=count($_REQUEST['wid']);
for($a=0; $a<$max; $a++){
    $query = mysql_query("UPDATE mywishlist SET     
        cusername='".$_SESSION['username']."',uid='".$_SESSION['id']."', 
        email='".$email."'  where id='".$_REQUEST['wid'][$a]."'") 
    or die ("Cart Email Query");
}

数据库图片

enter image description here

Page2实时图片

enter image description here

2 个答案:

答案 0 :(得分:3)

问题是你在查询的where子句中使用pid而不是$ pid。

$result=mysql_query("SELECT id AS wid FROM mywishlist where pid IN ($pid)")

答案 1 :(得分:1)

此:

$pid = join(',',$_SESSION['pid']); 
$result=mysql_query("SELECT id AS wid FROM mywishlist where pid IN (pid)")

应该是:

$pid = join(',',$_SESSION['pid']); 
$result=mysql_query("SELECT id AS wid FROM mywishlist where pid IN ($pid)")

它显示所有结果的原因是因为你有pid(pid)....将pid作为你桌子上的字段pid,所以对于你说的第一行的每一行:

pid value = 25
SELECT id AS wid FROM mywishlist where pid IN (25)
pid value = 26
SELECT id AS wid FROM mywishlist where pid IN (26)

并且所有行都相同......您正在与表中的值pid进行比较。

--------------------------- UPDATE ------------------- ----------

因为:

SELECT id AS wid FROM mywishlist where pid IN ($pid) 

如果你对$ pid做一个回音,它应该看起来像,例如:

24,25 

然后你选择应该看起来像:

SELECT id AS wid FROM mywishlist where pid IN (24,25)   

哎呀,如果使用mysql_real_scape_string

,代码应该更安全
"SELECT id AS wid FROM mywishlist where pid IN (".mysql_real_scape_string($pid).")"; 

如果您不知道如何使用输入数组,我添加了这个小提琴:

http://phpfiddle.org/main/code/2fd-p20

-------------------------- UPDATE2 -------------------- ------------

这个代码在我的小提琴上有一系列输入:

<?php
if(isset($_POST['friend']))
{ $arr = array();
 foreach ($_POST['friend'] as $value) {
   if(!empty($value))
$arr[] = $value;
 }

 //here you have you array of values in your session var

 $_SESSION['pid'] = implode(",",$arr);
 }
?>

然后才这样使用:

$pid = $_SESSION['pid'];
$result=mysql_query("SELECT id AS wid FROM mywishlist where pid IN (".$pid.")")

PS:不要使用mysql扩展...转到mysqli或PDO。