Find null values returned by SQL query - php

I am calling an SQL statement which selects everything from a view. There might be some null values returned, I would like to find them and highlight them in the HTML document. This is my code so far.
How can I find the empty columns (which can be seen in the picture) so I could highlight them with CSS?
Thanks.
<?php
require_once '../includes/header.php';
$sql = $conn->prepare("SELECT * FROM vw_allpropertiesandagents ORDER BY Price");
$sql->execute();
?>
<section class="main-sec">
<h1>All Agents and All properties</h1>
<p>The properties even the ones that have no agents assigned to them are displayed</p>
<table class ='dba-table'>
<tr>
<th>Property Id</th>
<th>Full Address</th>
<th>Price</th>
<th>Property Agent Id</th>
<th>Agent Id</th>
<th>For</th>
<th>Property Type</th>
</tr>
<?php while ($row = $sql->fetch()){ ?>
<tr>
<?php
foreach ($row as $value){ ?>
<td><?php echo $value?></td>
<?php } ?>
</tr>
<?php } ?>
</table>
</section>
<?php
require_once '../includes/footer.php';
?>
This is the HTML output]1

If I understand correctly you are looking for something like this:
<?php foreach ($row as $value): ?>
<?php if($value === null): ?>
<td style="background-color: red;">Empty</td>
<?php else: ?>
<td><?= $value ?></td>
<?php endif; ?>
<?php endforeach; ?>
Please be aware that this code is vulnerable to XSS because you are not escaping the data when echo'ing. I would recommend to only use this code locally for learning purposes.
There are some excellent articles on the internet, which you can read to learn how to prevent XSS injection.

Related

display plain text php mysql

after having found the data in a table the function displays the information without missing, with a td tag only the first word which displays the others after the space are not displayed.
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Service </th>
<th>Prix</th>
<th >Quantite</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$reqq = "SELECT * FROM service WHERE client = '$clientId' AND dossier = '$dossier' ";
$results = $connect->query($reqq);
?>
<?php if($results->num_rows > 0){ ?>
<?php
foreach($results as $data){ ?>
<?php echo $data['nom']; ?>
<tr>
<td> <?php print $data['nom']; ?>
<td><?= $data['prix']?></td>
<td><?= $data['quantite']?></td>
<td>Supprimer</td>
</tr>
</tbody>
</table>
the result is
Inside the table the last field have Franchise Procedure the table only display the first word which is Franchise
Help me find the solution please.
Try with:
<td> <?php echo htmlspecialchars($data['nom']); ?> </td>
Often, text stored in databases can contains reserved characters in HTML like "<" or "&" which should be replaced by html entities
That's what the PHP function htmlspecialchars was invented for.

Print results to a table with PDO

I'm using PDO and I'm trying to print the results on a table, but the values don't appear. I need to use the <td> tags.
Here is my complete code with a help of francisco:
<?php
require_once('config.php');
$stmt = $connect->prepare("SELECT id, username, email FROM user");
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
?>
<table id="table">
<thead>
<tr>
<th>ID</th>
<th>Username</th>
<th>email</th>
</tr>
</thead>
<tbody>
<?php
foreach ($result as $row):
?>
<tr>
<td><?= $row['id'];?></td>
<td><?= $row['username'];?></td>
<td><?= $row['email'];?></td>
</tr>
<?php
endforeach;
?>
</tbody>
</table>
You need to call fetchAll() outside of loop OR call fetch() in each iteration like this:
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
// do sth
If you want foreach, just call fetchAll() and do foreach loop over result.

display empty/blank table if query returns false

what would be the proper implementation of displaying an empty/blank table or just the table header if query result is empty?
**note/conditions
no page redirection
no creation of two tables, one for query with empty result and one for query with results
or is there a much, much better way to do this?
here is a sample code:
<?php if(isset($result)){ ?>
<table>
<tr>
<td>Name</td>
<td>Email</td>
</tr>
<?php foreach($result as $key => $data){?>
<tr>
<td><?php echo $data['name'];?></td>
<td><?php echo $data['email_add'];?></td>
</tr>
<?php }?>
</table>
<?php } ?>
the problem here is that it still throws an error on foreach loop.
When the query result returns false return an empty array instead
I hope this help , and ready for more help if needed
About the exception:
You check if $results is set, but then you try to loop over $result (without a trailing s). I believe you have a typo, which might be a part of the problem. Fixing the typo and making sure that the result is not empty (it might be set, but still empty) will probably fix the exception being thrown.
About always showing the header:
To display the header no matter what, move the if-statement to just before the the loop.
FYI - About well formatted HTML-tables:
To declare a header on a table, you usually make use of the <thead> element - to separate it from the content of the table. An example of a well-formatted HTML-table:
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td>John</td>
<td>john#email.com</td>
</tr>
</tbody>
</table>
More on formatting tables
In your case, I would put the loop around the <tr> element within the <tbody>.
<?php if(isset($result) && !empty($result)): ?>
<table>
<tr>
<td>Name</td>
<td>Email</td>
</tr>
<?php foreach($result as $data): ?>
<tr>
<td><?php echo $data['name'];?></td>
<td><?php echo $data['email_add'];?></td>
</tr>
<?php endforeach ?>
</table>
<?php else: ?>
No results found.
<?php endif ?>
Note that I prefer to use the long-form of statements for PHP templates, as it greatly improves readability.

What is the best way to display a table if an array is not null in PHP?

If the array is not null (and has values in it), then I want to display the table.
But if it is null, then I don't want to display any table code at all.
Using an MVC framework which appends a footer to the page.
What is the best way to avoid a statement like:
<?php
if ($users) {
echo '<table id="tha_table" cellpadding="0" cellspacing="0" width="100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>';
} ?>
And, don't want to do another test to add the table footer.
I think I see what you are after...
I would place all of the HTML in a separate file, and conditionally include it.
if(!empty($users)) {
include "users_table.template";
}
Note that the template file can include php if you want it to.
I always use empty() to check whether an array is empty. Empty will also check whether the variable is null. Note that empty() does not throw a warning if the array variable is not set, which may or may not be desirable.
<?php
$displayUserTable = !empty($users);
?>
<?php if($displayUserTable): ?>
<table id="tha_table" cellpadding="0" cellspacing="0" width="100%">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<?php foreach($users as $user): ?>
<tr>
<td><?php echo htmlspecialchars($user['firstName']); ?></td>
<td><?php echo htmlspecialchars($user['lastName']); ?></td>
<td><?php echo htmlspecialchars($user['emailAddress']); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
<?php if($displayUserTable): ?>
<!-- show footer here... -->
<?php endif; ?>
I recommend you use either a templating system or any other vehicle to separate your PHP code from the HTML rendering.
All template systems I know of allow for a block to be skipped depending on a boolean, so you would just include the (template for the) table in your page template and surround it with whatever your chosen framework uses as an if or repeat n times construct.

Using PHP as a template engine

I am not going to argue about the choice of a template engine against only PHP. I choose not to use a template engine, like Smarty, because I would like to learn how to properly design a template using PHP and HTML. Could someone provide links or examples on how to design a template page?
Just use alternative PHP syntax for if/for/foreach control language constructs which are designed specifically for this purpose:
<h1>Users</h1>
<?php if(count($users) > 0): ?>
<table>
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<?php foreach($users as $user): ?>
<tr>
<td><?php echo htmlentities($user->Id); ?></td>
<td><?php echo htmlentities($user->FirstName); ?></td>
<td><?php echo htmlentities($user->LastName); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else: ?>
<p>No users in the database.</p>
<?php endif; ?>
I also suggest creating view helpers for HTML outputs that are very similar and use them instead of having repeated HTML code.
It's really not all that difficult.
Non-PHP goes out here
<?php # PHP goes in here ?>
More non-PHP goes out here
<?php # More PHP goes in here ?>
function returnView($filename,$variables){
ob_start();
$htmlfile = file_get_contents($filename);
foreach($variables as $key=>$value){
$htmlfile = str_replace("#".$key."#", $value, $htmlfile);
}
echo $htmlfile;
return ob_get_clean();
}
//htmlfile
<html>
<title>#title#</title>
</html>
//usage
echo returnView('file.html',array('title'=>'hello world!');
im my framework i have function that loads view, and then outs it in layout:
public function returnView(){
ob_start();
$this->loader();
$this->template->show($this->controller,$this->action);
return ob_get_clean();
}
Layout looks like this:
<html>
<head>
<title><?php echo $this->layout('title'); ?></title>
</head>
<body>
<?php echo $this->layout('content'); ?>
</body>
</html>
What you might want to consider, if you should opt for a MVC-style approach, if you include your templates inside an object (one of its class methods) then $this inside the template file will point to the object you called it from.
This can be very useful if you want to ensure some kind of encapsulation for your templates, i.e. if you do not want to rely on global variables to pass around dynamic data (e.g. from a database).
I've used various template engines, and designed my own as well, getting more elaborate over time. I think its best to keep it as simple as possible by using native php stuff, instead of creating elaborate functions. (this article has some good points: Boring Architecture is Good). What I found was much better readability and maintenance when coming back to a project after months or years.
For example:
<?
$name="john";
$email="john#xyz.com";
require "templates/unsubscribe.php";
-- templates/unsubscribe.php --
<?
$o=<<<EOHTML
Hi $name, sorry to see you go.<BR>
<input type=input name=email value=$email>
<input type=submit value='Unsubscribe'>
EOHTML;
echo $o;
Using Richard's example, but more simple:
<h1>Users</h1>
<? if(count($users) > 0): ?>
<table>
<thead>
<tr>
<th>Id</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<? foreach($users as $user): ?>
<tr>
<td><?= htmlentities($user->Id) ?></td>
<td><?= htmlentities($user->FirstName) ?></td>
<td><?= htmlentities($user->LastName) ?></td>
</tr>
<? endforeach ?>
</tbody>
</table>
<? else: ?>
<p>No users in the database.</p>
<? endif ?>

Categories