PHP MySQL IF .. ELSE (Else Not Displaying Anything) - php

I am trying to go through all the records in a table and display something for all the records which has a match on the SQL and display something else for the record that don't have a match.
So I'm doing this:
$result = mysqli_query($con,"SELECT * FROM myTable WHERE id='$my_id' ");
while($row = mysqli_fetch_array($result)) {
if (!empty($row['id'])) {
echo 'Match Exists!';
} else {
echo 'There is NO Match';
}
}
My problem is that there is No echo for the non matches although there is for the matches.
So, I'm getting "Match Exists!" for the matches but no "There is NO Match" for the non matches.
What I'm I doing wrong here?

SELECT * FROM myTable WHERE id='$my_id
here you are checking if there exists any row where the ids matches so your code below loses his property:
if(!empty($row['id'])) {
echo 'Match Exists!';
} else {
echo 'There is NO Match';
}
You are already verifing if exists so there will not be any empty id.

Try this
<?php
$result = mysql_query($con,"SELECT * FROM myTable WHERE id='$my_id' ");
$num=mysql_num_rows($result);
if ($num!=0)
{
echo 'Match Exists!';
} else {
echo 'There is NO Match';
}
?>
OR
<?php
$result = mysql_query($con,"SELECT * FROM myTable WHERE id='$my_id' ");
while($row = mysql_fetch_array($result))
{
$id=$row['id'];
$query=$result = mysql_query($con,"SELECT * FROM myTable WHERE id='$id' ");
$num=mysql_num_rows($query);
if ($num!=0)
{
echo 'Match Exists!';
} else {
echo 'There is NO Match';
}
}
?>

If there are no matches, $row will evaluate to FALSE (because no rows are returned). If you have to do it with a while loop, try do { ... } while (...);, like below.
The difference is that the while() condition is checked after the first iteration.
$result = mysqli_query($con,"SELECT * FROM myTable WHERE id='$my_id' ");
do {
$row = mysqli_fetch_array($result);
if (!empty($row['id'])) {
echo 'Match Exists!';
} else {
echo 'There is NO Match';
}
} while(!empty($row['id']));

You have no matches because of your query.
SELECT * FROM myTable WHERE id='$my_id'
The above will fetch only matching records.
Maybe you should alter your query or the line
if (!empty($row['id']))
and check for another field that might be empty

Your query explicitely filters out "non-matching" rows:
WHERE id = '$my_id' -- neither rows having "id != $my_id"
-- nor rows with empty "id" are fetched by this query
You probably want to remove the WHERE condition from your query, and test for if($row['id'] === $my_id) in your PHP loop.

Try to remove "spaces" with trim:
if (!empty(trim($row['id']))) {
echo 'Match Exists!';
}

Related

How do I get desired value if no entry is found in the database

I have 2 columns in a table. 'phrase' and 'count'.
if($conn->connect_error){
echo 'Connection Faild: '.$conn->connect_error;
}
else{
$just_str = 'ghsfghffgh';
$sql="select * from dbtest where phrase like '%$just_str%'";
$res=$conn->query($sql);
while($row=$res->fetch_assoc()){
$jso = $row["count"];
}
}
exit(json_encode(array("name"=>$jso)));
I want it to return "Not found" as JSON response if there is no such entry in the database.
Note: $just_str variable is user input.
Since you only get one value, you don't need a loop. So just check whether any row is returned.
$row = $res->fetch_assoc();
if ($row) {
$jso = $row['count'];
} else {
$jso = 'Not found';
}

check if MySQL table is empty

I want to check if my table is empty I've tried this "which I think that is the solution"
$test_empty="SELECT *FROM objectif where 1 ";
if(empty($test_empty))
{
echo "I m here";
}
But it seems that it doesn't work.
Depending on how you are connecting to your database (for example, using mysqli):
$db = new mysqli("localhost","username","password","dbname");
$check = $db->query("SELECT COUNT(*) FROM objectif");
if ($check->num_rows == 0 || $check->fetch_field() == 0){
echo "table is empty";
}else{
echo "table is not empty";
}
Currently, your code isn't actually connecting to the database or querying the table - you are essentially just checking if the variable $query is empty (which it never will be, as it contains a string!
Running a query to fetch the number of records and checking that as per the code above is one way to do this.
Use this
$mysqli = new mysqli("localhost","root","","db");
if ($result = $mysqli->query("SELECT * FROM `table` LIMIT 1"))
{
if ($obj = $result->fetch_object())
{
echo "NOT EMPTY";
}
else
{
echo "empty";
}
$result->close();
}
$mysqli->close();
Please try below code :
$test_empty="SELECT * FROM objectif";
$query = mysql_query($test_empty);
if(mysql_affected_rows() > 0)
{
echo "It is Empty";
}

if else condition 'else' is not working

/MY CODE/
The if part is working properly but else is not working.
i even tried $variable instead of direct echo but still it is not working 'else'
Updated
<?php
$db = new mysqli('localhost', 'root' ,'', 'timeline');
if(!$db) {
echo 'Could not connect to the database.';
} else {
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
if(strlen($queryString) >0) {
$query = $db->query("SELECT collegename FROM college WHERE collegename LIKE '$queryString%' LIMIT 10");
if(isset($query)) {
echo '<ul>';
while ($result = $query ->fetch_object()) {
echo '<li onClick="fill(\''.addslashes($result->collegename).'\');">'.$result->collegename.'</li>';
}
echo '</ul>';
} else {
echo 'create some'; // this part is not working
}
} else {
// do nothing
}
} else {
echo 'There should be no direct access to this script!';
}
}
?>
help me out.....
even read lots of like problem on stackoverflow but no real return
If you are using mysqli::query then your if(isset($query)) statement will always be evaluated as true, as $query would be either FALSE or a mysqli_result object. isset returns TRUE for both these values, so your else code will never be called.
Documentation on isset:
Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
Use if($query !== false) instead.
Update
It also seems like you are checking $query to see whether or not there was a hit in the database. You need to check the number of rows in the result for that, e.g:
if ($query !== false && $query->num_rows > 0) {
// Query was ok and at least one row was returned
}
else {
// Will be reached if query was bad or there were no hits
}
Try
if($query_run = $db->query("SELECT collegename FROM college WHERE collegename LIKE '$queryString%' LIMIT 10")){
echo '<ul>';
while ($result = $query ->fetch_object()) {
echo '<li onClick="fill(\''.addslashes($result->collegename).'\');">'.$result->collegename.'</li>';
}
echo '</ul>';
} else {
echo 'create some';
}

confuse to make error message in PHP

all this code is work, what left is I try to echo a message if query not find anything..
include("config.php");
$search = $_POST['search'];
$sql = mysql_query("SELECT * FROM barangtbl WHERE nama LIKE '%$search%' ") or die(mysql_error());
while ($res=mysql_fetch_array($sql)) {
echo $res['nama'].'<br>';
}
?>
Write this:
if(mysql_num_rows($sql)) {
while ($res=mysql_fetch_array($sql)) {
echo $res['nama'].'<br>';
}
}
else
{
echo "Not found";
}
Try this:
include("config.php");
$search = $_POST['search'];
$sql = mysql_query("SELECT * FROM barangtbl WHERE nama LIKE '%$search%' ") or die(mysql_error());
if(mysql_num_rows($sql))
{
while ($res=mysql_fetch_array($sql)) {
echo $res['nama'].'<br>';
}
}
else
{
echo "The query resulted in an Empty Set";
}
Here,
mysql_num_rows($sql) will output the total no of rows in the result. If the query's output is zero rows, the value of mysql_num_rows($sql) is zero which will lead to the if condition being false and hence executing the else part.
John V is right.
But i would suggest you to use mysqli instead of the deprecated mysql function
(deprecated since version 5.5)
http://php.net/manual/en/book.mysqli.php
try this:
if($sql)
{
echo "success";
}
else
{
echo "Error";
}

Counting up array results from mysql

i've got a problem with my php script. I want to check my script if there is anything in array and if there's no to echo a message but when array is empty it just don't echo nothing.
That's my code:
include("mysql_connect.php");
$name = $_POST['playerName'];
$users = mysql_query('SELECT * FROM playerdata WHERE username LIKE "'.$name.'%"');
if($name==""){
echo 'Type in player name!';
}else{
while($usersList= mysql_fetch_assoc($users)){
if(!array_count_values($usersList)){
echo 'Player not found';
}else{
echo $usersList['username'].', ';
}
}//While end.
}//If name is empty end.
As mentioned, you have to check for rows before the loop.
$rows = mysql_num_rows($users);
if($rows==0) echo "No rows..";
else {
foreach() {
The problem seems is that, if a user enters a invalid name, the while loop does not execute, as the query simply cannot find any rows, the code should be as follows
include("mysql_connect.php");
$name = $_POST['playerName'];
if( $name === "" ){
echo 'Type in player name!';
} else {
$users = mysql_query('SELECT * FROM playerdata WHERE username LIKE "'.$name.'%"');
if ( mysql_num_rows($users) == 0) {
echo "Invalid Player name provided";
} else {
while($usersList= mysql_fetch_assoc($users)){
{
echo $usersList['username'].', ';
} //While end.
}
}//empty name
Notes:
I have re-formatted the code as it looked ugly
The query is executed only if a user provides some text for name, why execute the query when the name is empty !
instead of
if(!array_count_values($usersList)){
use
if(empty($usersList)){
Your while loop wont be executed if $users is empty, so the condition:
if(!array_count_values($usersList)){
echo 'Player not found';
}
will never be met because it is contained in a loop which will never run.

Categories