IN DB
row1 (type column=apple), (stage column=1)
row2 (type column=orange), (stage column=NULL)
IN PHP
开发者_Python百科$query = mysql_query("SELECT * from fruits");
$row = mysql_fetch_array($query);
$num = mysql_num_rows($query);
$i=0;
$storeMyData = array();
while($row = mysql_fetch_array($query))
{
if(isset($row['type'])){
$type = "-" . $row['type'];
} else {
$type = NULL;
}
if(isset($row['stage'])){
$stage = "STAGE " . $row['stage'];
} else {
$stage = NULL;
}
$fruit = implode (", ", array_filter(array($type, $stage)));
// This will show 2 rows of data
$storeMyData[] = $fruit;
// store current data in array
$i++;
}
/* this will echo your storedData of loop */
foreach($storeMyData as $prevData)
/* or join the data using string concatenation */
$allFinalData2 = "";
/* this will echo your storedData of loop */
foreach($storeMyData as $prevData)
{
$allFinalData2 = $allFinalData2.$prevData ; // keep on concatenating
}
echo $allFinalData2;
The final output shows as "Apple, Stage 1" "Orange, Stage".
How can I show it "Apple, Stage 1" "Orange" without the word Stage if stage is NULL for row2 (orange) in DB.
Change this line
while($i < $num)
to this
while($row = mysql_fetch_array($query))
also, there is no need to call mysql_query inside your loop, use this to prevent confusion.
$type = "-" . $row['type'];
$stage = "STAGE " . $row['stage'];
精彩评论