If no results in table show X, PHP MySQL - php

I have a query on my site and if there is no results, I'd like to say something else rather than have a blank page...
$sth = $conn->prepare("SELECT * FROM directory WHERE user_active != '' AND County = :county");
$sth->execute(array(':county' => $county));
$c = 1;
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
RETURNED DATA GOES HERE
$c++;
}

$sth->execute(array(':county' => $county));
if ($sth->rowCount() == 0) {
echo 'no rows';
} else {
while(yada yada yada) { ... }
}
Relevant docs: http://php.net/manual/en/pdostatement.rowcount.php

You're counting the results in $c, so you can check which value that has by appending your code with this:
if($c == 1) { // Counter is stuck at 1
echo "No results were found.";
}

2 possible solution,
execute a SELECT COUNT
execute a fetchall check it and later display the result

Related

I want to delete top first row from table in firebase Database

I want to delete top first row from table in firebase Database when no. of rows reach to 50.
I can search this lot of time but still not found. Anyone tell that how I can do this.
Through this technique
$searchdata = "Data";
$fetchdata = $database->getReference($searchdata)->getValue();
$found = 0;
$array=0;
if($fetchdata > 0)
{
foreach($fetchdata as $Key => $row)
{
if($found == 0)
{
$del = "Data/".$Key;
$DelRef = $database->getReference($del)->remove();
$found=1;
}
else
{
break;
}
}
}

Mysqli_stmt_num_rows and foreach

Hi i've got the following code, I'm trying calculate num rows to show a message if there is no rows in the database. I've got an array and I've used foreach to loop the arrays values and query the database. The problem is that if one of the ids from the array returns 0 rows but the other returns one row I get the value from the database query but also the message saying no rows found. Does anybody know why? Many thanks
$user_id = 30;
// Array of ids
$id_gruppo= user_group_ids($conn, $user_id);
$query_last_tickets = mysqli_prepare($conn, "SELECT ticket_id, ticket_subject, ticket_body, ticket_time_stamp, ticket_status, ticket_user_id, ticket_group FROM user_tickets WHERE ticket_group = ? ORDER BY ticket_time_stamp DESC LIMIT 5");
mysqli_stmt_bind_param($query_last_tickets, 'i', $data);
foreach ($id_gruppo as $data) {
mysqli_stmt_execute($query_last_tickets);
mysqli_stmt_bind_result($query_last_tickets, $ticket_id, $ticketsubject, $ticketbody, $ticketdate, $ticketstatus, $ticketuserid, $ticket_group);
mysqli_stmt_store_result($query_last_tickets);
$numTicket = mysqli_stmt_num_rows($query_last_tickets);
if ($numTicket > 0) {
while (mysqli_stmt_fetch($query_last_tickets)) {
echo $ticket_id;
}
}
}
if ($numTicket < 1) {
echo "no rows found";
}
You're checking the variable $numTicket after the loop that is updated inside the loop.
If the last $numTicket is 0, you'll fall in your last condition.
You can try something like this :
$have_tickets = false ;
foreach ($id_gruppo as $data) {
mysqli_stmt_execute($query_last_tickets);
mysqli_stmt_bind_result($query_last_tickets, $ticket_id, $ticketsubject, $ticketbody, $ticketdate, $ticketstatus, $ticketuserid, $ticket_group);
mysqli_stmt_store_result($query_last_tickets);
$numTicket = mysqli_stmt_num_rows($query_last_tickets);
if ($numTicket > 0) {
$have_tickets = true;
while (mysqli_stmt_fetch($query_last_tickets)) {
echo $ticket_id;
}
}
}
if (!$have_tickets) {
echo "no rows found";
}
You are assigning a value to $numTicket each time through the loop. This means that when you get to the if statement after the loop, it will contain the last value assigned to it within the loop. What you want to do is use a flag to determine if any of the iterations through the loop produce a count/result.
$user_id = 30;
// Array of ids
$id_gruppo= user_group_ids($conn, $user_id);
$query_last_tickets = mysqli_prepare($conn, "SELECT ticket_id, ticket_subject, ticket_body, ticket_time_stamp, ticket_status, ticket_user_id, ticket_group FROM user_tickets WHERE ticket_group = ? ORDER BY ticket_time_stamp DESC LIMIT 5");
mysqli_stmt_bind_param($query_last_tickets, 'i', $data);
// initialize the flag to false
$ticketsFound = false;
foreach ($id_gruppo as $data) {
mysqli_stmt_execute($query_last_tickets);
mysqli_stmt_bind_result($query_last_tickets, $ticket_id, $ticketsubject, $ticketbody, $ticketdate, $ticketstatus, $ticketuserid, $ticket_group);
mysqli_stmt_store_result($query_last_tickets);
$numTicket = mysqli_stmt_num_rows($query_last_tickets);
if ($numTicket > 0) {
// flip the flag to true since tickets were found
$ticketsFound = true;
while (mysqli_stmt_fetch($query_last_tickets)) {
echo $ticket_id;
}
}
}
if (!$ticketsFound) {
echo "no rows found";
}

How to check if all rows match a criteria in PHP

I want to check if a certain field of all rows match a criteria.
So if all rows has in the Status field 'RUN' as value then echo "Success".
If there is one row with END as value then echo "Fail":
I'm guessing I need a loop and an IF statement ?
I was thinking something like this but it doesnt return anything:
while($source_row = mysqli_fetch_array($source_selection)){
if ( ($source_row['Stat']) == ("Run" ) {
echo "Success<br />";
} else
echo "Fail";
}
I don't want to echo each row, I want all rows to match a criteria then echo, if one doesn't match a criteria then echo as well.
This should work for you:
First of all you have to fetch all rows with mysqli_fetch_all(). After this I extract only the Stat column with array_column(). Then I just simply array_fill() an array with X values as you have in $states with the value "Run". And check if every value is equals.
$result = mysqli_fetch_all($source_selection, MYSQLI_ASSOC);
$states = array_column($result, "Stat");
if($states == array_fill(0, count($states), "Run")) {
echo "Success";
} else {
echo "Fail";
}
There are some error in the code and you can use the count to match -
$count = 0;
while($source_row = mysqli_fetch_array($source_selection)){
if ($source_row['Stat'] == "Run" ) {
$count++;
}
}
if($count != mysqli_num_rows($source_selection)) {
echo "Fail";
} else echo "Success";
For best performance you can do it directy on the SQL:
select count(*) from table where Stat <> 'Run';
And then test the returning value to check that is greater than zero.
To do it with php you should know that when you find an error you can stop the iterations. The code would look like that:
while($source_row = mysqli_fetch_array($source_selection)){
if ( $source_row['Stat'] != "Run" ){
$fail = true;
break;
}
}
if ($fail) {
echo "Fail";
} else
echo "Success";
}
Try this
$success=true;
while($source_row = mysqli_fetch_array($source_selection)){
if ( ($source_row['Stat']) != ("Run" ) {
$success=false;
}
}
if ($success) {
echo "Success";
} else {
echo "Fail";
}

Check for empty rowset in oci_fetch_array

I am doing the following...
$approved = oci_parse($conn_prs, "select * from patch_files where patch_reviewer = '". $_SESSION['id'] ."' and patch_status = 'Approved'"); // now rows available for current id
oci_execute($approved);
while ($row = oci_fetch_array($approved, OCI_BOTH + OCI_RETURN_NULLS )) {
var_dump($row); // shows nothing
if ($row == null) { echo "<p>None Found...</p>"; }
else { ....
Not sure why the null condition is not working...
Your null condition is not working because $row is never null. oci_fetch_array() returns an array of the row fields, or false. If there are no rows your while loop is not executed.
You seem to have misunderstood the purpose of OCI_RETURN_NULLS. When used, it creates array elements for empty fields in $row, not an empty array if there are no rows.
A quick and dirty way to do what you want is:
$i = 0;
while ($row = oci_fetch_array($approved, OCI_BOTH + OCI_RETURN_NULLS)) {
$i++;
...
}
if ($i == 0) {
echo "<p>None Found...</p>";
}
try with -
while ($row = oci_fetch_array($approved, OCI_BOTH + OCI_RETURN_NULLS )) {
var_dump($row); // shows nothing
if (empty($row)) { echo "<p>None Found...</p>"; }
else { ....
oci_fetch_array() - returns the next row from a query as an array.

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

Categories