mysql query erro - php

I am using php and mysqli for my web project but every thing seems to be fine but it gives me boolean error at mysqli_num_rows();
Note: the first line I echo so I can see whether the values I entered are being passed or not and it works fine still on the next line it gives me error Boolean.
<?php
include("Database/database.php");
session_start();
$uname = $_SESSION['un'];
$upassword = $_SESSION['up'];
$varch = $_SESSION['ch'];
$sql = "SELECT `username`, `userpwd`, `userid` FROM `useraccount` WHERE username = '$uname' AND userpwd = '$upassword'";
echo $sql;
$result = mysqli_query($link, $sql);
if($rowcount = mysqli_num_rows($result))
{
if($varch == "on")
{
setcookie("name", $uname, time()+60*60*7);
setcookie("password", $upassword, time()+60*60*7);
}
header('Location: useraccount.php');
}
?>

The function "mysqli_query" returns the "mysqli_result object" when query run successfully.
Otherwise return "false".
In your case might be "false" is stored in $result might be query failed.
And "mysqli_num_rows" takes mysql_result object as parameter.Here when you
$result = mysqli_query($link, $sql);
the "false" i.e boolean is found.Thats why the error is shown.
You need to execute the output query in mysql (phpmyadmin) first. Correct it.
and use in your code

As you can read in manual
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.
You have to check if your query failed or returned empty result (contains FALSE value). You can do it in the same if where you have $rowcount = mysqli_num_rows($result). It will look like that:
if($result !== FALSE && $rowcount = mysqli_num_rows($result))

Related

mySQL returns result even though the database is empty

This SQL query return result and then session save empty variable like $_SESSION["fbid"] = $user->fbid; and array would be Array ( [fbid] => ).
$result = $mysqli->query("SELECT * FROM `users` WHERE `fbid` = '$fbid'") or die(mysqli_error());
if ($result) {
$user = $result->fetch_object();
...
The main question is, why is it passing through if ($result) when there isn't any records in the database?
You are saying if($result)
This states that your if will always be true.
You need to say if($result == 1) for example.
You need to have $result equal, or not equal.
That is how an if statement works. However, you are saying "if query" which wont work anyways, you need to say something like,
if(mysqli_num_rows($result) > 0){
$user = $result->fetch_object();
}
mysqli->query returns either true, or false or mysqli_result object.
Both true and mysqli_result object will pass if($result), and false returned in case of error. Getting empty result is not an error.
If you need to check if your query returns empty result, use $num_rows property, for example.
Your test if ($result) will only fail if mysqli_query() fails, perhaps with a syntax error.
If you have a valid query your test will pass. This is true even if your valid query returns an empty set (Finding nothing is a valid result).
You need to check the result of the query to ensure your query actually succeeded, but this is different from checking whether it returned anything.
Try
$result = $mysqli->query("select...");
if ($result->num_rows) {
// do stuff
}
mysqli::query returns FALSE if a query fails. In this case, it did not fail - it was successfully executed, and returned zero rows.
If you want to check for an empty result set, check the return value of fetch_object:
$user = $result->fetch_object();
if ($user) {
# do stuff...

Verifying MYSQL executed a result not using get_result()

What's the best way to verify mysql executed successfully and then returned a result when you CANNOT use the following code:
$db = dbConnect();
//begin prepared statements to search db
$stmt = $db->prepare("SELECT email,authentication,email_confirm,externalid,password,id, admin FROM users WHERE email=?");
$stmt->bind_param('s',$email);
$stmt->execute();
$result = $stmt->get_result();
if (!$result){
//error statement
} if (!(mysqli_num_rows($result)==0)){
//action to perform
} else {
// no result returned
}
I was using get_result numerous times in my scripts, and my hosting provider doesn't have mysqlnd driver so I have to rewrite a lot of code. I know I am limited to bind_result and fetch(), but I need a little help rewriting the code since my mindset is stuck in the way I first did it.
I'm also using mysqli and not PDO.
The Mysqli fetch() function will return one of 3 values:
TRUE - Success. Data has been fetched
FALSE - Error occurred
NULL - No more rows/data exists or data truncation occurred
This means you can set your query like this:
$db = dbConnect();
$query = "SELECT email,authentication,email_confirm,externalid,password,id, admin FROM users WHERE email=?";
$stmt = $db->prepare();
$stmt->bind_param('s',$email);
$stmt->execute();
$stmt->bind_result($email,$auth,$email_confirm,$externalid,$password,$id,$admin);
// Will only execute loop if returns true
$record_count = 0;
while($result = $stmt->fetch())
{
// Increment counter
$record_count++;
// Do something with bound result variables
echo("Email is $email");
}
// After the loop we either ran out of results or had an error
if($result === FALSE)
{
echo("An error occurred: " . $db->error());
}
elseif($record_count == 0)
{
echo("No records exist.");
}

How can I echo an array of values from a php mySQL query?

Basically I am attempting to make a login. I understand a very small amount of php, but everytime I try to log in it works. So it is not following my if statement below. So I would like to see if anyone can help me print the $results as not a string. Everytime I echo it, it says error can not print as string. Which makes me think its an array, can someone help ? =(
<?php
include('include/dbConnection.php');
if (isset($_REQUEST['attempt']))
{
//variables
$user = $_POST['user'];
$password = sha1($_POST['password']);
//SQL statement
$query = "SELECT COUNT(user)
FROM users
WHERE user = '$user'
AND password = '$password'";
//Execute prepared MySQL statement
$results = mysqli_query($dbc,$query) or die('Error querying database');
/* Here is where I want to print $results
if ($results = 1)
{
session_start();
$_SESSION['$user'];
header('location: home.php');
}
else
{
echo $results + 'Incorrect Username or Password';
}
*/
//Close dbConnect
mysqli_close($dbc);
}
?>
Use var_dump($output) or print_r($output) to display contents of an array.
You have to use this:
echo "<pre>";
print_r($results);
echo "</pre>";
It first echoes so that the print of the array is formatted properly. If you don't do this it will all be on one line.
Hope this helped! :D
mysql_query() returns a statement result handle, NOT the data you've requested in the query. You first have to fetch a row of data to get access to the actual query data:
$result = mysqli_query(...);
$row = mysqli_fetch_row($result);
$count = $row[0];
mysqli_query function returns false for unsuccessful queries. it returns a MySQLi_Result object for select or show queries and true for insert and update queries.
if your query fails for some reason your script will die because of or die statement and never returns false.
if ($results = 1)
statement assigns 1 to your result variable. when your script runs, your code enters this if block. because you control the assignment statement whether it is done or not.
your query is a select, mysqli_query function returns MySQLi_Result object.

MySQL query acting weird

I've got:
mysql_connect($host,$username,$password);
#mysql_select_db("db") or die("Error: Cannot select database");
$query = "select password from users where name = '".$_POST['login-userid']."'";
$result = mysql_query($query);
if ($result == false) {
echo "Invalid username or password";
} else {
if (mysql_result($result,0) == hash('sha256', $_POST['login-password'])) {
echo "Logging in...";
}
}
For some reason I keep getting an error for the mysql_result line, even when it shouldn't be executed (when the username doesn't exist, ie $result evaluates to false).
mysql_query will only return false if there is an error. In this case there is no error, there are just 0 rows.
You need to use mysql_num_rows to get the number of rows returned.
You can var_dump($result) and see the value, if it's a resource (according to php), then your query was successful, if not false is returned. It's a boolean false but your == should still be respected if indeed false was returned.
mysql_query($query);
returns the result set of your query. It does not return true or false.
You may use mysql_num_rows() to check if the result of the query exist such as:
if(mysql_num_rows($query)) {
// exist
} else {
// does not exist
}

What will the $result be when MySQL returns nothing?

This might seem ridiculously simple, but I've been getting all kinds of error depending on how I handle a query that returns nothing.
$query = "SELECT * FROM messages WHERE id > ".$messageId;
$result =mysql_query($query);
$time = time();
while(time()-$time<60 && $result==false)
{
$result = mysql_query($query);
}
if(result != false)
//Encode response
else
//return nothing
How do I check whether my mysql_query() returned anything?
You can check the number of returned rows using mysql_num_rows().
Presuming your loop is to query something until it gets a result, it would be
while(time()-$time<60 && $num_rows == 0)
{
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
(not sure whether what you're doing here is a really good idea, as it is likely to put a terrible burden on the database server, but that's a different issue)
mysql_query() will return false only on "real" errors, e.g. a misspelled query or lost connection.

Categories