foreach mysql row from query echo out html with row values - php

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 } ?>

Related

How to fix PHP/SQL search query only fetching one row of data instead of all associated rows?

I'm working on a little project and I want to be able to search my database for all items associated with my search
My problem is that when I use my code below, I get only one result rather than an array of all results that fit my query. I have seen some solutions that suggested using fetchAll() but that doesn't seem to output anything.
What the PHP query looks like.
if(isset($_POST['search'])){
if(preg_match("/^[a-zA-Z]+/", $_POST['sname'])){
$search = $_POST['sname']; //name in form
$pdo = & dbconnect();
$userid = $_SESSION['user_id'];
$sql = "SELECT * FROM movie_dets Where user_id=? and Title LIKE '%" .$search."%'";
$stmt=$pdo->prepare($sql);
$stmt->execute([$userid]);
if(!$stmt)
{
die("Database pull did not return data");
}
$row=$stmt->fetch();
}
}
Then I have a foreach loop in my html that looks like so
<div class="row">
<?php
$loop = 0;
foreach ($stmt as $row): //loop through result set ?>
<div class="column" >
<div>
<figure>
<img src="<?php echo "/.../".$row['Cover'] ?>" alt="<?php echo $row['Title']; ?> cover" />
<figcaption>
...
</figcaption>
</figure>
</div>
</div>
<?php
$loop++;
if ($loop % 4 ==0) //to display four results the wrap.
{
echo "</div> <div class='row'>";
}
?>
<?php endforeach ?>
</div>
In my database, there are two titles called frozen. This is supposed to output all rows when given the 'fr' search word. Instead, it only fetches one of them.

Some HTML tags disappear when i use PHP

I'm trying to generate dynamic contents fill from mysql db
here is my php code:
<?php
include 'header.php';
error_reporting(1);
$user = "root";
$pass = "";
$dbName = "haimi";
mysql_connect('localhost', $user, $pass) or
die("Could not connect: " . mysql_error());
mysql_select_db($dbName);
$sql = "SELECT * FROM Projects ";
$result = mysql_query($sql);
?>
<?php
while ($line = mysql_fetch_array($result)) {
?>
<li class="filter" data-filter=".cat<?php echo $line['Category'];?>"><?php echo $line['Category'];?></li>
<?php
}
?>
The li displays correctly, but the following does not:
<div class="row projects m0">
<?php
while ($line = mysql_fetch_array($result)) { ?>
<div class="project mix catHouses">
<div class="tint"></div>
<a href="images/projects/".<?php echo $line['ProjectImage1']; ?> data-
lightbox="project" data-title="Central Hospital (building)">
<img src="images/projects/".<?php echo
$line['ProjectImage1']; ?> alt="<?php echo $line['ProjectTitle'];?>"
class="projectImg"> </a>
<div class="projectDetails row m0">
<div class="fleft nameType">
<div class="row m0 projectName"><?php echo $line['ProjectTitle'];?></div>
<div class="row m0 projectType"><?php echo $line['ProjectType'];?></div>
</div>
<div class="fright projectIcons btn-group" role="group">
<a href="images/projects/<?php echo $line['ProjectImage1']; ?>" data-lightbox="project" data-title="Central Hospital (building)" class="btn btn-default">
<i class="fa fa-link"></i></a>
<i class="fa fa- search"></i>
</div>
</div>
</div>
<?php
}
?>
</div>
It data in the divs doesn't appear.
You're making a single call, but trying to loop through it twice. To do so, you need to reset the pointer back to the beginning:
//Add this after the first loop, but before the second
mysql_data_seek( $result, 0 );
The way you have it now, it's while($line = mysql_fetch_array($result)), but the second loop is never entered since it has already reached the end. Since the loop is ended, it never displays the contents.
Important Note
The mysql_* functions are deprecated, and is removed in PHP 5.5. You should use Mysqli or PDO. They have better protections against mysql injections (see Bobby Tables).
You have some HTML mistakes here:
<a href="images/projects/".<?php echo $line['ProjectImage1']; ?>
First, there is no need to use . operator (as you are in HTML, not PHP),
Also you shoud put your <?php ?> tag inside the href quotations, here is the correct code:
<a
href="images/projects/<?php echo $line['ProjectImage1']; ?>"
data-lightbox="project"
data-title="Central Hospital (building)"
>
<img
src="images/projects/<?php echo $line['ProjectImage1']; ?>"
alt="<?php echo $line['ProjectTitle']; ?>"
class="projectImg"
>
</a>
You will get older fast writing code like that ;)
How about this:
while ($line = mysql_fetch_array($result)) {
$category = $line['Category'];
echo <<< LOB
<li class="filter" data-filter="$category">$category</li>
LOB;
}
Like what Mr #matthew said
I was making a single call, and I was trying to loop through it twice.
The problem solved with this code before the while loop:
$result = mysql_query($sql);

calling a variable in PHP while loop

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>

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

PHP MYSQL Multiple table query

I have two tables 'p_tuts' and 'h_tuts'. I'm using a method to display all the returned rows. Although I'm not sure how to set it up to run multiple queries, I can only get it to return one query at a time. Heres my code...
public function QueryAll($my_field, $limit) {
$query = mysql_query("SELECT * from $my_field LIMIT $limit");
$rows = array();
while($row = mysql_fetch_array($query)) {
$rows[] = $row;
}
return $rows; }
Here is my index file
<?php $results = $Database->QueryAll('p_tuts', 5); ?>
<?php foreach ($results as $result): ?>
<div class="tutorial">
<div class="tut_header"><h2><?php echo $result['tut_header']; ?></h2></div>
<div class="tut_poster">Posted by: <?php echo $result['tut_poster']; ?> on <?php echo $result['tut_date']; ?></div>
<div class="tut_img rounded"><img src="<?php echo "img_uploads/". $result['tut_img']; ?>" width="180" height="151" /></div>
<div class="tut_content"><p><?php $Website->CharLimit($result['tut_content'], 800); ?></p></div>
</div>
<?php endforeach; ?>
I'd really like to adapt it so I can use this class to display both multiple tables, rather than just the one.
kind regards
This is difficult to answer without knowing the relationship between the two tables, but it looks like you need to use a JOIN or UNION.

Categories