Inserting php if statement within php code? - php

I have a php script that is basically querying my database and providing details about each store, and including an image. The code pulls in the image fine, but currently if no image exists in the database, I have spacer image being inserted instead. Instead of using a spacer image though, is there a way for me to use a PHP 'if' statement inside of the php code to not render an image if the database has no image listed? Here is the basic query code:
<?php
if(strlen($query) >= $min_length){$query = htmlspecialchars($query);
$query = mysql_real_escape_string($query);
$raw_results = mysql_query("SELECT * FROM stores WHERE `TRAVEL` = '1' AND `STATE` = '$query'") or die(mysql_error());
if(mysql_num_rows($raw_results) > 0){
while($results = mysql_fetch_array($raw_results)){
echo "<table width='150' border='3'>
<tbody><tr>
<td>".$results['NAME']."<br>
<img align='left' src='images/images/".$results['IMAGE']."'>
</td>
</tr></tbody>
</table>";
}
} else{ echo "No results were found";
}
} else{ echo " ".$min_length; }
?>
For the php if statement, I was thinking something along these lines:
<?php if ($results['IMAGE'] != '') { ?>
<img src='images/icons/".$results['IMAGE']."' height="100" width="auto">
<?php }?>

You're pretty close. Just use one more <?php ... ?> block in the img
<?php if ($results['IMAGE'] != '') { ?>
<img src='images/icons/<?php echo $results['IMAGE'] ?>' height="100" width="auto">
<?php }?>
You can use the alternative control flow syntax too. It reads a little nicer than spanning the { and } across multiple <?php tags
<?php if ($results['IMAGE'] != ''): ?>
<img src='images/icons/<?php echo $results['IMAGE'] ?>' height="100" width="auto">
<?php endif ?>
Shameless plug:
Generating HTML with PHP gets really ugly. At least in my opinion. To make the job a little nicer/easier, I made htmlgen, mirrored on packagist.

Simply like this :
if(isset($results['IMAGE'])){
echo "<table width='150' border='3'>
<tbody><tr>
<td>".$results['NAME']."<br>
<img align='left' src='images/images/".$results['IMAGE']."'>
</td>";
}

Related

Creating a table in HTML to display the result of a query in MySQL

I want to create a PHP page to display the results of a query in a MySQL database under the format of a table. By spending quite some time on different forums, I ended with something that is somehow satisfying me but that is strongly affecting the design and the layout of my webpage. Due to the fact that I wrote the code by a test-fail strategy, it is far from being straightforward and I am sure it is possible to shorten and simplify it and, therefore, make it more compatible with the format of my webpage. Could anybody have a look at it and give some suggestions of general interest about how to solve this kind of issues?
<div id="main">
<?php
require_once('../mysqli_connect.php');
$response = $db->query("SELECT * FROM metabolite");
echo '<table align="center" cellspacing="2" cellpadding="5" border = "1">
<tr><td align="center"><b>Metabolites</b></td>
<td align="center"><b>KEGG Id</b></td>
<td align="center"><b>Synonyms</b></td></tr>';
while ($data = $response->fetch())
{
?>
<tr><td align="left">
<?php echo $data['Metabolite_name']; ?></td>
<td align="left">
KEGG: <?php echo $data['Synonyms']; ?></td>
<td align="left">
<?php echo $data['Synonyms']; ?></td>
</tr>
<?php
}
$response->closeCursor();
?>
</div>
I thank you in advance for all your effort and your help.
Tom.
There's no way we can improve the design and layout of your webpage with the code you've given us. What I can do is write 'better' readable code.
<?php
function tableCell($content)
{
echo '<td align="left">'.$content.'</td>';
}
// database access
require_once('../mysqli_connect.php');
// get all records from the metabolite table
$response = $db->query("SELECT * FROM metabolite");
// start main division
echo '<div id="main">';
// start the table
echo '<table align="center" cellspacing="2" cellpadding="5" border = "1">';
// walk through all the metabolite records
while ($data = $response->fetch())
{
// start a row
echo '<tr>';
// create the cells
tableCell($data['Metabolite_name']);
tableCell('KEGG: '.$data['Synonyms']);
tableCell($data['Synonyms']);
// finish a row
echo '</tr>';
}
// close the table
echo '</table>';
// close main division
echo '</div>';
// close query
$response->closeCursor();
But this is not worth much, the output should remain the same.
if ($response->num_rows > 0) {
while($data = $response->fetch_assoc()) {
echo "<tr><td>" . $data["Metabolite_name"]. "</td></tr>" . ;
}
}
else {
echo "0 results";
}

3x3 table with random images - PHP

I'm new here and need some help. I'm doing a web development course and have an assignment I need a hand with.
Basically, I want to send a query that picks 9 random records, and show the result as a 3x3 table.
Here's my code so far:
<div id="productgrid">
<?php
$query = mysqli_query($conn, "SELECT * FROM products
ORDER BY RAND()
LIMIT 9");
?>
<h2>Featured Products</h2>
<table>
<?php
while($products = mysqli_fetch_array($query)){
$file = $products['prod_img'];
$pid = $products['prod_id'];
$product_price = $products['prod_price'];
$image_id = $products['prod_id'];
$desc = $products['prod_desc'];
?>
<tr>
<div class="bigred">
<td class="bigred">
<?php echo '<b>'. "$product_price".'</b>'; ?>
</td>
</div>
</tr>
<tr>
<td>
<img src="<?php echo $file ?>" height = "150px" width="150px"/><br />
</td>
<div class="smallblack"
</tr>
<tr>
<td class = "smallblack">
<?php echo '<b>' . "$desc".'</b>'; ?>
</td>
</tr>
</div>
<?php } ?>
I can get it to generate the 9 random images but it puts them all directly under each other in one long column. Is there a way I can get them to display in 3 rows of 3?
I apologise if this is a dumb question, but I'm only starting out and appreciate the help.
Thank you :)
Pic attached as sample
<?php
// A counter which is incremented by one for each product row
// in the loop below.
$i = 0;
echo "<table>\n";
echo "<tr>\n";
while ($product = mysqli_fetch_array($query)) {
// Re-open HTML row, if $i is divisible by 3
if ($i++ % 3 == 0) {
echo "</tr><tr>\n";
}
// Escape the `src` attribute value as appropriate, according to the
// logic of your app. This is just a sample.
$img_src = htmlspecialchars($product['prod_img']);
echo <<<HTML
<td>
<div><img src="{$img_src}"/></div>
<div>{$product['prod_desc']}</div>
<!-- Put the rest of the fields here -->
</td>
HTML;
}
// Add cells for the rest of the columns (if any)
while ($i++ % 3 != 0) {
echo "<td></td>\n";
}
echo "</tr>\n";
echo "</table>\n";
?>
P.S.: I recommend using a template engine such as Smarty, or Twig. With the help of a template engine you can make the markup much more readable and maintainable.
You should change your table out put and use 3 <td> tags instead of just the one, like so...
<table>
<tr>
<?php
$counter = 0; // Needs to be outside of the loop...
while($products = mysqli_fetch_array($query)){
$file = $products['prod_img'];
$pid = $products['prod_id'];
$product_price = $products['prod_price'];
$image_id = $products['prod_id'];
$desc = $products['prod_desc'];
?>
<td class="bigred">
<?php echo '<b>'. "$product_price".'</b>'; ?>
<img src="<?php echo $file ?>" height = "150px" width="150px"/><br />
<?php echo '<b>' . "$desc".'</b>'; ?>
</td>
<?php
// Check to see if you have looped through three times and close the <tr> tag.
if($counter % 3 === 0) {
echo '</tr><tr>';
}
$counter++
?>
</table>
If there is more than 9 images, then it will keep creating table rows and cells and you will need more logic to handle that, however, this should work for 9 images.
A more elegant way to handle this would be to use <div> tags and floats, but since you are already using a table, I formatted it as such.

Displaying an image in php

how to display blank if there is no image in a record.As i have inserted a record in database without an image but while fetching an record it is displaying an blank image in front end.It should not show any image if there is no image.Here is my code. If there is no image it should show only description.
Blogimage.php
<tbody>
<?php include "blogs.php" ;
while($row = mysql_fetch_array($result))
{?>
<tr>
<td><img src="admin/upload/<?php echo $row['image'];?>" height="100" style="width:60%;height:50%;"/></td>
</tr>
<tr>
<td><?php echo "<p style='width:60%;'>" .$row['blog_description']."</p>"; ?></td>
</tr>
<?php }?>
</tbody>
Blogs.php
$id=$_GET['title'];
$res = "SELECT * FROM blogs
WHERE blog_title='$id'";
$result=mysql_query($res);
try changing this
<img src="admin/upload/<?php echo $row['image'];?>" height="100" style="width:60%;height:50%;"/>
to this
<?php if($row['image']) echo "<img src='admin/upload/".$row['image']."' height='100' style='width:60%;height:50%;' />"; ?>
A couple of general points before we go into this
1) The MySql library you are using is old and busted - you should be using something newer - read this - the options are Mysql PDO and MySqli - I promise you, you will be glad you did, i use IDIORM as an interface and find it very good (Also helps prevent stuff in point 2 below!)
2) Your code can be SQL injected - more about that here - this is very bad :)
Below is an example, I have fixed the SQL injection problem, and put in some logic that would test to see if there is an image, if not, it will dump out a 'noimage.jpg' src value.
I have removed the include, and just simply put the code for blogs.php inline.
<tbody>
<?php
//START CODE FOR BLOGS.PHP
$query = sprintf("SELECT * FROM blogs WHERE blog_title='%s'",
mysql_real_escape_string($_GET['title']));
$result = mysql_query($query);
//END CODE FOR BLOGS.PHP
while($row = mysql_fetch_array($result))
{
if(!empty($row['image']) && strlen($row['image']) > 4)
{
$iamgeSrc = 'admin/upload/' . $row['image'];
}
else
{
$imageSrc = 'admin/upload/noimage.jpg';
}
?>
<tr>
<td>
<img src="<?php echo $imageSrc; ?>" height="100" style="width:60%;height:50%;"/>
</td>
</tr>
<tr>
<td>
<?php echo "<p style='width:60%;'>" .$row['blog_description']."</p>"; ?>
</td>
</tr>
<?php
}
?>
</tbody>
If you want no image to show at all, then this would work
<tbody>
<?php
//START CODE FOR BLOGS.PHP
$query = sprintf("SELECT * FROM blogs WHERE blog_title='%s'",
mysql_real_escape_string($_GET['title']));
$result = mysql_query($query);
//END CODE FOR BLOGS.PHP
while($row = mysql_fetch_array($result))
{
$image = '';
if(!empty($row['image']) && strlen($row['image']) > 4)
{
$image = '<img src="admin/upload/'.$row['image'].'" height="100" style="width:60%;height:50%;"/>';
}
?>
<tr>
<td>
<?php echo $image; ?>
</td>
</tr>
<tr>
<td>
<?php echo "<p style='width:60%;'>" .$row['blog_description']."</p>"; ?>
</td>
</tr>
<?php
}
?>
</tbody>

displaying table with images with PHP

I need to generate a table with php, that will display the images - names stored on database. It has to display 3 images in a row. The images are added to the database all the time, so I need that to be automatically generated, instead of hard coding the tables. I am not sure how do I do that? Please help!
You need to cycle the result recordset and print out the new row every 3rd element.
For example:
<table>
<tr>
<?php $i=0; foreach ($images as $image): ?>
<td><?php echo $image['name'] ?> <img src="<?php echo $image['path'] ?>" /></td>
<?php if(++$i%3==0): ?>
</tr><tr>
<?php endif ?>
<?php endforeach ?>
</tr>
</table>
suppose u get the all images name from database in an array
$img_array = array(
1=>'f.jpg',
2=>'s.jpg',
3=>'t.jpg',
4=>'f.jpg',
5=>'e.jpg'
);
// now create dynamic table via php
<table border="1" cellpadding="2" cellspacing="2" width="100%">
<tr>
<?php
$i=0;
foreach($img_array as $k){
if($i%3==0) { ?> </tr><tr> <?php } ?>
<td><img src="<?php echo $k?>" border="0"></td>
<?php $i++; } ?>
</tr>
</table>
Note: please write full path of image in src before <?php echo $k?>
Iterate the image records, using modulo 3 to change to the next table row.
Something like:
echo '<table><tr>';
foreach ($images) {
echo '<td>$image</td>';
if ($i % 3 == 0) {
echo '</tr><tr>';
}
}
echo '</tr></table>';
A simple table like that would be like
<table>
<tr><td>1</td><td>2</td><td>3</td></tr>
<tr><td>1</td><td>2</td><td>3</td></tr>
</table>
To generate this automatically you need to store where you are in the table, first col, 2nd col or 3th col.
<?php
$pos = 1;
print "<table>"
for ($i=0; $i<=10;$i++)
{
if ($pos==1)
{
print "<tr><td>1</td>";
$pos=2;
}
else if ($pos==2)
{
print "<td>2</td>";
$pos=3;
}
else if ($pos==3)
{
print "<td>3</td></tr>";
$pos=1;
}
}
if ($pos==2 || $pos==3)
print "</tr>";
print "</table>"
Keep in mind that if you use the options with $i%3 from the other comments, that your table will start end/or finish with an empty row. This would need additional checks. The $i%3 will give the remainder of the division of $i and 3. So when $i/3 == 0, means it is true on every third row.

member control through admin account using php

I am new to php.
I made a member registration on login page and adm too. So inside admin I wanted to get the list of the members and delete the members I dont want. So I took the a code from a sample code for phone book from http://localhost/xamp and editted it to my requirement I am able to retrieve the members but unable to delete the members. See the code below:
<?php
require_once('auth.php');
require_once('../config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
?>
<html>
<head>
<meta name="author" content="Kai Oswald Seidler">
<link href="../loginmodule.css" rel="stylesheet" type="text/css">
<title></title>
</head>
<body>
<p>
<h2><?php echo "User list"; ?></h2>
<table border="0" cellpadding="0" cellspacing="0">
<tr bgcolor="#f87820">
<td><img src="img/blank.gif" alt="" width="10" height="25"></td>
<td class="tabhead"><img src="img/blank.gif" alt="" width="150" height="6"><br><b><?php echo $TEXT['phonebook-attrib1']; ?></b></td>
<td class="tabhead"><img src="img/blank.gif" alt="" width="150" height="6"><br><b><?php echo $TEXT['phonebook-attrib2']; ?></b></td>
<td class="tabhead"><img src="img/blank.gif" alt="" width="150" height="6"><br><b><?php echo $TEXT['phonebook-attrib3']; ?></b></td>
<td class="tabhead"><img src="img/blank.gif" alt="" width="50" height="6"><br><b><?php echo $TEXT['phonebook-attrib4']; ?></b></td>
<td><img src="img/blank.gif" alt="" width="10" height="25"></td>
</tr>
<?php
$firstname=$_REQUEST['firstname'];
$lastname=$_REQUEST['lastname'];
$phone=$_REQUEST['phone'];
if($_REQUEST['action']=="del")
{
$result=mysql_query("DELETE FROM members WHERE member_id={$_REQUEST['member_id']}");
}
$result=mysql_query("SELECT member_id,firstname,lastname,login FROM members ORDER BY lastname");
$i = 0;
while($row = mysql_fetch_array($result)) {
if ($i > 0) {
echo "<tr valign='bottom'>";
echo "<td bgcolor='#ffffff' height='1' style='background-image:url(img/strichel.gif)' colspan='6'></td>";
echo "</tr>";
}
echo "<tr valign='middle'>";
echo "<td class='tabval'><img src='img/blank.gif' alt='' width='10' height='20'></td>";
echo "<td class='tabval'><b>".$row['lastname']."</b></td>";
echo "<td class='tabval'>".$row['firstname']." </td>";
echo "<td class='tabval'>".$row['member_id']." </td>";
echo "<td class='tabval'><a onclick=\"return confirm('".$TEXT['userlist-sure']."');\" href='userlist.php?action=del&member_1d=".$row['member_id']."'><span class='red'>[".$TEXT['userlist-button1']."]</span></a></td>";
echo "<td class='tabval'></td>";
echo "</tr>";
$i++;
}
echo "<tr valign='bottom'>";
echo "<td bgcolor='#fb7922' colspan='6'><img src='img/blank.gif' alt='' width='1' height='8'></td>";
echo "</tr>";
?>
</table>
</body>
</html>
I haven't editted it that properly and the looks in all.
Please help me in making it able to delete the members also.
I didn't understand what .$TEXT['userlist-button1'].,'".$TEXT['userlist-sure']. variables are?
I also want to include an approved and disapproved radio button in table for each members.
How can I do that?
Please if you can help me.
This should be a POST via a FORM not a href link (GET).
$TEXT is obviously an array holding the text you want printed.
You need to replace &member_1d in the href with a real & and a real i as &member_id.
$TEXT is an array contaning all the language strings for the selected language.
You find the strings defined unter /lang/yourlanguage.php
In general this is not a very good example to start coding with IMO.
But I think your app may start working, if you make sure, the language files and other include files are available and you change this &member_1d with &member_id
An example of a list of members with delete links:
$query = mysql_query("SELECT member_id,firstname,lastname,login FROM members ORDER BY lastname");
if(mysql_num_row($query)!= 0){ //only continue if there are members in the database
while($row = mysql_fetch_assoc($query)){ //loop through each row in the database
$member_id = $row['member_id'];
$firstname = $row['firstname'];
$lastname = $row['lastname'];
echo '<p>' . $firstname . ' - ' delete '</p>';
}
}
A simple script on delete_member.php to delete the member from the database.
if(isset($_GET['id'])){
$member_id = $_GET['id'];
$query = mysql_query("DELETE FROM members WHERE member_id='$member_id'");
echo '<p>This user was deleted from database</p>';
}
This code is only basic to give an example.
I would however prefer to use a simple form and $_POST for something like this instead of using $_GET which is very vulnerable in this kind of instance.
After getting the list of members use a form with input field to type the id you want to delete.

Categories