I am working on a directory where some of the listings have a images associated with them and others do not. I am wondering how I can write a loop within a loop to get my results.
Example, User selects state they want results from, query goes to DB requesting all listings in that state.
<?php
if (isset($_POST['searchButton'])) {
$state = $_POST['state'];
$query = "SELECT * FROM directory LEFT JOIN directory_images ON directory.id = directory_images.user_id WHERE directory.state = '$state' ";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) == 0) {
echo "<p>Sorry, there are no listings in '$state', check back soon!</p>\n";
}
else
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$id = $row['id'];
$name = $row['name'];
$address = $row['address'];
$city = $row['city'];
$state = $row['state'];
$zip = $row['zip'];
$has_support_pics = $row['file_name'];
?>
<h4><?php echo $name ?></h4>
<p><?php echo $address ?><br/>
<?php echo $city . ' ' . $state . ', ' . $zip; ?><br/>
</p>
<?php
// check to see if ID has extra images
if (isset($has_support_pics)) {
$query2 = "SELECT file_name FROM directory_images WHERE user_id = '$id'";
$result2 = mysql_query($query2) or die(mysql_error());
echo $query2.'<br/>';
?>
<ul class="support_images">
<?php
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
$support_image = $row['file_name'];
echo $support_image.'<br/>';
}
?>
</ul>
</div>
<br/>
</div>
<?php
}
echo "<hr/>";
}
}
?>
Do NOT run queries in loops - use a join.
Here is a tutorial: http://thewebmason.com/tutorial-parent-child-lists/
Related
pls i tried to display all content in a database, it keeps dispaying the last inserted, kindy help out.
<?php
include 'database/condb.php';
$query = mysql_query("SELECT * FROM posts ");
while($row = mysql_fetch_assoc($query)){
$id = $row["id"];
$username = $row["username"];
$body = $row["body"];
$date_added = $row ["date_added"];
$hasttags= $row["hashtags"];
?>
<?php
}
?>
<?php
echo $id;
echo $body;
?>
Either print the values in while loop or store them in an array to print them outside the loop.
while($row = mysql_fetch_assoc($query)){
echo $row["id"];
echo $row["body"];
}
condb.php
<?php
$con = mysqli_connect("localhost","username","password","databasename");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
index.php
<?php
include 'database/condb.php';
$query = "SELECT * FROM posts";
$res = mysqli_query($con, $query);
while($row = mysqli_fetch_assoc($res)){
$id = $row["id"];
$username = $row["username"];
$body = $row["body"];
$date_added = $row ["date_added"];
$hasttags= $row["hashtags"];
echo $id;
echo $body;
}
?>
For storing data, sometimes using array becomes helpful. I usually recommend it:
<?php
include 'database/condb.php';
$query = mysql_query("SELECT * FROM posts");
$array = [];
while($row = mysql_fetch_assoc($query)){
$id = $row["id"];
$username = $row["username"];
$body = $row["body"];
$date_added = $row ["date_added"];
$hasttags = $row["hashtags"];
$array[$id] = ['username'=>$username, 'body'=>$body, 'date_added'=>$date_added, 'hasttags'=>$hasttags];
}
?>
<?php
foreach($array as $id => $value){
echo $id; //Prints id
echo "<br>";
echo $value['username'].", ".$value['body'].", ".$value['date_added'].", ".$value['hasttags'];
}
?>
Or you can simply do this:
<?php
include 'database/condb.php';
$query = mysql_query("SELECT * FROM posts");
$array = [];
while($row = mysql_fetch_assoc($query)){
$id = $row["id"];
$username = $row["username"];
$body = $row["body"];
$date_added = $row ["date_added"];
$hasttags = $row["hashtags"];
?>
<?php
echo $id.", ".$username.", ".$body.", ".$date_added.", ".$hasttags;
}
?>
<?php
include 'database/condb.php';
$query = mysql_query("SELECT * FROM posts ");
while($row = mysql_fetch_assoc($query)){
$id = $row["id"];
$username = $row["username"];
$body = $row["body"];
$date_added = $row ["date_added"];
$hasttags= $row["hashtags"];
echo $id;
echo "<br>";
echo $body;
?>
<?php
}
?>
As an answer to the question "pls i tried to display all content in a database, it keeps dispaying the last inserted, kindy help out."
Put echo $id, echo $body be inside the loop.
I am trying to include a separate snippet of code to fetch data from MySQL tables. My page code:
<?php session_start(); ?>
<html>
<?php include('head.php'); ?>
<body>
<?php include('navigation.php'); ?>
<div id="container">
<?php
$section = "Movies";
print "THIS IS A TEST";
//$_SESSION['sectiontemp'] = $section;
include('section-grabinfo.php');
include('footer.php');
?>
</div>
</body>
</html>
My section-grabinfo.php page:
<?php
print "THIS IS A TEST";
$sql = mysqli_query($conn, "SELECT * FROM article JOIN person ON article.author=person.id WHERE section='".$section."' AND status=1 ORDER BY aid DESC LIMIT 1;");
if ($sql == 'false') {
print "SQL doesn't work";
}
elseif ($sql == 'true') {
print "Works all fine";
}
else {
print "Wrong code.";
}
while ($row = mysqli_fetch_assoc($sql)) {
$title = $row['title'];
$preview = $row['preview'];
$author = $row['name'];
$person_id = $row['author'];
$id = $row['id'];
$username = $row['username'];
include('featured-article.php');
}
//LEAVE SPACE FOR ADS
?>
<div id="secondaryArticleSection">
<?php
$sql2 = mysqli_query($conn, "SELECT * FROM article JOIN person ON article.author=person.id WHERE aid<(SELECT max(aid) FROM article WHERE section='."$section."' AND status=1) AND section='".$section."' AND status=1 ORDER BY aid DESC;");
while ($row = mysqli_fetch_assoc($sql2)) {
$title = $row['title'];
$preview = $row['preview'];
$author = $row['name'];
$person_id = $row['author'];
$id = $row['id'];
$username = $row['username'];
include('secondary-article.php');
}
?>
</div>
Basically my problem is that section-grabinfo.php and footer.php are not being included on the main page. Please keep in mind that this worked completely when I had this on my laptop computer (not the server I'm currently working with). Thank you.
If it is really an including trouble, you could try to include this way
<?php include(__DIR__.'/head.php'); ?>
I am in the process of building a institute review system and i just completed inserting reviews to the database. However i am in a fix as to how to display to the user all the reviews related to the particular institute.
Below is my code to retrieve review information along with the name of the person who has left the review:
$get_review_query = "SELECT * FROM reviews WHERE institute_id = {$id}";
$result = mysqli_query($connection, $get_review_query);
if(!$result) {
die("Database query failed.");
}
$count = mysqli_num_rows($result);
if($count == 0) {
$output = "There're no reviews for this institute.";
} else {
while($row = mysqli_fetch_assoc($result)) {
$review_contents = $row['content'];
$institute_id = $row['institute_id'];
$student_id = $row['student_id'];
$date = $row['created_on'];
$query_student_name = "SELECT f_name, l_name FROM students
WHERE student_id = {$student_id}";
$result1 = mysqli_query($connection, $query_student_name);
if(!$result1) {
die("Database query failed.");
} else {
$row1 = mysqli_fetch_assoc($result1);
$student_f_name = $row1['f_name'];
$student_l_name = $row1['l_name'];
}
}
}
Now i want to display the reviews somewhere down the page:
<!-- display reviews -->
<fieldset>
<legend>Reviews for <?php echo $name; ?></legend>
<br>
<?php
foreach($row as $value) {
?>
<legend><?php echo $student_f_name . " ". $student_l_name; ?> said:</legend>
<div id = "items" class="">
<?php echo $review_contents; ?>
</div>
<br>
<div>
<?php echo $date; ?>
</div>
<?php } ?>
</fieldset>
The above foreach loop doesn't work. It probably creates an infinite loop. I have tried using a for loop with $count as the maximum counter but that doesn't work either. Please suggest a for loop that prints all the reviews from the database.
try this
$get_review_query = "SELECT * FROM reviews WHERE institute_id = {$id}";
$result = mysqli_query($connection, $get_review_query);
if(!$result) {
die("Database query failed.");
}
$reviews = array();
$count = mysqli_num_rows($result);
if($count == 0) {
$output = "There're no reviews for this institute.";
} else {
while($row = mysqli_fetch_assoc($result)) {
$query_student_name = "SELECT f_name, l_name FROM students
WHERE student_id = {$student_id}";
$result1 = mysqli_query($connection, $query_student_name);
if(!$result1) {
die("Database query failed.");
} else {
$row1 = mysqli_fetch_assoc($result1);
$row['f_name'] = $row1['f_name'];
$row['l_name'] = $row1['l_name'];
}
$reviews[] = $row;
}
}
if( $reviews ){
?>
<fieldset>
<legend>Reviews for <?php echo $name; ?></legend>
<br>
<?php
foreach($reviews as $review) {
?>
<legend><?php echo $review['f_name'] . " ". $review['l_name']; ?> said:</legend>
<div id = "items" class="">
<?php echo $review['content']; ?>
</div>
<br>
<div>
<?php echo $review['created_on']; ?>
</div>
<?php } ?>
</fieldset>
<?php
}
I have a error on my php code. I will insert a new row
And i get the error: wrong parameter count in mysql_query
<?php
include('../sec/inc_mysql_connect.php');
include 'googledistance.class.php';
$sql = "SELECT VVBnummer, Adres, Postcode FROM tblscheidsrechters";// echo($sql);
$result = mysql_query($sql);
$sql_sh = "SELECT ID, SporthalAdres, Postcode FROM tblsporthal"; //echo('<br>' . $sql_sh);
$result_sh = mysql_query($sql_sh);
while($record = mysql_fetch_array($result))
{
while($record_sh = mysql_fetch_array($result_sh))
{
$fromAddress = $record['Adres'] . ',' . $record['Postcode']; //echo($fromAddress . '<br>');
$toaddress = $record_sh['SporthalAdres'] . ',' . $record_sh['Postcode']; //echo($toaddress . '<br>');
$gd = new GoogleDistance($fromAddress, $toaddress);
$vvb = $record['VVBnummer'];
$shid = $record_sh['ID'];
$afstand = $gd->getDistance();
$tijd = $gd->getDuration();
?>
<body>
<p>Scheidsrechter: <?php echo($record['VVBnummer']); ?></p>
<p>Sporthal: <?php echo($record_sh['ID']); ?></p>
<p>Afstand in km (h/t): <?php echo $gd->getDistance()/1000 ; ?></p>
<p>Tijd in minuten: <?php echo $gd->getDuration()/60; ?></p>
<p>Gevonden oorsprong: <?php echo $gd->getOrigin(); ?></p>
<p>Gevonden bestemming: <?php echo $gd->getDestination(); ?></p>
<hr />
</body>
<?php
$sql = "INSERT INTO klvv_sr_afstand_sh ( vvb_nr_sr, shid, afstand, tijd) VALUES('$vvb', '$shid', '$afstand', '$tijd')"; echo($sql);
$record = mysql_query();
}
}
?>
The error happens when i will insert the row
Thx for the help
You'd need to pass the query to the server:
$record = mysql_query($sql);
For clarification: in your code you stated $record = mysql_query();
How can I get data from my database to show. I am not very experienced with PHP or MySQL.
I do not get an error message but no data shows so what am I doing wrong?
PHP
<?php
if(strlen(trim($_POST['search'])) > 0) {
$search = "%" . $_POST["search"] . "%";
$searchterm = "%" . $_POST["searchterm"] . "%";
mysql_connect ("cust-mysql-123-03", "", "");
mysql_select_db ("weezycouk_641290_db1");
if (!empty($_POST["search_string"]))
{
}
$query = "SELECT name,lastname,email FROM contact WHERE name LIKE '%$search%' AND
lastname LIKE '%$searchterm%'";
$result = mysql_query ($query);
echo mysql_error();
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
echo $row["name"];
echo $row["lastname"];
echo $row["email"];
} ?>
<?php echo $row["name"]; ?>
<br>
<?php echo $row["lastname"]; ?>
<br>
<?php echo $row["email"]; ?>
<?php
}
}
?>
It should be like this:
<?php
if(strlen(trim($_POST['search'])) > 0) {
mysql_connect ("cust-mysql-123-03", "", "");
mysql_select_db ("weezycouk_641290_db1");
$query = "SELECT name,lastname,email FROM contact WHERE name LIKE '%" . mysql_real_escape_string($_POST['search']) . "%' AND lastname LIKE '%" . mysql_real_escape_string($_POST['searchstring']) . "%'";
$result = mysql_query ($query);
echo mysql_error();
if ($result) {
while ($row = mysql_fetch_assoc($result)) {
echo $row["name"];
echo $row["lastname"];
echo $row["email"];
} ?>
<?php echo $row["name"]; ?>
<br>
<?php echo $row["lastname"]; ?>
<br>
<?php echo $row["email"]; ?>
<?php
}
}
?>
The mysql_real_escape_string is to prevent mysql injection which is a serious risk.
Make sure the query you are executing returns record(s). You can check this by adding an echo statement which will print the query in your screen. Copy that and run it againist the database.You can use any mysql front end tools(php myadmin,mysqlyog to run the query. If there is any error in the query, you can see that then.
$query = "SELECT name,lastname,email FROM contact WHERE name LIKE '%$search%' AND
lastname LIKE '%$searchterm%'";
//the below line will print the query on the screen
echo $query;
$result = mysql_query ($query);