Is there a way to hide a section of html if it is used to display a php/mysql query result that comes back empty. Below is the query:
try
{
$park_id = $_GET['park_id'];
$query2="SELECT `name` FROM `tpf_rides` WHERE `park_id` = $park_id AND `top_ride` = 1 ORDER BY `name` ASC";
$result2 = $pdo->query($query2);
}
catch (PDOException $e)
{
$output = 'Unable to pull rides.';
include 'output.html.php';
}
$output = 'Sucessfully pulled rides';
//include 'output.html.php';//
and the part of code used to display the results:
<h2>Top Attractions</h2>
<ul>
<?php foreach ($result2 as $row2): ?>
<li><h3><?php echo $row2['name']; ?></h3></li>
<?php endforeach; ?>
</ul>
<hr>
There are a number of parks on the site that don't yet have top attractions - indicated by "top_ride = 1". Rather than have "<h2>Top Attractions</h2>" show up with no rides listed below I would ideally have the whole code above not show if there are no "top ride = 1" for a particular park.
Is this possible?
Thanks
Try this;
<?php
if($count = $query2->rowcount() < 1) {
echo "No results found";
} else {
echo "<h2>Top Attractions</h2>";
foreach($result2 as $row2) {
if(!empty($row2['name'])) {
echo "<li><h3>{$row2['name']}</h3></li>";
} else {
}
}
}
?>
Related
I am creating a result page using php to pull data from database.
I have been able to connect the database to my webspace and displayed the data.
Now , I would like to have the page not show all the data at once. I want to add an input field example "Origen= Los Angeles" "Destination = London" and then show the results based on that criteria.
This is my first time doing something like this so if this sounds like I should know this I'm sorry. I hope I can get some help.
<?php
// include connection settings
require_once "connect.php";
// display a list of flights
if(!empty($_GET) && !empty($_GET['name'])){
$query = "SELECT * FROM Flight_Information WHERE name LIKE ''".
$_GET['name']."".$_GET['name']."'";
} else {
$query = "SELECT ID, airlineName, departureAirport, departureDate, destinationAirport FROM Flight_Information";
} // END if
$result = $db->query($query);
if ($result) {
// ... display results in while loop
while ($row = $result->fetch_assoc()) {
echo '<li>'.$row['airlineName'].' '.$row['departureAirport'].''.$row['departureDate'].''.$row['destinationAirport'].'</li>';
} // END while
} else {
// if there was an error with your query
// this will display it
echo "SQL Error: " . $db->error;
} // END if
?>
</ul>
<?php
if (!empty($_GET) && !empty($_GET['Flight_Information_ID'])) {
$Flight_Information_ID = $_GET['Flight_Information_ID'];
$query = "SELECT * FROM Flight_Information WHERE ID =" . $Flight_Information_ID;
// perform the query
if ($result = $db->query($query)) {
// check we have a result
if ($result->num_rows > 0) {
// loop through and print out the results
while ($row = $result->fetch_assoc()) {
// output a title for each result
echo '<hr/><p>You have selected FriendShipper' .$Flight_Information_ID. ':</p> <ul>';
// loop through and output details for each item
foreach ($row as $key => $value) {
echo '<li><em>'.$key.'</em> = <strong>'.$value.'</strong></li>';
}
// output a horizontal rule under the result
echo '</ul><hr/>';
}
// num_rows = 0, no results found
} else {
echo "<p>No Flights Found " .$Flight_Information_ID. "</p>";
}
// if there was an error with your query, this will display it
} else {
echo "SQL Error: " . $db->error;
}
}
?>
I am making a blog and I want to fetch all rows using a pdo statement but no matter what I do only one row comes back even though there are two rows in my database.
Here's the code sample where I connect:
<?php
try{
$link=new PDO('mysql:host=127.0.0.1;dbname=blog1','root','');
$link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
echo $e->getMessage();
die();
}
?>
Then I try to fetch all rows
<?php
require 'Escape.php';
$posts_query=$link->query('SELECT * FROM posts');
$posts_query->execute();
/* variable that holds a with the database link and query in it then fetches
all the data related to the query into and assoc array */
$result=$posts_query->fetchAll();
//counting all rows
$count=$posts_query->rowCount();
if($count>0){
foreach($result as $r){
$id= $r['id'];
$title= $r['title'] ;
$content=$r['content'];
$date= $r['date'];
//admin buttons
$admin="";
//keeping title safe
$Title=htmlentities($title);
//keeping output safe
$output=htmlentities($content);
// styling the posts to be echoed with secure variables
$posts= "<div><h2><a href='view_post.php?pid=$id' class='names'>$Title</a>
</h2><h3>$date</h3><p>$output</p>$admin</div>";
escape($posts);
}
echo"<div id=posts>$posts</div>";
} else{
echo 'There are no posts to display.';
}
?>
Your $posts's value is reset to the latest row when you loop, either you append the value of each post using concat . operator:
if($count>0){
$posts = "";
foreach($result as $r){
// Define your variable
$posts .= "<div><h2><a href='view_post.php?pid=$id' class='names'>$title</a></h2><h3>$date</h3><p>$output</p>$admin</div>";
escape($posts);
}
echo"<div id=posts>$posts</div>";
} else { ... }
Or printing each post while looping:
if($count>0){
$posts = "";
echo "<div id='posts'>";
foreach($result as $r){
// Define your variable
$posts = "<div><h2><a href='view_post.php?pid=$id' class='names'>$title</a></h2><h3>$date</h3><p>$output</p>$admin</div>";
escape($posts);
echo $posts;
}
echo"</div>";
} else { ... }
Looks like you are re-assigning posts on every iteration, try adding the values to an array and imploding them when you would like to echo them out.
require 'Escape.php';
$posts_query=$link->query('SELECT * FROM posts');
$posts_query->execute();
$result=$posts_query->fetchAll();
$count=$posts_query->rowCount();
if($count>0){
$posts=[];
foreach($result as $r){
$id= $r['id'];
$title= $r['title'] ;
$content=$r['content'];
$date= $r['date'];
$admin="";
$Title=htmlentities($title);
$output=htmlentities($content);
// Add the HTML to the $posts array, also taking advantage of NOWDOCS
$posts[]= <<< HTML
<div>
<h2>
<a href='view_post.php?pid={$id}' class='names'>{$Title}</a>
</h2>
<h3>{$date}</h3>
<p>{$output}</p>
{$admin}
</div>
HTML;
escape($posts);
}
echo"<div id='posts'>" . implode('', $posts) . "</div>";
} else {
echo 'There are no posts to display.';
}
Here is a reference to PHP HEREDOCS.
I have a menu block that contains some links like: Some_link1: 5pcs, Some_link2: 13pcs, Some_link3: 0pcs, Some_link4: 0pcs.
I want to hide link "Some_link" with 0pcs value. I write a code with MySQL query, but it's not working! "Some_link" with 0pcs not hiding but still show 0pcs value.
What i'm doing wrong or what my mistake? I can't understand. Thank you for help.
<?
$resultonline = mysql_query("SELECT count(customers_id) from tbl_customers WHERE active='Y' and saled='N'");
$resultonshafasaled = mysql_query("SELECT count(customers_id) from tbl_customers WHERE shafa='Y' and saled='Y'");
$resultonlinenonactive = mysql_query("SELECT count(customers_id) from tbl_customers WHERE active='N' and saled='N'");
$topmenuNotOnShafa = mysql_result($resultonshafasaled, 0);
$topmenuonline = mysql_result($resultonline, 0);
$topmenuoffline = mysql_result($resultonlinenonactive, 0);
$topmenuonlineText = "Some text : ";
$topmenuOnShafaText = "Some text 2 : ";
?>
<?php if ($topmenuonline!=0): ?><?=$topmenuonlineText;?><?php endif; ?>
<?php if ($topmenuonline!=0): ?><?=$topmenuonline;?>
<?php endif; ?>
<?php if ($topmenuoffline!=0): ?> / <?=$topmenuoffline;?>
<br /><?php endif; ?>
<?php if ($topmenuNotOnShafa!=0): ?>
<span class="saled-warning"><a href="some_link" target="_self" ><?=$topmenuNotOnShafa;?></a></span>
<?php endif; ?>
You can check if the value of the item is 0 or not and print it only if it is not 0:
Example:
<?php
$items='0';
if(isset($items)){
if($items != 0){
echo "<a href='non_zero_item.php'>Item from menu (".$items.")";
} else {
echo "Oh sorry, there are no items!";
}
} else {
echo "items variable is not declared!";
}
?>
In this example you will get the else condition, if you change the variable $items to 1 you will get printed the html code. This is a small test, the variable can be the mysql query result, a manual input like this, etc.
If you dont want to print anything if the value is 0 or not declared, like I understand you want you can do only this:
<?php
$items='1';
if(isset($items)){
if($items != 0){
echo "<a href='non_zero_item.php'>Item from menu (".$items.")";
}
}
?>
For debuging I recommend you to use allways the else condition.
use
mysql_num_rows
<?php
$link = mysql_connect("localhost", "mysql_user", "mysql_password");
mysql_select_db("database", $link);
$result = mysql_query("SELECT * FROM table1", $link);
$num_rows = mysql_num_rows($result);
echo "$num_rows Rows\n";
?>
http://php.net/manual/en/function.mysql-num-rows.php
Hey guys so i really have a problem in php and i have been working on it for like an hour and i can get it to work. So in my database i have two tables:
usuarios and menus
So each user have a menu assigned like this:
usuarios
id email ....... menus
1 email ...... 1,2,3,4
where 1,2,3,4 is text that i will explode and convert it into an array so latter i can get the menus checking the menu id's.
menus
id url .....
1 profile ..........
2 messages ..........
3 log out ..........
4 support ..........
I dont know why it is not working, please help.
<?php
if (!empty($_SESSION['id'])) {
include_once "database.php";
$section = !empty($_GET['s']);
try {
$stmt = $db->prepare("SELECT * FROM usuarios WHERE id=:usuid");
$stmt->execute(array(':usuid'=>$_SESSION['id']));}
// Checks the user id from his session (session has been already started in headers)
if($stmt->rowCount() > 0){
$row = $stmt->fetch();
$menus = $row['menus'];
//Gets the menus
$menus = explode(",", $menus);
//Converts the text into an array.
$i = 0;
$menusize = sizeof($menus);
//Checks how big is $menus array
$menusize = $menusize -1;
//This is because $i=0 and not 1
while ($i == $menusize) {
try{
$stmt = $db->prepare("SELECT * FROM menus WHERE id=:menus");
$stmt->execute(array(':menus'=>$menus[$i]));
$row = $stmt->fetch();
if ($section==$row['url']) {
echo '<li class="liselected"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}else{
echo '<li class="menuelement"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}
$i++;
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
//Here is the problem, in this while
} else {
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}else{
header("Location:index.php");
}
?>
I have checked and what happends is that $i doesnt seems to be incrementing, i have been working on it but nothing seems to do it.
Thank you all for your support!
You should do it a little bit differently altogether, like storing the menu's in different rows but for now:
<?php
if (!empty($_SESSION['id'])) {
include_once "database.php";
$section = !empty($_GET['s']);
try {
# When you set the $_SESSION['id'] and you're sure it's sanitized you don't have to prepare a query. Instead execute it directly.
# Preparing is useful for user submitted data or running the same query more then once with different values (seen below)
$stmt = $db->prepare("SELECT * FROM usuarios WHERE id=:usuid");
$stmt->execute(array(':usuid'=>$_SESSION['id']));
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if($stmt->rowCount() > 0){
// This part of the code does not match your description of your database.
$row = $stmt->fetch();
$menu = explode(",", $row['menus']);
// end
$stmt = $db->prepare("SELECT * FROM menus WHERE id=:menus");
try{
foreach($menu as $value){
$stmt->execute(array(':menus'=>$value));
$row = $stmt->fetch();
$css_class = ($section == $row['url']) ? 'liselected' : 'menuelement';
echo '<li class="'.$css_class.'"><i class="'.$row['icon'].'"></i><p>'.$row['name'].'</p></li>';
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
} else {
header("Location:index.php");
}
?>
Please note that I only prepared the query once, this is the proper way to do it. Preparing takes server performance, but once prepared you can rebind the values.
Also, I changed the loop to a foreach loop, easier to maintain.
There where also some bracket issues in the code, my advice always code in the same way so these issues are easy to spot.
im having a simple mysql/php problem. so i am adding in Image titles for my website, and the code is displayed below. It works, but when you dont put a image, it shows up as blank. I need it to show up as 'No image title' (bc i will use this for image description to). It basically gets the image name, then takes the title from that row.
So how do i do it? :/ im still very new to PHP.
<?php
if (isset($imgtitleset))
{
$sql = "SELECT image_title FROM images WHERE image_name = '$image_main'";
$result = mysql_query ($sql);
while ($row = mysql_fetch_array($result))
{
$imgtitle= $row["image_title"];
echo "$imgtitle";
}
}
else {
echo 'no image title';
}
?>
Change the while loop like so:
while ($row = mysql_fetch_array($result)) {
$imgtitle= $row["image_title"];
if($imgtitle != '') {
echo $imgtitle;
} else {
echo 'no image title';
}
}
Also, I'm not sure what the $imgtitleset variable is for, but you can probably get rid of the if statement checking to see whether it's set.
Edit: the whole thing should probably look like this:
<?php
$sql = "SELECT image_title FROM images WHERE image_name = '$image_main'";
$result = mysql_query ($sql);
while ($row = mysql_fetch_array($result)) {
$imgtitle= $row["image_title"];
if($imgtitle != '') {
echo $imgtitle;
} else {
echo 'no image title';
}
}
?>
This all depends on what $imgtitleset is equal to. It is clearly set against something:
while ($row = mysql_fetch_array($result)) {
$imgtitle = $row["image_title"];
if (isset($imgtitle))
echo "$imgtitle";
else
echo 'no image title';
}
This would mean if nothing was found in the database then it will echo the no image title. However like I said, this could depend on what $imgtitleset is, maybe post the code for that?
If you only expect the select to return a single row, then use if rather than while and return the error on else:
<?php
if (isset($imgtitleset))
{
$sql = "SELECT image_title FROM images WHERE image_name = '$image_main'";
$result = mysql_query ($sql);
if ($row = mysql_fetch_array($result))
{
$imgtitle= $row["image_title"];
echo "$imgtitle";
}
else {
echo 'no image title';
}
}
?>