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.
Related
<tr>
<td id="idtypesectype2">Skype</td>
<td id="doubledotsec">:</td>
<td>
<?php
$search = $_GET['search'];
$sql ="SELECT * FROM contact_info WHERE CU_id='$search' AND contact_information_type='social_media_skype' AND visibility='1'";
$result = $db -> query($sql);
WHILE ($row=$result->fetch_assoc()) {
if(mysqli_num_rows($result) < 0) {
echo "-";
} else {
echo $row['contact_information'];
}
?><br>
<?php
}
?>
</td>
</tr>
I don't get - when the row is empty, instead it is a blank. Can you help me with this isuue? I want that it will show - when the row doesn't exist.
You're checking how many rows your query returns in your while loop, where you fetch the single rows. Yet, if there are none, you never get in the while loop.
So, what you need to do, is put your if condition before the while, and the while loop inside the else statement.
First, you have to remember that a while loop with nothing to process just terminates and continues with the code after it. So if you want to test the number of rows in the resultset, you need to do it before running the while loop
You also need to use prepared queries to protect yourself from SQL Injection Attack
<tr>
<td id="idtypesectype2">Skype</td>
<td id="doubledotsec">:</td>
<td>
<?php
$sql ="SELECT *
FROM contact_info
WHERE CU_id=?
AND contact_information_type='social_media_skype'
AND visibility='1'";
# prepare and bind parameter to the query to protect against SQL Injection
$stmt = $db->prepare($sql);
$stmt->bind_param('i', $_GET['search']);
$stmt->execute();
$results = $stmt->get_result();
if($result->num_rows == 0) {
echo "-";
}
while ($row=$result->fetch_assoc()) {
echo $row['contact_information'];
}
?>
<br>
</td>
</tr>
I think you must change your code to this to get the disired result:
<tr>
<td id="idtypesectype2">Skype</td>
<td id="doubledotsec">:</td>
<td>
<?php
$search = $_GET['search'];
$sql ="SELECT * FROM contact_info WHERE CU_id='$search' AND contact_information_type='social_media_skype' AND visibility='1'";
$result = $db -> query($sql);
if($result->num_rows < 0) {
echo "-";
} else {
WHILE ($row=$result->fetch_assoc()) {
echo $row['contact_information'];
}
?><br>
<?php
}
?>
</td>
</tr>
I really can't figure out what I'm doing wrong here. I'm doing a query to check whether there are records in a DB table called 'newCards'.
With $count I check how many results it's returning: it shows me '1'. But the while loop isn't returning ANY thing. The only things I'm seeing are the <th>'s at the top of the table, but no table records are present, while $count is giving '1' as a result. Which is true, cause there is actually 1 record present in DB.
How can I fix this?
<?php
$query = $db->prepare("SELECT * FROM `newCards` WHERE `company` = :companyID");
$query->bindParam(":companyID", $enterprise['id'], PDO::PARAM_INT);
$query->execute();
$count = $query->rowCount();
echo $count;
if(empty($query->fetch())){
echo "Geen gevonden";
} else {
?>
<table>
<tr>
<th>Ontvanger</th>
<th>Saldo</th>
<th></th>
</tr>
<?php
while($result = $query->fetch()){
?>
<tr>
<td><?php echo $result['id']; ?></td>
<td>2</td>
<td>3</td>
</tr>
<?php
}
?>
</table>
<?php
}
?>
$query->fetch() already fetches a record. So next call to fetch() fetches next record or nothing if there're no records. In your case with one record second fetch() fetches nothing, so while never starts.
You can change your code to:
if($count){?>
<table>
<tr>
<th>Ontvanger</th>
<th>Saldo</th>
<th></th>
</tr>
<?php
while($result = $query->fetch()){
// show row
}?>
</table>
} else {
// echo that no rows found
}
I think fetch in first if is executed so that is why second returns empty,
try to assign it to var before conditions or check wit $cont var
I believe you want to return an array indexed by column names with
->fetch(PDO::FETCH_ASSOC)
More information can be found here http://php.net/manual/en/pdostatement.fetch.php
Because fetch() fetches the first row, even when checking in empty(), it will try to fetch the next row when you use while($result = $query->fetch()){. You can either check the value from $count (like shown by u_mulder), but you should beware of the note in the manual for rowCount() (emphasis mine)
If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behavior is not guaranteed for all databases and should not be relied on for portable applications.
You can use a do..while structure and check if the fetch was successful or not instead. If you change out if(empty($query->fetch())){ with if (!$row = $query->fetch()) {, you check if there was a row fetched or not (as fetch() returns null on an empty result). Then $row is ready to use, and you can use it before the first loop takes place.
<?php
$query = $db->prepare("SELECT * FROM `newCards` WHERE `company` = :companyID");
$query->bindParam(":companyID", $enterprise['id'], PDO::PARAM_INT);
$query->execute();
$count = $query->rowCount();
echo $count;
if (!$row = $query->fetch()) {
echo "Geen gevonden";
} else {
?>
<table>
<tr>
<th>Ontvanger</th>
<th>Saldo</th>
<th></th>
</tr>
<?php
do {
?>
<tr>
<td><?php echo $result['id']; ?></td>
<td>2</td>
<td>3</td>
</tr>
<?php
} while ($result = $query->fetch());
?>
</table>
<?php
}
PHP.net on PDOStatement::rowCount()
PHP.net on do..while
I know how to produce results one after another but how do you separate them? So in my sql I'm selecting * from table and limiting it to 4
$sql = "SELECT * FROM table limit 4";
$result = $conn->query($sql);
while($row = $result->fetch_assoc())
{$rows['id']=$row;};
$price = $row['price'];
I dont seem to get any result, any suggestions, sorry guys beginner
...<?php echo $id ?></font></span>
<h4><?php echo $price ?></h4></div>
<div class="planFeatures"><ul>
<li><h1><?php echo $id=2 ?></h1></li>//how do I echo the next id?
<li><?php echo $price2 ?></li> //also the next price which id now is also 2
//and so on......
How do I display the next increments results in a different area of the same page, within another div?
I do get results if I sql and re-select all over again (and say id=2) but I'm sure there is a better way of doing it because I've already got my 4 results with my limit.
It seems you are not saving the results from the query result properly. Each iteration of the loop overwrites the same bucket in the $rows array. Instead, you need to add elements to the $rows array; this will produce an indexed array. Then you can iterate over it and generate the HTML content.
<?php
// Perform query.
$sql = "SELECT * FROM table limit 4";
$result = $conn->query($sql);
// Fetch results
while (true) {
$row = $result->fetch_assoc();
if (!$row) {
break;
}
$rows[] = $row;
}
// Generate HTML content using $rows array.
?>
<table>
<thead>
<tr>
<th>ID</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php foreach ($rows as $row):?>
<tr>
<td>ID: <?php print $row['id'];?></td>
<td>Price: <?php print $row['price'];?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
I took some liberty in the above example and generated a simple HTML table. Of course you can modify this to generate whatever you want.
I hope I've interpreted your question accurately, apologies if not!
I executed this code in localhost but it kept looping the table infinitely. How do I fix this? Is there something I should add? The looping never stops until I click the x button to stop loading the page.
//fetching data in descending order (lastest entry first)
//$result = mysql_query("SELECT * FROM users ORDER BY id DESC"); // mysql_query is deprecated
$query=("SELECT * FROM songs ORDER BY songid DESC");
$result = mysql_query($query) or die(mysql_error());
?>
<html>
<head>
<title>View</title>
</head>
<body>
Add New Data<br/><br/>
<table width='80%' border=0>
<tr bgcolor='#CCCCCC'>
<td>Song ID</td>
<td>Title</td>
<td>Artist</td>
<td>Genre</td>
<td>Language</td>
<td>Lyrics</td>
<td>Updated by</td>
</tr>
<?php
$counter == 1;
$res = mysql_fetch_array($result);
//while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
do {
echo "<tr>";
echo "<td>".$res['songid']."</td>";
echo "<td>".$res['title']."</td>";
echo "<td>".$res['artist']."</td>";
echo "<td>".$res['genre']."</td>";
echo "<td>".$res['language']."</td>";
echo "<td>".$res['lyrics']."</td>";
echo "<td>".$res['update']."</td>";
echo "<td>Edit | Delete</td>";
} while($res)
?>
</table>
You are missing $res = mysql_fetch_array($result); at the end of the loop. Currently, the while statements checks if $res is (still) truthy, but it never changes, so it will always evaluate to TRUE (and so, the loop will always continue to run).
I was just about to write the same thing as Daan Meijer. res never changes and so its always true for the while-statement. I just want to add that mysql_fetch_assoc($result) works a littlebit faster than mysql_fetch_array($result). So if you have a big database, mysql_fetch_assoc($result) is the better choice.
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';
}