I have a statement, quite basic that pulls in from a database and displays the information. It works. However if I delete the entry in the database, the else statement should kick in a say that there are no results. However it does not. Can anyone see the problem?
This is the code, the bit I'm taking about is the if($result) {
$con=mysqli_connect("localhost","user","pass","db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else {
$result = mysqli_query($con,"SELECT * FROM vacancies WHERE status ='0'");
if($result) {
while($row = mysqli_fetch_array($result)) {
echo "<li>". $row['title'] ." <img src=\"rightarrow.png\" alt=\"next\"></li>";
}
} else {
// execute for 0 rows returned.
echo "There are currently no vacancies available";
}
}
If the SELECT operation was successful then mysqli_query() will always return an object. Whether this object holds 0 or more records it will always be true. What you should rather have done instead is fetch all the records from the result.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli("localhost", "user", "pass", "db");
$con->set_charset('utf8mb4'); // always set the charset
$result = $con->query("SELECT * FROM vacancies WHERE status ='0'");
$data = $result->fetch_all(MYSQLI_BOTH);
if ($data) {
foreach ($data as $row) {
echo "<li>". $row['title'] ." <img src=\"rightarrow.png\" alt=\"next\"></li>";
}
} else {
// execute for 0 rows returned.
echo "There are currently no vacancies available";
}
To implementing no result, you need to check number of rows you fetch by query with mysqli_num_rows().
In your case you checked for the $result variable this will store the status of the query execution, therefore it will always be true, since query will always execute even if it returns no rows.
To make it more natural way
$data = [];
$result = $con->query("SELECT * FROM vacancies WHERE status ='0'");
while($row = mysqli_fetch_array($result)) {
$data[] = $row;
}
?>
and now you may use $data the way you tried to use $result:
<?php foreach ($data as $row): ?>
<li>
<a href="current_vacancy?id=<?=$row['id']?>">
<?=$row['title']?>
</a>
<img src="/images/rightarrow.png" alt="next">
</li>
<?php endforeach ?>
<?php if(!$data): ?>
There are currently no vacancies available
<? endif ?>
The result returned from mysqli_query is an object, not a row count. Use mysqli_num_rows($result) to get the row count.
By the way, be sure to call mysqli_free_result($result) at the end. Suggested outline:
$result = mysqli_query(…);
if (!$result) {
# Handle failure
} else {
if (mysqli_num_rows($result) == 0) {
# Handle no vacancies
} else {
# Normal case
}
mysqli_free_result($result);
}
Related
<?php
$successreturn[]=array(
"id"=>"any",
"firstname"=>"any",
"lastname"=>"any",
"dateofbirth"=>"any",
"city"=>"any",
"gender"=>"any"
);
header("Access-Control-Allow-Origin: *");
$servername="localhost";
$username="root";
$password="sandeepchetikam";
$dbase="mydb";
$conn=mysqli_connect($servername,$username,$password,$dbase);
if (!$conn) {
echo "Connection Problem".mysqli_connect_error($conn);
}
$sql= "SELECT * FROM Employees";
$result = mysqli_query($conn,$sql);
$count = mysqli_num_rows($result);
$value=0;
if(!$result){
echo "Connection Failed " .mysqli_connect_error($result);
}
while($row = mysqli_fetch_assoc($result)){
$successreturn[$value]['id'] =$row['id'];
$successreturn[$value]['firstname'] =$row['firstname'];
$successreturn[$value]['lastname'] =$row['lastname'];
$successreturn[$value]['dateofbirth'] =$row['dateofbirth'];
$successreturn[$value]['city'] =$row['city'];
$successreturn[$value]['gender'] =$row['gender'];
$value++;
};
echo json_encode($successreturn);
?>
output :
[{"id":"any","firstname":"any","lastname":"any","dateofbirth":"any","city":"any","gender":"any"}]
I am trying to return a JSON value into my angular service. But when there are no more rows in the table. Its returning the Colomn value as "any".
Why is it like that ?? How do i return a empty row with no value?
You need to control the program flow a little differently
<?php
header("Access-Control-Allow-Origin: *");
$servername="localhost";
$username="root";
$password="sandeepchetikam";
$dbase="mydb";
$conn=mysqli_connect($servername,$username,$password,$dbase);
if (!$conn) {
echo "Connection Problem".mysqli_connect_error($conn);
}
// first only select what you want to use from the row
$sql= "SELECT `id`,`firstname`,`lastname`,
`dateofbirth`,`city`,`gender`
FROM Employees";
$result = mysqli_query($conn,$sql);
if(!$result){
// you only use `mysqli_connect_error` to get connection errors
// use mysqli_error($result) for normal query errors
echo "Query failed " . mysqli_error($result);
echo json_encode(array('error'=>'Query failed'));
exit;
}
if ( mysqli_num_rows($result) > 0 ) {
while($row = mysqli_fetch_assoc($result)){
// now as you only have what you want in your assoc array
$rows[] = $row;
}
echo json_encode($rows);
} else {
// no data returned from query
// return something so the calling code knows what to do
echo json_encode(array('error'=>'No data in table'));
}
?>
When no row selected then the while loop is not executting and the initial $successreturn array is return with value 'any' to return no value if no row selected then
Just change this
$successreturn[]=array(
"id"=>"any",
"firstname"=>"any",
"lastname"=>"any",
"dateofbirth"=>"any",
"city"=>"any",
"gender"=>"any");
To
$successreturn[]=array(
"id"=>"",
"firstname"=>"",
"lastname"=>"",
"dateofbirth"=>"",
"city"=>"",
"gender"=>"");
Edit:-
$successreturn=[];
And check the value is empty or not in view and then display the data if it have otherwise don't display it.
I thing it will help you.
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";
}
I've tried like twenty times and the closest I got was when I put in a variable stored in row 1 of the db and it returned the content the last row in the db. Any clarity would be extremely helpful. Thanks.
// Create connection
$coco = mysqli_connect($server, $user, $pass, $db);
// Check connection
if (!$coco) { die("Connection failed: " . mysqli_connect_error()); }
// Start SQL Query
$grabit = "SELECT title, number FROM the_one WHERE title = 'on' AND (number = 'two' OR number='0')";
$result = mysqli_query($coco, $grabit);
// What I need it to do
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$titleit = $row["title"];
$placeit = $row["number"];
$incoming = 'Help';
if ($titleit[$_REQUEST[$incoming]]){
$message = strip_tags(substr($placeit,0,140));
}
echo $message;
}
} else {
echo "not found";
}
mysqli_close($coco);
Put the input that you want to match into the WHERE clause of the query, rather than selecting everything and then testing it in PHP.
$incoming = mysqli_real_escape_string($coco, $_POST['Help']));
$grabit = "SELECT number FROM the_one WHERE title = '$incoming' AND number IN ('two', '0')";
$result = mysqli_query($coco, $grabit);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['number'];
}
} else {
echo "not found";
}
I think you need to add a break; in that if or I would assume it would go through each row in the database and set message if it matches the conditional. Unless you want the last entry that matches...if not you should debug:
if ($titleit[$_REQUEST[$incoming]]){
// set message
}
and see when it's getting set. That may not be the issue, but it's at least a performance thing and could explain getting the last entry
Have you tried print_r($row) to see the row or adding echos to the if/else to see what path it's taking?
i wrote a PHP Function but it does nothing at a specific point.. im new to php and my english is bad, sorry for that.
<?php
function SQLwriteRecent($id, $title, $link) {
$con=mysqli_connect("localhost","","","");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$count = mysqli_query($con,"SELECT count FROM recent WHERE sc_stream='$id'");
if(!isset($count)) {
try {
mysqli_query($con,"INSERT INTO recent (title, link, sc_stream, count) VALUES ('$title', '$link', '$id',$count)");
mysqli_close($con);
return 1;
} catch(Exception $e) {
return 0;
}
} else {
try {
// ------ SHOW HERE!!!! ------------ //
mysqli_query($con,"UPDATE recent SET count=$count WHERE sc_stream='$id'");
mysqli_close($con);
return 2;
} catch(Exception $e) {
return 0;
}
}
}
?>
the code runs every time until a specific point (i marked it in the code with // ------ SHOW HERE!!!! ------------ //)
in the sql table, currently there is no entry. so i should create a new row
whats wrong with that code?! :(
Your script wont insert a new row, because you have defined $count, it is a mysqli_result object. You have to check if there is a row, something you could do like this;
Instead of
if(!isset($count))
use
if(mysqli_num_rows($count) == 0)
Some explanation:
You have this in your code:
if(!isset($count)) {
This checks that your variable has been set, nor is empty, false, or 0. This condition ALWAYS return true because the variable is setted in line before, use mysqli_nuw_rows instead
Combining what other people have said, and looking at the logic of what you're doing, it looks like you have a few fundamental issues:
I've tweaked some variable names to make it clearer what you're getting an peppered the code with comments that describe the issues.
I've ignored the SQL injection issues.
<?php
function SQLwriteRecent($id, $title, $link) {
$con=mysqli_connect("localhost","","","");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$countQuery = mysqli_query($con,"SELECT count FROM recent WHERE sc_stream='$id'");
$numberOfRowsReturnedByQuery = mysqli_num_rows($count);
if ( $numberOfRowsReturnedByQuery > 0 ) {
$valueOfCountInQuery = $countQuery [0]['count'];
}
if( $numberOfRowsReturnedByQuery == 0) {
try {
// In this situation it looks like you want to set up a value in "recent" - I.E. you didn't have a record.
// But think about it for a second - if you had no record in "recent" then how could "$valueOfCountInQuery" possibly be set?
mysqli_query($con,"INSERT INTO recent (title, link, sc_stream, count) VALUES ('$title', '$link', '$id',$valueOfCountInQuery )"); // makes no sense to use "$valueOfCountInQuery" - maybe you mean "0" (zero)
mysqli_close($con);
return 1;
} catch(Exception $e) {
return 0;
}
} else {
try {
// In this situation it looks like you want to update the value in "recent" - I.E. you DID have a record and you want to change it.
// But think about it for a second - the value of "$valueOfCountInQuery" is the value that you got from "count" on "recent". You are setting it to the same value that's already in there!
// ------ SHOW HERE!!!! ------------ //
mysqli_query($con,"UPDATE recent SET count=$valueOfCountInQuery WHERE sc_stream='$id'"); // redundant
mysqli_close($con);
return 2;
} catch(Exception $e) {
return 0;
}
}
}
?>
You did a mistake here, query returns array
try this
mysqli_query($con,"UPDATE recent SET count=$count[0]['count'] WHERE sc_stream='$id'");
You have set:
count=$count
but
$count = mysqli_query($con,"SELECT count FROM recent WHERE sc_stream='$id'");
Specify a proper value for count not a resource
to retrieve the actual result of the query you have to do something like
if ( $result = $con->query($sql)){ //perform the query
if ($result->num_rows == 1){
if ($row = $result->fetch_assoc()){
$count = $row['count'];
}
else{
echo "couldn't fetch result row";
}
else {
echo "expected one result row, got ".$result->num_rows;
}
}
else {
echo "query failed:".$sql;
echo $con->errno.' '.$con->error;
}
// if you have more than one result row
if ( $result = $con->query($sql))
while ($row = $result->fetch_assoc()){ //loop through the result(s)
$count = $row['count']
}
// procedural style
if ( $result = mysqli_query($con,$sql))
while($row = mysqli_fetch_assoc($result)){
This should be simple.... but it's taking a while... Here's the code that's not working (it either shows nothing or the blank state message each time). $show image is the query and I know it's running fine.
// BLANK STATE TOGGLE
$result = mysqli_fetch_array($showimage, MYSQLI_ASSOC);
if($result == ''){
echo '<p>Sorry- no image.</p>';
}
else {
echo '<p>There is an image!</p>';
}
}
If you only want to check for the existence of rows in the result from your query, why don't you simplify it like this
// $db is your MySQLi connection object
$query = 'SELECT COUNT(1) FROM `table` WHERE `something` = ?';
$stmt = $db->prepare($query);
$stmt->bind_param('s', $something);
$stmt->execute();
$stmt->bind_result($rowCount);
$stmt->fetch();
$stmt->close();
if ($rowCount > 0) : ?>
<p>There is an image!</p>
<?php else : ?>
<p>Sorry- no image.</p>
<?php endif ?>
mysqli_fetch_array returns null if there is no match in the database. So you need to check for null.
You may need to try this:
if $showimage is your query ..
//This should run fine
//$link is ur connection
$new_result = mysqli_query($link,$showimage);
$result = mysqli_fetch_array($new_result, MYSQLI_ASSOC);
if($result == null){
echo '<p>Sorry- no image.</p>';
}
else {
echo '<p>There is an image!</p>';
}
}