简体   繁体   中英

PHP - Retrieve multiple records from a single mysql table and append to a string

I have the following table in mysql. I need to select the Hid(s) from this table and append the results to a string '$s'. It would be great if you could help.

Table name : CASES

Did   Hid   Year  Case
---   ---   ----  ----
 1     1    2011   6
 1     1    2012   7
 2     2    2011   40
 2     2    2012   10

php code segment:

$did=1;
$yr=2011;
$s='';
$q="select Hid from CASES where Did=$did and Year=$yr and Case!=0 ";
$r=mysql_query($q);
while($rw=mysql_fetch_assoc($r))
{
    //I need to append the Hid(s) to a String '$s' declared above
}

Assuming your query works, which it looks like it might:

$did=1;
$yr=2011;
$s='';
$q="select Hid from CASES where Did=$did and Year=$yr and Case!=0 ";
$r=mysql_query($q);
while($rw=mysql_fetch_assoc($r))
{
    $s .= $rw['Hid'];
}

That will just give you a string with all of the Hids together.. if you want to have a character in between or something else, you could:

$did=1;
$yr=2011;
$s=array();
$q="select Hid from CASES where Did=$did and Year=$yr and Case!=0 ";
$r=mysql_query($q);
while($rw=mysql_fetch_assoc($r))
{
    $s[] = $rw['Hid'];
}
$result = implode( ',', $s );

$result above will end up with a comma-separated list of Hids.

使用字符串串联运算符

$s .= $rw['Hid'];

Get/ retrieve the data's to an array and implode it to a string. Refer http://php.net/manual/en/function.implode.php

for implode

$did=1;
$yr=2011;
$s='';
$q="select Hid from CASES where Did=$did and Year=$yr and Case!=0 ";

    $r=mysql_query($q);
    while($rw=mysql_fetch_assoc($r))
    {
        $s .= $rw['hid'] . '<br />';
    }



echo $s;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM