Handling x2 (multiple) php $sql $results with if statement - php

I have a sql database that when a key is passed from the web page input box back to the sql database (server)
this generates the encoded key and passes it back to the web page.
If the wrong key is sent then it returns wrong key. If it is correct it will return the generated key.
This works perfectly.
However when i try to add an additional check in the name of payment 1 for true 0 for false i can not combine the two. Meaning i would like both conditions to be met to make this work. Here is the code that works.
$sql = "SELECT decrypt_key FROM keys WHERE software_key=" . "'" . $software_key_encoded . "'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["decrypt_key"];
}
} else {
echo "Failed";
}
$conn->close();
}
else {
echo "Failed";
}
followed by what i am trying to do, This throws the error of
Trying to get property of non-object in /---/ Failed
$sql = "SELECT decrypt_key FROM keys WHERE software_key=" . "'" . $software_key_encoded . "'";
$eql = "SELECT payment FROM new_keys WHERE payment =1";
$result = $conn->query($sql) && $result1 = $conn->query($eql);
if ($result->num_rows > 0 && $result1->num_rows > 1) {
while($row = $result->fetch_assoc()) {
echo $row["decrypt_key"];
#echo $row["payment"];
}
} else {
echo "Failed";
}
$conn->close();
}
else {
echo "Failed";
}

$result = $conn->query($sql) && $result1 = $conn->query($eql);
change this line to:
$result = $conn->query($sql);
$result1 = $conn->query($eql);
and in if statement change $result1->num_rows > 1 to $result1->num_rows > 0;

Split the result variables in 2 different statements like below
$result = $conn->query($sql);
$result1 = $conn->query($eql);
If you still face any issue please post the error message too.

Related

Why is this function only returning one (1st) value in what should be an array of 5?

I am running an SQL query when my user logs into my app to retrieve a list of 'communities' they are part of.
I am trying to test what values are being returned by pasting the login link directly into my address bar.
It should return an array of 5 entries, but it is only returning 1.
I have tested the SQL query in phpMyAdmin and it returns the correct result.
What am I doing wrong?
This is from userLogin.php
$communities = array();
$communities = $dao->getCommunities($email);
echo json_encode($communities);
Which runs the following function in MySQLDao.php
public function getCommunities($email){
$returnValue = array();
$sql = "SELECT communities.name \n"
. "FROM users \n"
. "join community_players \n"
. "on community_players.player_id=users.id \n"
. "join communities \n"
. "on communities.id=community_players.community_id \n"
. "WHERE users.user_email = '".$email."'";
$result = $this->conn->query($sql);
if($result != null && (mysqli_num_rows($result) >= 1)){
$row = $result -> fetch_array(MYSQLI_ASSOC);
if(!empty($row)){
$returnValue = $row;
}
}
return $returnValue;
}
This is currently returning {"name":"EnclliffeT"} in the browser.
However, there should be another 4 entries.
Your code is fetching only the first row. Replace these lines:
if($result != null && (mysqli_num_rows($result) >= 1)){
$row = $result -> fetch_array(MYSQLI_ASSOC);
if(!empty($row)){
$returnValue = $row;
}
}
with these:
if($result != null && (mysqli_num_rows($result) >= 1)){
while($row = $result -> fetch_array(MYSQLI_ASSOC)){
if(!empty($row)){
$returnValue[] = $row;
}
}
}
Your public function getCommunities($email){ is fetching only the first row, no matter how many are returned by the SQL query.
Try to apply the following change:
$results = array();
while ($row = $result->fetch_array(MYSQLI_ASSOC))
$results[] = $row;
}
return $results;
A query produces a resultset. That resultset can contain 0 to n rows. Therefore you must unload the resultset row by row in a loop of some sort. A while loop is the best way of doing this.
public function getCommunities($email){
// the query
$result = $this->conn->query($sql);
if ( ! $result ) {
//report error somehow
exit;
}
$returnValue = array();
while ( $row = $result -> fetch_array(MYSQLI_ASSOC)){
$returnValue[] = $row;
}
return $returnValue;
}

PHP and SQL wont work?

$sql = mysqli_query($db, "SELECT COUNT(ID) from bruker");
if (!$sql) {
while ($row1 = mysqli_fetch_array($sql, MYSQL_NUM)); {
echo $row1;
}
} else {
echo "Funker ikke";
}
I cant get it to work, all I get is the: else "Funker ikke".
1) Using wrong if condition. If query return true then insert into if condition
2) Wrong echo data using MYSQL_NUM. It return numeric array
$sql = mysqli_query($db, "SELECT COUNT(ID) from bruker");
if ($sql) {// if true
while ($row1 = mysqli_fetch_array($sql, MYSQL_NUM)) {
echo $row1['0'];//numeric array
}
} else {
echo "Funker ikke";
}
UPDATED as per below comments
$sql = mysqli_query($db, "SELECT COUNT(ID) from bruker");
if ($sql) {
$row1 = mysqli_fetch_array($sql, MYSQL_NUM);
echo $row1['0']; //numeric array
} else {
echo "Funker ikke";
}
Read http://php.net/manual/en/mysqli-result.fetch-array.php
Your code is correct except the not sign before sql in if condition.According to you if your sql query is wrong then the $row1 is displayed else if it is correct then "funker ikke" gets printed.Just the opposite. This code works:
$sql = mysqli_query($db, "SELECT COUNT(ID) from bruker");
if ($sql) {
// as the query can only return 1 row the while look is unnecessary
//while ($row1 = mysqli_fetch_array($sql, MYSQL_NUM)) {
$row = mysqli_fetch_array($sql, MYSQL_NUM)
echo $row[0];
} else {
echo "Funker ikke";
}
Your code are having two error there.
First, it should be true condition only can get into the display loop. But you put the condition as !$sql means false only can get into the loop. So, you should change !$sql to $sql. Besides, after the While loop should not direct put the semicolon. You try see the following code
$sql = mysqli_query($db, "SELECT COUNT(ID) from bruker");
if ($sql) {
while ($row1 = mysqli_fetch_array($sql, MYSQL_NUM))
{
echo $row1[0];
}
}
else {
echo "Funker ikke";
}
There are a few errors in your code
First you do not need a while loop to process a single result, SELECT COUNT() can only return one row.
Second as mysqli_query() for a SELECT query will return either FALSE or a mysqli_result object it would be better to flip your if condition as below and test specifically for FALSE rather than TRUE.
Third, a mysqli_fetch_array($sql, MYSQL_NUM) returns an array, you have to use array notation to get the only returned value i.e. $row[0]
Also when any mysqli_ function fails it leaves some error information that is very useful, so show that info or send it to an application error file if you dont want users to see them when the code goes live.
$sql = mysqli_query($db, "SELECT COUNT(ID) from bruker");
if ($sql === FALSE) {
echo "Funker ikke";
echo mysqli_error($db);
exit;
} else {
$row = mysqli_fetch_array($sql, MYSQL_NUM);
echo $row[0];
}

PHP SQL loop outputs as 0 rows

I am trying to create a PHP loop to show the players the tournaments they are partaking in. I tried the function on phpMyAdmin, and I got the result that I wanted. But when I try to run this simple script on PHP, it outputs as 0 rows.
index.php
chdir("../"); // path to MyBB
define("IN_MYBB", 1);
require("./global.php");
if($mybb->user['uid']) {
$sql = "SELECT * FROM players, tourneys WHERE players.forumname = 1 AND players.tid = tourneys.id";
$result = mysqli_query($conn, $sql);
// output data of each row
if (mysqli_num_rows($result) > 0) {
// output data of each ro
while($row = mysqli_fetch_assoc($result)) {
$name = $row['name'];
$date = $row['date'];
$time = $row['time'];
echo $name;
echo $date;
echo $time;
}
} else {
echo "0 rows";
}
}
The problem is not in "if ($mybb->user['uid']) {" as suggested by #Dagon. Try to leave the well indented code to avoid this kind of confusion. Run the code below and post the the DB error output.
Try this:
<?php
chdir("../"); // path to MyBB
define("IN_MYBB", 1);
require("./global.php");
if ($mybb->user['uid']) {
$player_forumname = '1';
// Return only the necessary fields
$sql = "SELECT tourneys.name, tourneys.date, tourneys.time
FROM tourneys
INNER JOIN players ON players.tid = tourneys.id
WHERE players.forumname = {$player_forumname}";
$result = mysqli_query($conn, $sql);
// If the query fails display the error
if ($result === FALSE) {
die('MySQLi Error: ' . mysqli_error($conn));
}
if (mysqli_num_rows($result) == 0) {
die('0 rows');
}
// Returns only the associative array
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$name = $row['name'];
$date = $row['date'];
$time = $row['time'];
echo 'Name:',$row['name'],'Date:',$row['date'],'Time:',$row['time'];
}
}

PHP Mysql If statement not working

Got a issue where if the rows are equal to 0 the else statement is not called. if i type in the correct details on the site, the first condition is met and the xml is displayed, however if the incorrect details are entered, the error xml is not displayed.
echo "<users>";
$result = mysql_query("SELECT * FROM `numbers` WHERE `email` = '".$email."' AND `password` = '".$password."'") or die('Invalid query: ' . mysql_error());
if (!$result) die('Invalid query: ' . mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
if(mysql_num_rows($result) != 0)
{
echo "<usercallback>";
echo "<id>".$row['id']."</id>";
//echo "<number>".$row2['number']."</number>";
//echo "<gender>".$row2['gender']."</gender>";
//echo "<relationship>".$row2['relationship']."</relationship>";
echo "</usercallback>";
}
else
{
echo "<usercallback>";
echo "<id>error</id>";
echo "</usercallback>";
}
}
echo "</users>";
actually you have to put the if mysql_num_rows check outside the while block
echo "<users>";
$result = mysql_query("SELECT * FROM `numbers` WHERE `email` = '".$email."' AND `password` = '".$password."'") or die('Invalid query: ' . mysql_error());
if(mysql_num_rows($result) != 0)
{
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo "<usercallback>";
echo "<id>".$row['id']."</id>";
//echo "<number>".$row2['number']."</number>";
//echo "<gender>".$row2['gender']."</gender>";
//echo "<relationship>".$row2['relationship']."</relationship>";
echo "</usercallback>";
}
}
else
{
echo "<usercallback>";
echo "<id>error</id>";
echo "</usercallback>";
}
echo "</users>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
If there are no rows then $row will be false and it will never enter the above while loop.
So you can not get error message
You check for rows while performing the loop, you should check for the number of rows BEFORE the while loop.
It looks like you're expecting a zero-row response from MySQL to result in an undef $result. That's not what happens. mysql_query() returns null if there was an error. You can test the "truth" of its return value to see if the query ran correctly. If the query results in 0 rows of response, it ran correctly. The value to test, then is mysql_num_rows($result).
However, it can be done simpler. I usually write this like:
$res = mysql_query("SELECT 1");
if (!$res) {
//do whatever error reporting if the SQL was bad
//though you should probably deal with any condition that ends up
//here before you go into production!
}
if (mysql_num_rows($res) == 0) {
//put out my "no results found" message
}
while ($row = mysql_fetch_assoc($res)) {
//do my per-row business
}
mysql_fetch_assoc() returns false when there are no (or no more) results to return. So if it's empty, that while loop will never run, so it doesn't need to be inside an else.

How can I show a message when no rows have been selected in mysql, php?

My code looks like this:
$result = mysql_query("SELECT * FROM `picdb` WHERE `picid` = '$picid' ") or trigger_error(mysql_error());
while($row = mysql_fetch_array($result)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
Problem is that when there is no row to select, nothing happens, my $row array is empty.
How can i have this present a message of "no row found" when no rows match the select?
try
if (mysql_num_rows($result) == 0) {
// Show message
} else {
// do your while stuff here
}
Use mysql_num_rows() to determine the amount of rows in your result.
$result = mysql_query("SELECT * FROM `picdb` WHERE `picid` = '$picid' ") or trigger_error(mysql_error());
if(mysql_num_rows($result) == 0) {
echo "No row found!"
} else {
while($row = mysql_fetch_array($result)) {
foreach($row AS $key => $value) {
$row[$key] = stripslashes($value);
}
}
}
if (mysql_num_rows($result) == 0) {
echo "Result is empty!";
}
You should've read the description of mysql_query, it gives you the answer: http://php.net/mysql_query
mysql_num_rows() only works on buffered queries. If you have potentially a large/huge result set you might switch to unbuffered queries and num_rows is not an option anymore.
You can test the return value of the first call to mysql_fetch_array(). If it's FALSE there were no matching records.
<?php
$result = mysql_query("SELECT * FROM `picdb` WHERE `picid` = '$picid' ") or trigger_error(mysql_error());
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if ( !$row ) {
echo '0 rows';
}
else {
do {
echo htmlspecialchars($row['x']), "<br />\n";
} while($row=mysql_fetch_array($result, MYSQL_ASSOC));
}
The downside of this do { } while() is that the $row=mysql_fetch... code has been duplicated. But it's only a small doublet.
This method never seems to fail for me.
if(!$result = mysqli_query($con,"SELECT * FROM `picdb` WHERE `picid` = '$picid' ")){
// Enter you error message here.
} else {
// Do all your magic.
}

Categories