calling a variable in PHP while loop - php

i have a website structure as follow
<div id="title">
<h1> //call $title here after executing loop </h1>
</div>
<?php
...
while ($row = $result->fetch_assoc()) { $title = $row['title']; ?>
<h2> this is the <?php echo $title;?> </h2>
<?php } ?>
is there a way i could still use or call the $title variable on an html element on top of the while loop statement?
whenever i call it above the while loop i get errors like Undefined variable: id..
edit: change id into 'title' instead

PHP will read code line by line so variable can't be used before declaration.
Only one option is to move loop above your div, get html from loop inside variable and print it later.
I think that you've got only one row in that loop so use this code instead.
$row = $result->fetch_assoc();
$title = $row['title'];
echo '<h2> this is the '.$title.' </h2>';

If you're only retrieving a single row, you don't need the loop:
<?php
$row = $result->fetch_assoc();
$title = $row['title'];
?>
<div id="title">
<h1><?php echo $title; ?></h1>
</div>

Related

How to loop within a for loop to get multiple values with the same ID

I want to get some data from a MySql database which has the same ID but different values. see the image (this is just a sample)
Although the venue styles are different, I want to pull all the styles with the same ID. I'm using a foreach loop to get the data from the database.
How can I improve my code to achieve what I want.
<?php
$myrows = $wpdb->get_results( "SELECT vf_venues.title, vf_venues.mainimage,
vf_venues.permalink, vf_venuestyles.slug
FROM vf_venues
LEFT JOIN vf_venuestyles ON vf_venuestyles.vid=vf_venues.vid WHERE
vf_venuestyles.vid=vf_venues.vid" );?>
<div class="venue-list venue-grid">
<?php
foreach ( $myrows as $myrow ) {
//pull the data from the DB
"<pre>"
$venueName = $myrow->title;
$mainImage = $myrow->mainimage;
$permalink = $myrow->permalink;
$slug = $myrow->slug;
$vid = $myrow->vid;
"<pre>"
?>
<li class="venue-block block">
<div class="venue-img">
<a href="<?php echo $permalink; ?>">
<img src="<?php echo $mainImage; ?>">
</a>
</div>
<div class="venue-details"><h2><?php echo $venueName; ?></h2></div>
<?php echo $slug; ?>
<?php echo $vid; ?>
</li>
<?php
}
?>
</div>
I managed to fix this by creating a for loop within the existing for loop. I then created a sql query to pull the venue styles for that venue.

For each inside other for each on view MVC PHP

I'm trying to give structure to my code and i am facing a problem.
I'm looping through a sql query response and for each element i'm trying to retrieve other related elements. It works in my controller without problem but when i'm trying to repeat in the view I always get the same value for the related element
My controller:
<?php
include_once('class/guide.class.php');
$bdd = new DBHandler();
$req = guide::getGuides($bdd,0,5);
foreach ($req as $results => $poi)
{
$req[$results]['id'] = htmlspecialchars($poi['id']);;
$req[$results]['name'] = nl2br(htmlspecialchars($poi['name']));
$guide = new guide($results['name'],$bdd);
$guidePois = $guide->getGuidePois($poi['id']);
foreach ($guidePois as $res => $re)
{
echo $guidePois[$res]['id'];
echo $guidePois[$res]['name'];
$guidePois[$res]['id'] = htmlspecialchars($re['id']);
$guidePois[$res]['name'] = nl2br(htmlspecialchars($re['name']));
}
}
include_once('listing.php');
here, you see that I echo the ids/names of the related list of element and it works well, the output is correct for each element of the first list.
When i do it in my view:
<?php
foreach($req as $poi)
{
?>
<div class="news">
<h3>
<?php echo $poi['id']; ?>
<em>: <?php echo $poi['name']; ?></em>
</h3>
<?php foreach($guidePois as $re)
{
?>
<h4>
<?php echo $re['id']; ?>:
<?php echo $re['name']; ?>
</h4>
<?php
}
?>
</div>
<?php
}
?>
Somehow the first list output are the good elements, but for the 2nd list, i always get the related elements of the first item.
Do you have an idea ?
Thanks a lot for your help
This is because you only set:
$guidePois = $guide->getGuidePois($poi['id']);
once in the controller.
If you want it to work in the view, you need to insert this code right after the closing </h3>
<?php $guidePois = $guide->getGuidePois($poi['id']); ?>
So that $guidePois gets a new value in each iteration.
Complete view code:
<?php
foreach($req as $poi)
{
?>
<div class="news">
<h3>
<?php echo $poi['id']; ?>
<em>: <?php echo $poi['name']; ?></em>
</h3>
<?php
$guidePois = $guide->getGuidePois($poi['id']);
foreach($guidePois as $re)
{
?>
<h4>
<?php echo $re['id']; ?>:
<?php echo $re['name']; ?>
</h4>
<?php
}
?>
</div>
<?php
}
?>

Get multiple rows from foreach

So on my project I have posts. And basically they include the post time and post content. Now here's my issue, I can only figure out how to retrieve one row instead of post content and post time. Here's my code
$posts = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$posts[] = $row['post_content'];
}
And how I'm returning
<?php
foreach($posts as $post) {
$post;
?>
<div class="content">
<div class="post">
<h1 class="message">
<?php
echo $post;
?>
</h1>
<p class="time">4 minutes ago</p>
</div>
</div>
<?php
}
?>
I've tried
$posts = array();
$time = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$posts[] = $row['post_content'];
$time[] = $row['post_time'];
}
But that doesn't work. I've ran out of ideas. Any help would be great. Also if there is a cleaner way to do this, it would be nice knowing how. Thanks
You can use nested arrays:
$posts = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$posts[] = array(
'post_content' => $row['post_content'],
'time' => $row['post_time']
);
}
Then your echo needs to reference $post['post_content'] and $post['time'].
Your're using $post = value, this will overwrite your value each time, try:
array_push($posts, $row['post_content']);
inside of your while loop
You could simply generate your HTML within the while loop. Otherwise, you might like to populate your posts array directly with PDOStatement::fetchAll -
$posts = $stmt->fetchAll();
and use it as you have been, e.g -
<?php foreach($posts as $post): ?>
<article>
<h1> <?php echo $post['title']; ?> </h1>
<p> <?php echo $post['content']; ?> </p>
</article>
<?php endforeach; ?>

PHP MySQL query variables not returning

I store my testimonials in a database table and would like them to be displayed on my website via this for loop:
<?php
$count = mysql_fetch_assoc(mysql_query("SELECT COUNT(*) cnt FROM testimonials"));
for ($i = 1; $i <= intval($count['cnt']); $i++)
{
$sql = mysql_query("SELECT * FROM testimonials WHERE id='{$i}'");
?>
<li class="span4">
<div class="thumbnail thumbnail-1">
<section>
<a class="link-1" style="cursor:pointer;"><?php echo $sql['name'] ?></a>
<p><?php echo $sql['text'] ?></p>
<?php echo $sql['product'] ?>
</section>
</div>
</li>
<?php
}
?>
The issue is that the $sql variables product, name and text are not displaying. However the $count is getting the correct intval, so it knows there are entries.
It's also worth pointing out that the loop is working as I get the <li> <div> and <section> tags working, the only issue is the <a>'s and the <p> not getting the textual value from the echo
P.S. I know that mysql_* functions are depreciated however my php version 5.3 and they are only depreciated from 5.5 so they are ok for my website.
you missed to fetch second sql
add this line
$result= mysql_fetch_assoc($sql) ;
and then call your variables like that
<?php echo $result['name'] ; ?>
<?php echo $result['product'] ;?>
<?php echo $result['product'] ; ?>
^^-----dont forget `;` because you missed them also

foreach mysql row from query echo out html with row values

So basicly what I'm trying to accomplish is that foreach row in mysql query it prints out the html with the data from that row. Here's what I have, it keeps giving me an error on my foreach.
<?php
$shots = mysql_query("SELECT * FROM shots") or die(mysql_error());
while($row=mysql_fetch_array($shots))
$data[]=$row;
foreach($shots as $data)
if (!empty($data)){
$id = $data["id"];
$shotby = $data["shot"];
$passby = $data["pass"];
$time = $data["time"];
?>
<div class="feedbody">
<div class="title"><?php echo $shotby; ?></div>
<div class="feed-data">: gets a pass from <span><?php echo $passby; ?</span> and he takes a shot!</div>
<img class="dot" src="images/dot.png" />
</div>
<?php
}
}
?>
Or something like that. Can anybody help point me in the right direction. I've been trying to find the answer.
EDIT: adding the error as requested.
Warning: Invalid argument supplied for foreach() in /home/content/93/7527593/html/fusionboard/includes/feed.php on line 7
First, if you want to access the data by name (instead of index), you need to include MYSQL_ASSOC as a second parameter to mysql_fetch_array, or use mysql_fetch_assoc.
Not really sure why you were copying the MySQL results to a second array just to loop through that later - you can loop through the results directly:
<?php
$shots = mysql_query("SELECT * FROM shots") or die(mysql_error());
while($row = mysql_fetch_assoc($shots)) { ?>
<div class="feedbody">
<div class="title"><?php echo $row["shot"]; ?></div>
<div class="feed-data">: gets a pass from <span><?php echo $row["pass"]; ?></span> and he takes a shot!</div>
<img class="dot" src="images/dot.png" />
</div>
<?php } ?>
Update after you posted the error message: the error from your original code was that you first went through and copied each result row into $data, but then in your foreach you tried to loop on $shots (again) and have it call each item $data.
What you probably wanted to do was have foreach ($data as $item) and then copy the properties from $item.
Something like this?
<?php
$shots = mysql_query("SELECT * FROM shots") or die(mysql_error());
while($row=mysql_fetch_assoc($shots))
{
$id = $row["id"];
$shotby = $row["shot"];
$passby = $row["pass"];
$time = $row["time"];
?>
<div class="feedbody">
<div class="title"><?php echo $shotby; ?></div>
<div class="feed-data">: gets a pass from <span><?php echo $passby; ?</span> and he takes a shot!</div>
<img class="dot" src="images/dot.png" />
</div>
<?php
}
?>
Perhaps you need another closing brace? (Another "}" at the end, I mean).
You saved your data in the $data variable, but your foreach uses the $shots variable.
Just change it to foreach($data as $something) and $something["id"] (for example) to retrieve a value
you are using one variable instead of another.
and many useless code.
while youneed only
<?php foreach($data as $row) { ?>
<div class="feedbody">
<div class="title"><?php echo $row['shotby'] ?></div>
<div class="feed-data">:
gets a pass from <span><?php echo $row['passby'] ?</span> and he takes a shot!
</div>
<img class="dot" src="images/dot.png" />
</div>
<?php } ?>

Categories