简体   繁体   中英

How to make a php variable equal to the result of mysql_fetch_array?

$query = mysql_query("SELECT * FROM fruit WHERE color='red' ");
while ($row = mysql_fetch_array($query)) {
    echo $row['name']."|" ;// this echo apple|strawberry|cherry     
}

How to make a php variable equal to the result of mysql_fetch_array? I need to make a equal like: $newname="apple|strawberry|cherry" , so that I can use the new variable $newname for another process. Thanks.

Rather than echo, concatenate:

$newname = '';
while ($row = mysql_fetch_array($query)) {
    $newname .= $row['name']."|" ;// this echo apple|strawberry|cherry     
}
$newname = rtrim($newname,'|');
$newname .= $row['name']."|" ;
$query = mysql_query("SELECT * FROM fruit WHERE color='red' ");

$newname= '';

while ($row = mysql_fetch_array($query)) {
    $newname.= $row['name']."|" ;  
}

This gives you a string $newname like you want.

i use this in my joomla :

$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('price');
$query->from($db->quoteName('#__google_api'));
$query->where($db->quoteName('id')." = ".$db->quote('1'));
// Reset the query using our newly populated query object.
$db->setQuery($query);

$db->setQuery($query);
$price = $db->loadResult();

Fetches data for a single colume and stores it in $price

I know everyone else went with string concatenation, but I would personally suggest an array push followed by a join - I haven't benchmarked it, but I believe it would perform slightly better.

while($row = mysql_fetch_array($query)) {
     $newname[] = $row['name'];
}
echo join('|', $newname);

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