PHP PDO Display message if no results are found in search - php

I am trying to set an 'No Results Found' message when no search results are found after executing a MySQL 'LIKE' Query
I have the following code below:
I have an if statement just to test to see if an error message will work but I seem to get the output of the else statement 'found'
<table class="center"> <!-- Creating a table with the class of 'center' -->
<!-- SEARCH FORM -->
<?php
$KEYWORD = $_POST['keyword'];
$stmt = $conn->prepare("SELECT DISTINCT dog_park_name FROM dog_park.items WHERE dog_park_name LIKE '%{$KEYWORD}%'");
$stmt->execute();
for($i=0; $row = $stmt->fetch(); ){
$_SESSION["KEYWORD".$i] = $row[0];
if(empty($stmt))
{
echo 'Nothing found';
}
else
{
echo 'found';
}
?>
<!-- DISPLAY RESULTS -->
<tr> <!-- Adding the first table row -->
<th>Dog Park</th> <!-- Adding the second table header -->
</tr>
<tr> <!-- Adding the second table row -->
<td><a href="individual_item_page.php?keyword='<?php echo $row[$i] ?>' " ><?php echo $row[$i] ?></a></td> <!-- Add the second cell on the second row -->
</tr>
<?php } ?>
</table>
Example:
If a user searches a keyword, and no results are found from that keyword, I am trying to get a message saying 'No Results found'

To make a Mike Brant's answer a proper one:
$stmt = $conn->prepare("SELECT DISTINCT dog_park_name FROM items WHERE dog_park_name LIKE ?");
$stmt->execute(array("%".$_POST['keyword']."%"));
$_SESSION['KEYWORD'] = $stmt->fetchAll(PDO::FETCH_COLUMN);
if($_SESSION['KEYWORD']) {
?>
<table>
<tr><th>Dog Park</th></tr>
<?php foreach($_SESSION['KEYWORD'] as $word):?>
<tr><td><?php echo $word?></td></tr>
<?php endforeach?>
</table><?php
} else {
echo 'Nothing found';
}
So in other words, you always have the query results to tell whether you have any results.

Your if structure should show 'found' because your query executed successfully, in this cases you can count rows for decide about this issue:
if($stmt->rowCount() == 0)
{
echo 'Nothing found';
}
else
{
echo 'found';
}

I am not going to get into the SQL injection problem you have with your current code. You need to fix it, likely using parameters with your prepared statement, but that is another topic.
I would also say your KEYWORD.$i approach is an antipattern. Why not just have numerically-indexed array under $_SESSION['KEYWORD']?
$_SESSION['KEYWORD'] = array();
$stmt = $conn->prepare("SELECT DISTINCT dog_park_name FROM dog_park.items WHERE dog_park_name LIKE '%{$KEYWORD}%'");
if($stmt) {
$result = $stmt->execute();
if($result) {
while($row= $stmy->fetch() {
$_SESSION['KEYWORD'][] = $row[0];
}
}
}
if(count($_SESSION['KEYWORD']) === 0) {
echo 'Nothing found';
} else {
echo 'found';
}

Related

How can I add prepare statement in my comment printing system

I'm currently building a system where users can write and read comments. So the comments will be inserted into database (the inserting part is already protected with the prepared statement), so now I want to add the prepared statement at the comment printing part too.
This is the comment inserting part
<?php
if (isset($_POST['submit'])) {
$nickname=$_POST['user_nickname'];
$email=$_POST['user_email'];
$comment=$_POST['cmt_text'];
$course=$_POST['user_course'];
$rating=$_POST['user_rating'];
$classof=$_POST['user_classof'];
$school_id=$_POST['id'];
$db="INSERT INTO comments(user_nickname,user_email,cmt_text,user_course,user_rating,school_id,user_classof) VALUES(?,?,?,?,?,?,?)";
$stmt=mysqli_stmt_init($con);
if(!mysqli_stmt_prepare($stmt,$db)){
echo "Data Error";
}else{
mysqli_stmt_bind_param($stmt,"ssssiii", $nickname,$email,$comment,$course,$rating,$school_id,$classof);
mysqli_stmt_execute($stmt);
}
header("location:Done.php");
exit;
}?>
And this is where I want to add prepared statements
<?php
$sql = "SELECT * FROM comments WHERE school_id=$sid ORDER BY Datetime DESC ";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<div class="single-item">
<h4><?php echo $row['user_nickname']; ?></h4>
<p><?php echo $row['Datetime'];
?></p>
<p><b>Course</b> : <?php echo $row['user_course'];
?></p>
<p><b>Class of</b> <?php echo $row['user_classof'];
?></b></p>
<p><b>Rating : </b><?php echo $row['user_rating'];
?>/5</p>
<p><b>Comment : </b><?php echo $row['cmt_text'];
?></p>
</div>
<?php
}
}
?>
I have tried adding, but I got stuck when it comes to the part where I need to put the parameter, since I am printing out all the comments, how can I add the ? parameter?
By the way, $sid is a specific id for one school. There's more than a hundred schools in thecomments table. I put all the comments from every schools in one table.
Just create a function in which you will prepare the data.
function selectComments(mysqli $mysqli, ?int $schoolId = null): array
{
if ($schoolId) {
$stmt = $mysqli->prepare('SELECT * FROM comments WHERE school_id=? ORDER BY Datetime DESC');
$stmt->bind_param('s', $schoolId);
$stmt->execute();
$result = $stmt->get_result();
} else {
$result = $mysqli->query('SELECT * FROM comments ORDER BY Datetime DESC');
}
return $result->fetch_all(MYSQLI_ASSOC);
}
Then you can call it like this:
foreach(selectComments($con, $sid) as $row) {
// your HTML table
}

I am having search error in following php code

I am having an error in php search. If the record is not found it echo "Record Not Found". But if the record is found it is still giving same message "Record Not Found"
<?php
if(isset($_GET['submit']))
{
$search = $_GET["search"];
$result = mysqli_query($conn, "select * from login where password like
'".$_GET['search']."%' or email like '".$search."%' ");
$rows = 0;
while($rows = mysqli_fetch_array($result))
{
?>
<tr>
<td>
<?php echo $rows['email']; ?>
</td>
<td>
<?php echo $rows['password']; ?>
</td>
<td>
Edit ,Del
</td>
</tr>
<?php
$rows++;
}
if($rows == 0)
{
echo "No Record Found";
}
}
?>
The problem here is that you seem to be using your $rows variable for 2 things: counting the rows and fetching the rows.
Rename it to let's say $count for counting and it will solve your problem.
The thing is, your while loop is assigning the result from mysqli_fetch_array to your $rows variable and then evaluating it to see if it continues looping.
If the while loop stopped looping, it means that the last call to mysqli_fetch_array returned a result that is equivalent to false. Therefore, it will always be equivalent to 0 (because false == 0 will return true) in the if right below otherwise it would not have exited the while loop.

Display all rows of data from the database

I am developing a document management system, so far I'm able to log in and upload documents based on the user that's logged in. I've also managed to construct the code so it captures the records assigned to that user and display them in a table. So I am able to log in as different users and see what I've uploaded as them users individually. However, the only problem is that the script is only pulling out one row of data for each users, when there are multiple instances in the database. See the code below:
<!-- start of php code to query and display documents -->
<?php
$sql = mysqli_query($conn, "SELECT upload.personalid, upload.file, upload.type, upload.size, person.personalid FROM upload inner join person on upload.personalid=person.personalid where person.username='$uname '") or die (mysqli_error($conn));
$filedata= ($sql) ? mysqli_fetch_array($sql) : false;
{
if($filedata){
?>
<tr>
<td><?php echo $filedata['file'] ?></td>
<td><?php echo $filedata['type'] ?></td>
<td><?php echo $filedata['size'] ?> Bytes</td>
</tr>
<?php
}
else {
echo 'No files found';
}
}
?>
<!-- end of php code to query and display documents -->
This all works fine, I just want it to display all the rows of data assigned to the logged in user, instead of one. How do I do this?
Thanks,
Sohail.
You're close. You need a while loop. Replace
$filedata= ($sql) ? mysqli_fetch_array($sql) : false;
if($filedata){
With
while($filedata = mysqli_fetch_array($sql)) {
You can change it so that you loop through each returned record like this:
<?php
$sql = mysqli_query($conn, "SELECT upload.personalid, upload.file, upload.type, upload.size, person.personalid FROM upload inner join person on upload.personalid=person.personalid where person.username='$uname '") or die (mysqli_error($conn));
if (mysqli_num_rows($sql) > 0) {
while ($filedata = mysqli_fetch_array($sql)) {
?>
<tr>
<td><?php echo $filedata['file']; ?></td>
<td><?php echo $filedata['type']; ?></td>
<td><?php echo $filedata['size']; ?> Bytes</td>
</tr>
<?php
}
} else {
echo 'No files found';
}
?>

How add a value from select/dropdown list to my Prepare Statement?

First question here but I have been teaching myself PDO over the past few days to integrate into a site I'm developing and I'm not quite sure what I'm doing wrong. I have been trying to use GET to retrieve the selection from a dropdown menu in order to limit the results displayed from a query.
Here is my code so far
HTML:
<form action="searchfx.php" method="get">
<p>Provider Name: <input type="text" name="name" /></p>
<p>Provider Number: <input type="text" name="prvdrnum" /></p>
<p>Number of results to display:</p> <select name="disp" size="1">
<option name="10" value="10">10</option>
<option name="25"value="25">25</option>
<option name="50" value="50">50</option>
</select>
<p><input type="submit" /></p>
</form>
PHP:
<?php
include("link.php");
$name=$_GET['name'];
$num=$_GET['prvdrnum'];
if(isset($_GET['disp']){
$disp=$_GET['disp'];
}
$query = $link->prepare("SELECT *
FROM hcisip
WHERE providerName LIKE '%$name%'
AND providerNum LIKE '%$num%'
LIMIT 0, $disp");
//<------The 50 is what I am trying to change to have the $disp selection
$query -> bindValue(':name', $name, PDO::PARAM_STR);
$query -> bindValue(':num', $num, PDO::PARAM_STR);
$query -> bindValue(':disp', $disp, PDO::PARAM_INT);
$query->execute();
// Display search result
if (!$query->rowCount() == 0) {
echo "Search found :<br/>";
echo "<table>";
echo "<tr><td>Provider Name</td><td>Provider Number</td></tr>";
while ($results = $query->fetch()) {
echo "<tr><td>";
echo $results['providerName'];
echo "</td><td>";
echo $results['providerNum'];
echo "</td></tr>";
echo "</table>";
}
} else {
echo 'Nothing found';
}
?>
Basically what I am trying to do here is take the value from the selection box (named "disp" in the html) and add it to the second parameter of the prepared statement (which to my understanding is the upper limit to how many results are displayed.
So far I have tried adding $disp=$_GET['disp']; to the top and then changing the prepared statement to:
$query = $link->prepare("SELECT * FROM hcisip WHERE providerName LIKE '%$name%'
AND providerNum LIKE '%$num%' LIMIT 0, '%$disp%'");
but upon doing this my search returns no results ("Nothing Found").
How can I allow the user to select the number of results returned by the query?
I apologize if this is a common question and can assure you I scoured google as I'm sure this is an easy fix/syntax error but I had no success finding a relative topic.
Thanks in advance.
EDIT: I have modified the code above to reflect the changes but am still recieving "Nothing found" which means :disp is not doing its job.
I am also receiving this error: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens
EDIT: It's working now, I have edited the code above to reflect my changes. I chose not to enclose the entire block in the if(isset()) statement as I wanted the user to be able to search by any of the fields as opposed to filling in them all.
First you must check that the values in $_GET exists:
EDIT:
<?
include("link.php");
if(isset($_GET['disp']) && isset($_GET['name']) && isset($_GET['prvdrnum'])) {
$disp=$_GET['disp'];
$name=$_GET['name'];
$num=$_GET['prvdrnum'];
$query = $link->prepare("SELECT * FROM hcisip WHERE providerName LIKE '%$name%' AND providerNum LIKE '%$num%' LIMIT 0, $disp");
$query->execute();
// Display search result
if ($query->rowCount() > 0) {
echo "Search found :<br/>";
echo "<table>";
echo "<tr><td>Provider Name</td><td>Provider Number</td></tr>";
while ($results = $query->fetch()) {
echo "<tr><td>";
echo $results['providerName'];
echo "</td><td>";
echo $results['providerNum'];
echo "</td></tr>";
echo "</table>";
}
} else {
echo 'Nothing found';
}
}
?>

detect if array value contains specific text PHP

I have a SQLite- database containing articles. All articles contains HTML, but one of those articles contain an <aside>. So I'd like to present this article in another way than the others.
This is my code now:
$db = new PDO("sqlite:$dbPath");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); // Display errors, but continue script
$stmt = $db->prepare('SELECT * FROM Article WHERE category = "article" ORDER BY pubdate DESC;');
$stmt->execute();
$res = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<table id="artikelLista">
<caption><em>Visar alla artiklar</em></caption>
<?php foreach($res as $article): ?>
<tr class="artikelContent">
<td><h4><?php echo $article['title']; ?></h4>
<?php echo $article['content']; ?>
<span class="floatRight"><?php echo "Artikel skriven " . $article['author'] . " " . $article['pubdate']; ?></span></td>
</tr>
<?php endforeach; ?>
</table>
Is there a way to check if the $article['content] array value contains "<aside>" and set a different style for that tr? (Or div if this is not possible inside tr)
All you need to do is:
if(strpos($article['content'],"<aside>") == false) {
//is <aside> is not present
} else {
//if word detected
}

Categories