0
$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.

5 Answers 5

3

Rather than echo, concatenate:

$newname = '';
while ($row = mysql_fetch_array($query)) {
    $newname .= $row['name']."|" ;// this echo apple|strawberry|cherry     
}
$newname = rtrim($newname,'|');
Sign up to request clarification or add additional context in comments.

Comments

3
$newname .= $row['name']."|" ;

Comments

1
$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.

Comments

0

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);

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.