开发者

PHP: make a 'fake'/custom statement in while

开发者 https://www.devze.com 2023-02-01 19:25 出处:网络
I have this while loop. while($show = $queryActivities->fetch()){ echo $show[\"name\"].\"<br>\"; }

I have this while loop.

while($show = $queryActivities->fetch()){ echo $show["name"]."<br>"; }

This takes data from the query and outputs the names..

Now is it possible to make a custom/fake data? I would like to make one if theres no data/statement in the $queryActivities then it should make a custom one called "name" with value "Nothing here.."

Is this possible? Can you do that?

I know I can do if($queryActivities->rowCount == 0){ echo "Nothing here" ; }

But I more thought of creating a custom data, so it runs the while loop, with the custom data, that only gets made if theres nothing in $queryActivities.

开发者_如何学运维

Something like..:

if($queryActivities->rowCount == 0){
 # ..MAKE CUSTOM DATA..
 # ..SOMETHING LIKE THIS MAYBE:  .. 
 # $queryActivities = MAKE ARRAY WITH name => 'Nothing here'.. (just a thought)
}
while ($show = $queryActivities->fetch()){
echo $show["name"]."<br>";
}

Something like this, just what I imagine, although I dont know really how.

Thank you


Retrieve your data to an array, and then print it out. In between these two steps, you can modify it as desired.

This is more orderly, anyhow. I don't like retrieving from the DB and displaying in one step

You could either have an if/else that checks if the array is empty and prints a default message, or creates a default entry with a 'name' property that then is displayed with the same output loop as normal data. I'd prefer the first, but we'll do the second style since that's what you asked about.

Here's one simple solution.

$activities=array();
while($show = $queryActivities->fetch()){ $activities[]=$show; }

if(empty($activities)){ $activities=array(array('name'=>'None Found')); }

foreach($activities as $activity){
   echo $activity['name']."<br>";
   }

I think just using an if/else is a better solution. Depending on your output style, though, this might involve more code repetition.

$activities=array();
while($show = $queryActivities->fetch()){ $activities[]=$show; }

if(empty($activities)){ 
   echo "None found <br>";
   }

else{
   foreach($activities as $activity){
     echo $activity['name']."<br>";
     }
   }
0

精彩评论

暂无评论...
验证码 换一张
取 消