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
}
Related
What is the correct condition for the if statement in the code below
$sql = "INSERT INTO table ($columns) VALUES ($values)";
echo $sql;
$results = odbc_exec($conn, $sql);
if ($results){
echo "Query Executed";
}else {
echo "Query failed " .odbc_error();
}
or should it be
if ($results > 0){
Please advise.
From the manual: http://php.net/manual/en/function.odbc-exec.php
Returns an ODBC result identifier if the SQL command was executed
successfully, or FALSE on error.
So checking for a $result is OK:
<?php
...
$result = odbc_exec($conn, $sql);
if ($result) {
// OK
} else {
// Failure
}
The correct way to test odbc_exec() for success or failure is:
if ($result !== false) {
// success
} else {
// failure
}
The documentation says:
Returns an ODBC result identifier if the SQL command was executed successfully, or FALSE on error.
If a function returns a boolean (FALSE) or non-boolean values, be sure to use the identity comparison operator.
While if ($result) may work in this case (it depends on possible ODBC result identifiers), it will not work in other cases.
For example, strpos() returns FALSE if the substring is not found and the position of the substring otherwise - that means 0 is a positive result.
if ($result) would be wrong in this case while if ($result !== FALSE) will work as expected.
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))
The problem I am having is that it always returns true no matter if the username passed in is valid or not.
$data = array($_POST["username"]);
$db = new PDO('mysql:host=localhost;dbname=Example;charset=utf8', 'Example', 'Example');
$stmt = $db->prepare("SELECT * FROM Table WHERE username=?");
$num_rows = $stmt->execute($data);
if($num_rows>0){
echo "true";
}
else{
echo "false";
}
$stmt->execute($data) returns TRUE on success.
If you want to get the number of rows returned, you need to use fetchAll after the execute
USE SQL FUNCTIONS
SELECT COUNT(*) as uCount FROM Table WHERE username=? // you can change * to id, for example.
then check if($data['uCount'] > 0)
You can change your SQL statement a little bit and capture either true or false in return as query result.
SELECT count(username) > 0 as user_exists FROM Table WHERE username=?
Read the query result to find if it is true or false.
PDOStatement::execute() returns a boolean to indicate success; if you're using exception error handling it will always return true or throw an exception (recommended by yours truly).
You can fetch the results (assuming there's only one) like this:
if (($data = current($stmt->fetchAll(PDO::FETCH_ASSOC)) !== false) {
echo "yay";
// do stuff with $data
} else {
echo "sorry dude";
}
The use of current() returns the first element of the returned result set or false if there was none.
Update
If you only need to return true or false, it's better to do just this:
$stmt = $db->prepare("SELECT COUNT(*) FROM Table WHERE username=?");
if ($stmt->execute($data) && current($stmt->fetchAll(PDO::FETCH_COLUMN))) {
echo 'true';
} else {
echo 'false';
}
try this
$num_rows = $stmt->fetch(PDO::FETCH_NUM);
I'm sure this is a simple fix, I want to run a code block if an sql query comes back with a positive result. something like:
if($query = mysqli_query($cxn,"[query]"))
{
Code to be executed if the query returns a positive result
}
I have tried this format but doesn't work. I'm sure I have done this before but I'm running in to a wall here.
Hope you can help.
As stated in php.net/manual/mysqli.query.php, mysqli_query will:
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 should for you next question specify what you mean by positive result. But this code will see if there was an error, if the query returned an empty set, and so on... (I have not tried to run the code)
$result = mysqli_query($cxn,"[query]");
if ($result === FALSE) {
echo "There was an error";
}
else if ($result === TRUE) {
echo "The query was successful (a query that didn't return anything)";
}
else if (mysqli_num_rows($result) == 0) {
echo "The result is empty"
}
else {
echo '$result contains data';
}
So you mean if the query doesn't fail? then:
$query = mysqli_query($cxn, "[query]");
if($query !== false) {
// Code to be executed if the query returns a positive result
}
This is not dieing as I expected it to, if $key is not a value in the key_code column of the database. Instead it just continues. I'm probably missing something really simple.
$key = $_GET['k'];
$keycheck = mysql_query("SELECT * FROM ib_dist WHERE key_code = '$key'");
if (!$keycheck) {
die("A database error has occured.");
} else {
mysql_query returns a resource or false based on whether the query executed successfully. It does not in any way denote how many rows were returned or whether the query did anything, only whether it executed successfully.
Check how many results where returned or evaluate the returned result separately.
try checking the amount of rows found.
$key = $_GET['k'];
$result = mysql_query("SELECT * FROM ib_dist WHERE key_code = '$key'");
if (!$result) {
die("A database error has occured.");
} else if (0 == mysql_num_rows($result)) {
// unknown key action
} else {
// known key action
}