check if MySQL table is empty - php

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";
}

Related

PDO - Test Of Empty Results

I have a query that should look for an entry. If it's not in the database then enter in the data. Otherwise it returns back the data and they can update any fields. If there is an entry it will be only one. This works great if the entry is in the table. But I've tried checking for empty rows, doing row_count, etc and doesn't seem to work. Right now I just have this in the code(sanitized to remove company table information):
$query1 = " SELECT Number, Notes, Qty1, Qty2 FROM test.notes ";
$query1 .= " WHERE Number = '$searchnumber' ";
$result1 = $conn1->query($query1);
$conn1 = null;
if($result1==null)
{
echo "Result is null</p>\n";
return 0;
}
else
{
echo "Result is not null</p>\n";
return $result1;
}
If I take out the if check what I seem to get back is if it's found it returns the values correctly. If it's not found the result seems to be the query string itself. The check doesn't work. Probably because it returns back the query string if it's not found.
I know it's something simple but just haven't found it.
// if available in database
$query="SELECT Number, Notes, Qty1, Qty2 FROM test.notes WHERE Number='".$searchnumber."'";
$qnt = $conn1->query($query);
$coun = count($qnt->fetchAll());
if($coun > 0){
// available
echo "Result is available</p>\n";
}else{
//not available
echo "Result is not available</p>\n";
}
i Think you need something like this.
if this is not working fine, try another aproach
$queryi = $conn1->prepare("SELECT Number, Notes, Qty1, Qty2 FROM test.notes WHERE Number='".$searchnumber."' ");
$queryi->execute();
$qn= $queryi->fetchAll(PDO::FETCH_ASSOC);
foreach ($qn as $row => $data) {
$in_use = $data['Number'];
//echo $in_use ;
}
// evaluate
if($in_use == NULL){
//not avilable
}else{
// available
}
I suggest doing something like this:
Establish your query
$query1 = " SELECT Number, Notes, Qty1, Qty2 FROM test.notes ";
$query1 .= " WHERE Number = '$searchnumber' ";
See if there's a result for the query, and no error
if ($res = $conn1->query($sql)) {
/* Check the number of rows that match the SELECT statement */
if ($res->fetchColumn() > 0) {
/* Issue the real SELECT statement and work with the results */
$sql = "SELECT name FROM fruit WHERE calories > 100";
foreach ($conn->query($sql) as $row) {
print "Name: " . $row['NAME'] . "\n";
}
}
/* No rows matched -- do something else */
else {
print "No rows matched the query.";
}
}
After some trial and error I got this to work:
$result1 = $conn1->query($query1);
$count = $result1->fetchColumn();
if($count == "")
{
// echo "Result is null</p>\n";
return "0";
}
else
{
// echo "Result is not null</p>\n";
$result1 = $conn1->query($query1);
return $result1;
}
I had to change the setup to include:
$conn1->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, TRUE);
Probably not a clean way but it works for now. Thanks for all the help.

Using Mysqlii_query result object to check if the return value match the desired result

So I want to search the database and return a result, take a look at this query:
$sql = "SELECT workforce from users WHERE email='$username'";
$result = mysqli_query($con,$sql);
if($result == "General"){
echo "General Category";
}else
echo "Manager Category"
I found out that the result returned is not a string but an object, thus I am unable to find a way to achieve the desired result.
For this example I am expecting a single result. Also I want to return the result to a android code via Volley Library which I have already done.
I am stuck with the php part since I am not familiar with it.
You can try this:
Read for more info : mysqli_query mysqli_fetch_assoc
$sql = "SELECT workforce from users WHERE email='$username'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
if ($row['category'] == 'general') {
echo 'general category';
}else
{
echo 'manager category';
}
}
} else {
echo "0 results";
}
here you go
<?
$sql = "SELECT workforce from users WHERE email='$username'";
if($result = mysqli_query($con,$sql)): //check query
$row = mysqli_fetch_assoc($result);
if($row['workforce'] == "General") {
echo "General Category";
} else {
echo "Manager Category"
}
endif;

IF VAR is in mySQL database then return that rows data as variable PHP

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?

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";
}

PHP MYQSLi Returning a different value if field is empty

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>';
}
}

Categories