Check if the fetched array is empty or not PHP? - php

I am trying to check if the mysql_fetch_array() function returns an empty array or not. But my code doesn't seem to work. Here I want to ensure that if the array is empty I want to display under construction message.
Code :
$queryContents= queryMembers();
$exeQuery = mysql_query($queryContents);
while($fetchSet = mysql_fetch_array($exeQuery)) {
if(count($fetchSet) == 0) {
echo "This Page is Under Construction";
}else{
// something else to display the content
}
}
How do I check to acheive such feature ?

use mysql_num_rows to count number of rows. try this.
$exeQuery = mysql_query($queryContents);
if(mysql_num_rows($exeQuery)== 0){
echo "This Page is Under Construction";
}
else{
while($fetchSet = mysql_fetch_array($exeQuery)) {
// something else to display the content
}
}

You really should be using mysql_num_rows http://us2.php.net/manual/en/function.mysql-num-rows.php
However, on a side note, you should use php empty() instead. http://us2.php.net/empty

When you use mysql_fetch_array(), it returns the rows from the data
set one by one as you use the while loop.
If there will be no record, while loop wont execute. In this case, declare a boolean variable and make it true if it enters the while loop. Like:
$queryContents= queryMembers();
$exeQuery = mysql_query($queryContents);
$recordExists = 0;
while($fetchSet = mysql_fetch_array($exeQuery)) {
if($recordExists == 0 )
$recordExists = 1;
// something else to display the content
}
if($recordExists == 0 ){
echo "This Page is Under Construction";
}
Hope this works!

You can do it this way:
while($r[]=mysql_fetch_array($sql));
// now $r has all the results
if(empty($r)){
// do something
}
source: php doc

Your code inside the while loop never runs if there are no results. mysql_fetch_array returns null/false if there are no more results. What you need yo do is check with mysql_num_rows first, before the while.
$queryContents= queryMembers();
$exeQuery = mysql_query($queryContents);
if(mysql_num_rows ($exeQuery) == 0) {
echo "This Page is Under Construction";
}
while($fetchSet = mysql_fetch_array($exeQuery)) {
// something else to display the content
}

Try this
if(empty($fetchSet)
{
echo "This Page is Under Construction";
}
else
{
// something else to display the content
}

Related

Comparison of words from the database and output of the result

I need to check the words received from the database with the user's entered word and if there is a match, then output its value from the database, and if not, then output what the user entered.
The code below works fine if there is a match.
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('SELECT vozmozhnyi_variant_mesta, ego_slovoforma_v_predlozhnom_padezhe FROM dEzpra_jet_cct_tip_mest_obrabotki');
if ($typeplace_results) {
foreach ($typeplace_results as $typeplace_result) {
$d_typeplace_raw = mb_strtolower($typeplace_result->vozmozhnyi_variant_mesta);
$d_typeplace_morf = mb_strtolower($typeplace_result->ego_slovoforma_v_predlozhnom_padezhe);
$d_typeplace = mb_strtolower($d_typeplace);
if (stripos($d_typeplace, $d_typeplace_raw) !== false) {
echo $d_typeplace_morf;
}
}
}
}
I'm an amateur in PHP, just learning. And I can't figure out how to output $d_typeplace if no match is found.
I tried to add
else {
echo $d_typeplace;
}
, but I get an array of words from the user entered.
I will be grateful for any help. Also for any suggestions for improving this code.
---Addition---
I apologize for my English. This is a problem in the Russian language, I need to take into account the morphology. To do this, the database has a list of words and their analog, for example, X = Y. I get these words and compare what the user entered. If he entered X, then we output Y. If he led Z, which is not in the database, then we output Z.
Thus, we check $d_typeplace with $d_typeplace_raw and if there is a match, we output $d_typeplace_morf, which is equal to $d_typeplace_raw. And if not, then $d_typeplace (it contains the value that the user entered).
Oh, I'm sorry, I understand myself that I'm explaining stupidly)
I cannot quite understand what you are asking: you need to output the string entered by the user, but you can only print an array?
If this is the case, I think you parsed the string before, in order to therefore you need to do join again the values contained in the array.
Try with:
else {
echo implode(" ", $d_typeplace);
}
--- EDITED ---
Try with:
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('SELECT vozmozhnyi_variant_mesta, ego_slovoforma_v_predlozhnom_padezhe FROM dEzpra_jet_cct_tip_mest_obrabotki');
if ($typeplace_results) {
$found = false;
foreach ($typeplace_results as $typeplace_result) {
$d_typeplace_raw = mb_strtolower($typeplace_result->vozmozhnyi_variant_mesta);
$d_typeplace_morf = mb_strtolower($typeplace_result->ego_slovoforma_v_predlozhnom_padezhe);
$d_typeplace = mb_strtolower($d_typeplace);
if (stripos($d_typeplace, $d_typeplace_raw) !== false) {
echo $d_typeplace_morf;
$found = true;
break;
}
}
if (!$found) {
echo $d_typeplace;
}
}
}
But I think it would be more efficient, if you implemented the second code snippet written by #Luke.T
I'm presuming you were trying to add the else like this?
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('SELECT vozmozhnyi_variant_mesta, ego_slovoforma_v_predlozhnom_padezhe FROM dEzpra_jet_cct_tip_mest_obrabotki');
if ($typeplace_results) {
foreach ($typeplace_results as $typeplace_result) {
$d_typeplace_raw = mb_strtolower($typeplace_result->vozmozhnyi_variant_mesta);
$d_typeplace_morf = mb_strtolower($typeplace_result->ego_slovoforma_v_predlozhnom_padezhe);
$d_typeplace = mb_strtolower($d_typeplace);
if (stripos($d_typeplace, $d_typeplace_raw) !== false) {
echo $d_typeplace_morf;
} else {
echo $d_typeplace;
}
}
}
}
Which was outputting an array because the for loop was continuing, if you add a break like so...
echo $d_typeplace;
break;
It should stop outputting an array. Depending on your use case you could however perform similar functionality directly in your sql query using LIKE ...
function d_typeplace_morf($d_typeplace)
{
global $wpdb;
$typeplace_results = $wpdb->get_results('
SELECT ego_slovoforma_v_predlozhnom_padezhe
FROM dEzpra_jet_cct_tip_mest_obrabotki
WHERE vozmozhnyi_variant_mesta LIKE %' . $d_typeplace . '%');
if ($typeplace_results) {
//Echo result
} else {
echo $d_typeplace;
}
}

How do you make sure an array is empty in PHP?

Im writing a page in HTML/PHP that connects to a Marina Database(boats,owners etc...) that takes a boat name chosen from a drop down list and then displays all the service that boat has had done on it.
here is my relevant code...
if(isset($_POST['form1'])){//if there was input data submitted
$form1 = $_POST['form1'];
$sql1 = 'select Status from ServiceRequest,MarinaSlip where MarinaSlip.SlipID = ServiceRequest.SlipID and BoatName = "'.$form1.'"';
$form1 = null;
$result1 = $conn->query($sql1);
$test = 0;
while ($row = mysqli_fetch_array($result1, MYSQLI_ASSOC)) {
$values1[] = array(
'Status' => $row['Status']
);
$test = 1;
}
echo '<p>Service Done:</p><ol>';
if($test = 1){
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
echo '</ol>';
}else{
echo 'No service Done';
}
the issue im having is that some of the descriptions of sevice are simply Open which i do not want displayed as service done, or there is no service completed at all, which throws undefined variable: values1
how would I stop my script from adding Open to the values1 array and display a message that no work has been completed if values1 is empty?
Try this
$arr = array();
if (empty($arr))
{
echo'empty array';
}
We often use empty($array_name) to check whether it is empty or not
<?php
if(!empty($array_name))
{
//not empty
}
else
{
//empty
}
there is also another way we can double sure about is using count() function
if(count($array_name) > 0)
{
//not empty
}
else
{
//empty
}
?>
To make sure an array is empty you can use count() and empty() both. but count() is slightly slower than empty().count() returns the number of element present in an array.
$arr=array();
if(count($arr)==0){
//your code here
}
try this
if(isset($array_name) && !empty($array_name))
{
//not empty
}
You can try this-
if (empty($somelist)) {
// list is empty.
}
I often use empty($arr) to do it.
Try this instead:
if (!$values1) {
echo "No work has been completed";
} else {
//Do staffs here
}
I think what you need is to check if $values1 exists so try using isset() to do that and there is no need to use the $test var:
if(isset($values1))
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
Or try to define $values1 before the while:
$values1 = array();
then check if it's not empty:
if($values1 != '')
foreach($values1 as $v1){
echo '<li>'.$v1['Status'].'</li>';
}
All you have to do is get the boolean value of
empty($array). It will return false if the array is empty.
You could use empty($varName) for multiple uses.
For more reference : http://php.net/manual/en/function.empty.php

GET Multiple MySQL Rows, Form PHP Variables, and Put Into Json Encoded Array

I am trying to GET different rows from different columns in php/mysql, and pack them into an array. I am able to successfully GET a jason encoded array back IF all values in the GET string match. However, if there is no match, the code echos 'no match', and without the array. I know this is because of the way my code is formatted. What I would like help figuring out, is how to format my code so that it just displays "null" in the array for the match it couldn't find.
Here is my code:
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode($fbaddra);
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['addr'];
} else {
$fbaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['addr'];
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
UPDATE: The GET Request
I would like the GET request below to return the full array, with whatever value that didn't match as 'null' inside the array.
domain.com/api/core/engine.php?a=fbaddra&facebook=username&facebookp=pagename
The GET above currently returns null.
Requests that work:
domain.com/api/core/engine.php?a=fbaddra&facebook=username or domain.com/api/core/engine.php?a=fbaddra&facebookp=pagename
These requests return the full array with the values that match, or null for the values that don't.
TL;DR
I need assistance figuring out how to format code to give back the full array with a value of 'null' for no match found in a row.
rather than assigning as 'null' assign null. Your full code as follows :
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode('no match');
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
You can even leave else part altogether.
Check your code in this fragment you not use same names for variables:
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = 'null';
}
$fbaddr not is same as $fpaddr, this assign wrong result to if statement.
It was the mysql query that was the problem.
For those who come across this, and need something similar, you'll need to format your query like this:
** MYSQL QUERY **
if ($_GET['PUTVALUEHERE']) {
$g = $_GET['PUTVALUEHERE'];
$gq = $mysqli->real_escape_string($g);
$q1 = "SELECT * FROM `addrbook` WHERE `facebookp` = '".$gq."' OR `facebook` = '".$gq."'";
}
** PHP CODE **
if($_GET['PUTVALUEHERE']{
echo json_encode($row['addr']);
}

How to check if php mysqli_fetch_array is empty before while loop

I wanted to make sure there are results before running the while loop but all the methods I am trying seem to remove the first result.
$nearbyResult = mysqli_query($con,$sqlNearby);
if(mysqli_fetch_array($nearbyResult) == 0) {
echo '<p>No results found, Add your property here.</p>';
} else {
while($rowNearby = mysqli_fetch_array($nearbyResult)) {
}
}
This line will take the first row of your result set and chuck it in the bin:
if(mysqli_fetch_array($nearbyResult) == 0) {
Change to:
if( ! mysqli_num_rows($nearbyResult) ) {
And check your freakin function returns:
if( ! $nearbyResult = mysqli_query($con,$sqlNearby) ) {
echo "Mysql error: " . mysqli_error($con);
}
You can use the mysql_row_count method to count how many rows are returned in your query http://php.net/manual/en/mysqli-result.num-rows.php
Try assigning the results to a variable as part of your if statement. If mysqli_fetch_array() has no result set to work with it will return false.
if($rowNearby = mysqli_fetch_array($nearbyResult)) {
//There was a result, work with it here
doStuffWith($rowNearby);
} else {
//No records in your result set, handle as desired
}

How to check if results on while($row = mysql_fetch_array in PHP

Im trying to figure out how to handle this is no results are returned, how would I code that?
while($row = mysql_fetch_array($Result))
So like if there a results: print them out
else: show a link
http://ca3.php.net/manual/en/function.mysql-num-rows.php
if(mysql_num_rows($result) > 0) {
while($row = mysql_fetch_array($result)) { ... }
} else {
// show link
}
You can use mysql_num_rows() to tell you how many results are found. Using that with a simple if-statement, and you can determine what action to take.
if (mysql_num_rows($result) > 0) {
// do while loop
} else {
// show link
}
Others suggest using mysql_num_rows() but you should be aware that that function works only if you use a buffered query. If you query using mysql_unbuffered_query(), the number of rows in the result is not available.
I would use a simple flag variable:
$found_row = false;
while ($row = mysql_fetch_array($result)) {
$found_row = true;
. . .
}
if ($found_row == false) {
// show link
}
It may seem redundant to set $found_row to true repeatedly, but assigning a literal value to a variable ought to be an insignificant expense in any language. Certainly it is small compared to fetching and processing an SQL query result.
Use even shorter syntax without insignificant mysql_num_rows to save processor time:
if($result) {
// return db results
} else {
// no result
}
I might have figured it out:
if (!($row = mysql_fetch_array($descResult)))
{
echo "<tr><td>Add Link</td></tr>";
}
This can be done without mysql_num_rows() or an additional (flag) variable
if ( false===($row=mysql_fetch_array($result, MYSQL_ASSOC)) ) {
echo 'no rows in result set';
}
else {
do {
echo $row['X'];
} while ( false===($row=mysql_fetch_array($result, MYSQL_ASSOC)) );
}
but it duplicates the actual fetch command (one in the if-statement and one in the while-clause).

Categories