If database field is empty echo "nothing" if something there echo "something" - php

looking for a solution to this bit of coding below.
<?php
$nextfive_events = mysql_query("SELECT date_format(date, '%d/%m/%Y') AS formatted_date, title, location, regs FROM events WHERE status = 'ACTIVE'");
if(mysql_num_rows($nextfive_events) == 0) { echo "<p>No events coming up!"; } else {
echo "<table width=\"600\" border=\"0\" cellpadding=\"2\" cellspacing=\"2\" class=\"greywritinglight\" align=\"left\">
<tr align=\"center\">
<td>Date</td>
<td>Name</td>
<td>Location</td>
<td></td>
</tr>";
$x=1;
while($next_row = mysql_fetch_array($nextfive_events))
{
if($x%2): $rowbgcolor = "#FFFFFF"; else: $rowbgcolor = "#EEEEEE"; endif;
echo "<tr align=\"center\">";
echo "<td>" . $next_row['formatted_date'] . "</td>";
echo "<td>" . $next_row['title'] . "</td>";
echo "<td>" . $next_row['location'] . "</td>";
echo "<td>Regs</td>";
echo "</tr>";
$x++;
}
echo "</table>";
}
?>
I want the row echo "<td> <a href regs .....
To display the word Regs when there is something in 'regs' in the database. Say if there is nothing in that field I want it to be blank and not say Regs.
thanks

You could do Ternary operator:
echo "<td><a href='" . (empty($next_row['regs']) ? "#" : $next_row['regs']) . "'>Regs</a></td>";
Try not to do escape characters, they look confusing, do single quote for href attribute. Also, Did you want
<a href='#'>Regs</a>
to show if it was blank?
If Not, try this:
echo (!empty($next_row['regs']) ? "<td><a href='" . $next_row['regs'] . "'>Regs</a></td>" : "");

You could use a ternary:
echo ( ! empty($next_row['regs'])) ? '<td>Regs</td>' : '<td>&nspb;</td>';

First off, I'd like to show you a really handy trick with PHP that allows you to echo out into HTML without actually saying echo. Just create a break in your PHP code, and in between anything you put will be echoed as HTML.
As for the number of rows returned, you are doing it correctly. Make sure that you are querying properly, that you have an established connection, and that there are no logical errors in your SQL.
Sorry, didn't notice you wanted to check if the column was empty! Just use the function empty(). This function will return true when the data you give it is empty, so simply give it the column from the row of data you wish to check.
<?php
// Lets say this is your database connection variable
$connection = mysqli_connect(//Your info goes here);
// This is the query you want to run
$query = "SELECT something FROM somewhere WHERE something='$something_else'";
// This is where you are storing your results of the query
$data = mysqli_query($connection, $query);
// Here, you can ask for how many rows were returned
// In PHP, ZERO is evaluated to false. We can use a
// Short-hand boolean expression like this
if (mysqli_num_rows($data))
{
// Because zero evaluates to false, we know
// that if we get HERE that there ARE rows
// We can break out of PHP and into our HTML
// by simply ending our PHP tag! Just remember
// that you need to open it back up again though!
?>
<!--You can put your HTML here-->
<p>
We found some rows that you might
need to know about!
</p>
<?php
}
else
{
// But, if we get here, we know it evaluated as
// FALSE and therefore no rows returned
// Here's that HTML trick again
?>
<!--HTML can go here-->
<p>
No rows returned!
</p>
<?php
}
?>

Related

PHP While HTML Table

I am trying to get my code to display in an HTML table using the while loop. However, I can't get my table to display. Is there something wrong with the way I am trying to echo the table out?
<?php
#-----call includes-----# include('E:/includes/database.php');
include('E:/includes/sendmail.php');
ini_set('error_reporting', E_ALL ^ E_NOTICE);
ini_set('display_errors','on');
$do = $_REQUEST['do'];
$queryOrders = "select t2.SlpName As 'Seller', t1.SWW As 'Vendor', t0.DocDate As 'Date',t0.DocTotal As 'Total'
from twh.dbo.OINV t0
inner join twh.dbo.inv1 t1 on t0.DocEntry = t1.DocEntry
inner join twh.dbo.OSLP t2 on t1.SlpCode = t2.SlpCode
where t0.DocDate > DATEADD (month, -2, getdate())
order by t0.DocTotal desc";
$resultItemData = sqlsrv_query($con, $queryOrders);
echo "<table border=\"1\" align=\"center\">";
echo "<tr><th>Seller</th>";
echo "<th>Vendor</th>";
echo "<th>Date</th>";
echo "<th>Total</th></tr>"
while($rowItemData = sqlsrv_fetch_array($resultItemData)){
echo "<tr><td>";
echo "$resultItemData";
echo "</td></tr>";
endwhile;
}
echo"</table>";
Modified a little bit. Check this:
while($rowItemData = sqlsrv_fetch_array($resultItemData)) :
echo "<tr><td>";
echo $rowItemData[ColumnValue]; //In your code, didn't access the column value earlier
echo "</td></tr>";
endwhile;
There's a combination of problems at play:
First, you open the while with {, but close with endwhile; - while technically not a problem, it's not consistent - if you open with {, it's best practice to close with }.
Second, you're attempting to echo an entire array, which won't work properly.
Third, no need to put the value inside of quotes: echo "$resultItemData"; could simply be echo $resultItemData.
Fourth, you're attempting to echo $resultItemData, which is a resource, not the row data. You want to echo $rowItemData values.
And finally, you'll likely want the results in an associative array, rather than a numerically-indexed array, so you might consider using sqlsrv_fetch_array( $resultItemData, SQLSRV_FETCH_ASSOC).
Below is your code, revised to work, and follow a bit better practices:
// columns: 'Seller',Vendor, 'Date', 'Total'
while( $rowItemData = sqlsrv_fetch_array( $resultItemData, SQLSRV_FETCH_ASSOC ) ) {
echo "<tr><td>";
echo "<td>$rowItemData['Seller']</td>";
echo "<td>$rowItemData['Vendor']</td>";
echo "<td>$rowItemData['Date']</td>";
echo "<td>$rowItemData['Total']</td>";
echo "</tr>";
}
You should specify the indexes of the array $rowitemdata.
For example:
echo"<tr><td>".$rowitemdata['Vendor']."
I haven't gone through your full code, but I can see wrong syntax for while
while($rowItemData = sqlsrv_fetch_array($resultItemData)){
echo "<tr>";
echo "<td>".$resultItemData['Seller']."</td>";
echo "<td>".$resultItemData['Vendor']."</td>";
echo "<td>".$resultItemData['Date']."</td>";
echo "<td>".$resultItemData['Total']."</td>";
echo "</tr>";
}
or
while($rowItemData = sqlsrv_fetch_array($resultItemData)) :
echo "<tr>";
echo "<td>".$resultItemData['Seller']."</td>";
echo "<td>".$resultItemData['Vendor']."</td>";
echo "<td>".$resultItemData['Date']."</td>";
echo "<td>".$resultItemData['Total']."</td>";
echo "</tr>";
endwhile;
Update:
still you can optimize the code, I just gave sample working
Let's assume your query actually produces a result, because you don't check that it does:
$resultItemData = sqlsrv_query($con, $queryOrders);
$header = <<<HEREDOC
<table border="1" align="center">
<tr>
<th>Seller</th>
<th>Vendor</th>
<th>Date</th>
<th>Total</th>
</tr>
HEREDOC;
echo $header;
while($rowItemData = sqlsrv_fetch_array($resultItemData)) {
echo "<tr>
<td>{$rowItemData['Seller']}</td>
<td>{$rowItemData['Vendor']}</td>
<td>{$rowItemData['Date']}</td>
<td>{$rowItemData['Total']}</td>
</tr>";
}
echo '</table>';
To actually check that the query works, you might want to do this instead. This is just to debug/illustrate error checking for the query execution. You wouldn't want to output an error to the screen, but rather log it. You probably want to just output the table header/footer and skip the while/loop entirely.
$resultItemData = sqlsrv_query($con, $queryOrders);
if (resultItemData === false) {
die(print_r(sqlsrv_errors(), true));
}

How can I use hyperlinks in PHP to display data on the page it sends you to?

I have this piece of code below. It displays the image and name of all the entries in a table in my database. The name is set up to become a hyperlink.Is it possible to make it so when one specific name is clicked that data for only that specific name will be displayed on the page you are sent to?
So for example if I select the first entry that is displayed back "mealname1" and it takes me to the showrecipe.php page, can I make it so I can display all the data I have for "mealname1" and only "mealname1". I'm really lost, I have scoured the internet and my php books but can't find anything to that is relevant.
If there is no way of doing it is there an obvious solution that I am missing?... I am very much a novice to this... thanks for your help guys.
<?php
require("db.php");
$prodcatsql = "SELECT * FROM recipes";
$prodcatres = mysql_query($prodcatsql);
$numrows = mysql_num_rows($prodcatres);
if($numrows == 0)
{
echo "<h1>No Products</h1>";
echo "There are no recipes available right now.";
}
else
{
echo "<table id='recipetable'>";
while($prodrow = mysql_fetch_assoc($prodcatres))
{
echo "<tr>";
if(empty($prodrow['image'])){
echo "<td><img
src='./images/No_image.png' alt='"
. $prodrow['mealname'] . "'></td>";
}
else {
echo "<td><img src='./images/".$prodrow['image']
. "' alt='"
. $prodrow['mealname'] . "'></td>";
}
echo "<td>";
echo ''.$prodrow['mealname'].'';
echo "</td>";
echo "</tr>";
}
echo "</table>";
}
?>
Change the query to
SELECT * FROM recipes WHERE mealname='$mealname' LIMIT 1;
You can remove "LIMIT 1" if you want but this makes sure you will only get 1 or 0 row back. Don't forget to escape the string.

php - using a hyper link to send variable used in data base to use get command to echoe results

I have a table with arrays pulling information from a database, I have linked the fix to be a hyperlink "click me for fix" I have entered the link to send the variable to a php that will use $GET to echoe the information.
code below , i am new to php and been racking brains . the only out put i get is Welcome . (done welcome to test if information was being passed)
<div id=list>
<?php
// Create connection
$con=mysqli_connect('172.16.254.111',"user","password","Faults"); //(connection location , username to sql, password to sql, name of db)
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//where statement in the sql syntax will select where in db to get infor, use AND to add another condition
$result = mysqli_query($con,"SELECT * FROM Fixes WHERE Product='Serv1U' AND Fault_type='Broadcast Manager'"); //this creates a variable that selects the database
//below is the echo statment to create the results in a table format, list collumn titles
echo "<table id=tables border='1'>
<tr>
<th>Products</th>
<th>Fault_type</th>
<th>Fault_Description</th>
<th>Fix</th>
</tr>";
//below is script to list reults in a table format, $row [row name on table]
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Product'] . "</td>";
echo "<td>" . $row['Fault_type'] . "</td>";
echo "<td>" . $row['Fault_Description'] . "</td>";
echo "<td>Click for Fix</td>"; //this is how you link into an echo, alsothe id=" hopefully means i can send ID information.
}
echo "</tr>";
echo "</table>";
// below closes the coonection to mysql
mysqli_close($con);
index.php:
Welcome <?php echo $_GET["Fix"]; ?>.
I'm lost. Any help is appreciated.
Thanks
?>
Is it just a typo here? $GET must be $_GET.
And it should be $row['Fix'] not $rows['Fix']! Note the 's'!

How do I comment out php to add a HTML form within a php print?

Here is my code, works fine and prints out everything I want it to. But on the end of each cell I would like a form that makes a button which will allow the user to configure the item that the row in the table describes. I want to know how I can escape out of php to use html again, I've tried double quotes but this does not work, I was wondering if anyone could explain to me how to do this.
<?php
$data = mysql_query("SELECT * FROM basestation WHERE email_address ='$email'")
or die(mysql_error());
Print "<table border = 1>";
while( $info = mysql_fetch_array( $data ) ) {
Print "<tr>";
Print "<th>Name:</th> <td>".$info['base_station_id'] . "</td>";
Print "</tr>";
Print "<tr>";
Print "<th>Serial Number:</th> <td>".$info['serial_no'] . "</td> ";
Print "</tr>";
}
Print "</table>";
?>
PHP code will only being executed between the opening <?php and the closing ?> php tags. However you are free to use multiple php sections per file.
So, you can just close the PHP section using ?> . Then after writing HTML content you can open <?php again.
Here comes a little example. It creates a couple of <a> achors from an imaginal array $links:
<?php
foreach($links as $link) { ?>
<?php echo $link['title'];?>
<?php }
Note that this mostly leads to unreadable code. But it is possible and can be used.
Also not that there is short syntax available for shorter echo syntax. But you'll have to make sure that it is enabled in your php configuration. Using the shorter syntax, may example from above could look like this:
foreach($links as $link) { ?>
<?=$link['title'];?>
<? }
You'll find a good documentation on the PHP website
You are already using the PHP delimiters <?php and ?>. Use these to switch back to HTML within the document also.
<?php
function foo(bar) {
return bar == 1 ? 'bar' : 'nobar';
}
?>
<h1>Heading with just HTML</h1>
<div class="<?php print foo(1); ?>">This is a div with a dynamic class.</div>
<?php
// and php again
?>
Just make a link to a page with the id in the url
Print "<tr>";
Print "<th>Edit:</th><td>Edit</td> ";
Print "</tr>";
Then on edit.php you can get the id ($_GET['id']) and query the database.
<?php
$data = mysql_query("SELECT * FROM basestation WHERE email_address ='$email'")
or die(mysql_error());
Print "<table border = 1>";
while( $info = mysql_fetch_array( $data ) ) {
Print "<tr>";
Print "<th>Name:</th> <td>".$info['base_station_id'] . "</td>";
Print "</tr>";
Print "<tr>";
Print "<th>Serial Number:</th> <td>".$info['serial_no'] . "</td> ";
?>
<-- form here --->
<?php
Print "</tr>";
}
Print "</table>";
?>

PHP SQL Display images

I've written a php code to display all the images. But there's is something wrong in the code and I can't fix it. It's kind of a syntax error but I've wasted hours over it and still mixing up the "quotes(')"..here's my php code:
while($row = mysql_fetch_array($display_query)){
print "<tr><td>".$row['itemid']."</td><td><img src="resources/wh/'.$row['itemid'].'.png"/></td><td>".$row['description']."</td><td>";
print "₹".$row['cost']."</td></tr>";
}
"<tr><td>".$row['itemid']."</td><td><img src="resources/wh/'.$row['itemid'].'.png"/></td><td>".$row['description']."</td><td>";
Should be
"<tr><td>".$row['itemid'] . '</td><td><img src="resources/wh/'.$row['itemid'].'.png"/></td><td>'.$row['description']."</td><td>";
But mix ' and " make your code a mess, you could use HEREDOC to make it more readable.
while($row = mysql_fetch_array($display_query)){
echo <<<EOF
<tr>
<td>{$row['itemid']}</td>
<td><img src="resources/wh/{$row['itemid']}.png"/></td>
<td>{$row['description']}</td>
<td>₹{$row['cost']}</td>
</tr>
EOF;
}
Your concatenation of string and quotation is not right. Try this -
while($row = mysql_fetch_array($display_query)){
print "<tr><td>" . $row['itemid']."</td><td><img src=" . 'resources/wh/' .$row['itemid']. ".png'/></td><td>".$row['description'] . "</td><td>";
print "₹".$row['cost']."</td></tr>";
}
The simplest solution is just make proper pencuation in your code.
The correct code is:
print "<tr><td>".$row['itemid']."</td><td><img src='resources/wh/".$row['itemid'].".png'/></td><td>".$row['description']."</td><td>";
from db we get column value of rating $number=$row->rating ;
if we want TO print image as rating value in a table row then
then
$number=$row->rating ;
$middle="";
$first="<td width='200' align='left'>";
for($x=1;$x<=$number;$x++) {
$middle=$middle.img($fullimage_properties);
}
if (strpos($number,'.')) {
$middle=$middle.img($halfimage_properties);
$x++;
}
while ($x<=5) {
$middle=$middle.img($blankimage_properties); ;
$x++;
}
echo $last=$first.$middle."</td>";

Categories