【问题标题】:Where IN Clause in PHP & output of while loop outside of whilePHP 中的 Where IN 子句和 while 之外的 while 循环的输出
【发布时间】:2014-01-27 08:02:52
【问题描述】:

我的 PHP 代码是

<?php
include('session.php');
include('db.php');

$session=$_SESSION['agent'];

$home1 = "SELECT fullname FROM users WHERE role='$session'";
$result1=mysql_query($home1) or die(mysql_error());
while ($row1=mysql_fetch_array($result1)) {

echo $gallery = "'".$row1[0]."',"; // output is 'sam','teja','multiplevaluessoon',


$home = "SELECT * FROM chat WHERE chat.from IN ('$gallery')";
}
$result=mysql_query($home) or die(mysql_error());

while ($row=mysql_fetch_array($result)) {

    $msg         =$row["message"];
    echo $randomUserId=$row["from"];
   echo $msg . "<br/>";
   }
 ?>

这里 $gallery 在末尾包含 ',' 逗号,所以当我尝试修剪 $gallery 的输出时,我在 where 子句中遇到错误

 'sam','teja','multiplevaluessoon',

我得到的循环内的最后一个字符

 'sam''teja''multiplevaluessoon'

由于while循环正在修剪所有逗号,我需要修剪最后一个逗号,以便我可以在where子句中执行它

请给我建议

【问题讨论】:

    标签: php mysql while-loop trim


    【解决方案1】:

    使用rtrim()

    $yourfinaltext = rtrim($yourcommadelimitedstring, ',');
    

    像这样更改您的while

    while ($row1=mysql_fetch_array($result1)) {
    
          $gallery .= "'".$row1[0]."',";
          $home = "SELECT * FROM chat WHERE chat.from IN ('$gallery')";
    }
    echo rtrim($gallery,',');
    

    【讨论】:

    • 这就是我在那里解释的,当我修剪它时它正在删除所有逗号,因为它在 while 循环中
    • 您需要在while 循环之外执行此操作。这就是为什么我将变量名称设置为$yourfinaltext
    • 但在循环外我不会得到与循环内相同的输出,在循环外它只会打印列的最后一个值
    【解决方案2】:
    $rest = substr("abcdef", 0, -1);  // returns "abcde"
    

    http://php.net/manual/en/function.substr.php

    【讨论】:

      【解决方案3】:

      把逗号去掉...

      $gallery=substr_replace($gallery ,'',0,1);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-02
        • 2016-08-10
        • 1970-01-01
        • 2016-05-27
        • 1970-01-01
        • 1970-01-01
        • 2014-04-15
        • 1970-01-01
        相关资源
        最近更新 更多