Displaying a message when resultset is empty - php

In the following code, if the resultset is empty, the code continues to process the result. What I want instead is to just display "Query failed." when there are no results.
$connInfo = array('UID'=>$user, 'PWD'=>$passwd, 'Database'=>$database);
$dbconn = sqlsrv_connect($server, $connInfo);
if($dbconn === false){
die("<br />Error connecting to the database.<br />");
}
//SQL Query
$query = "SELECT ... FROM somehwere";
//Run Query
$qresult = sqlsrv_query($dbconn, $query);
if($qresult === false) {
die('Query failed.');
}
?>
...more code...

$qresult will contain an empty result set if no rows are found, but it still won't evaluate to false.
Try this function instead:
http://www.php.net/manual/en/function.sqlsrv-num-rows.php
So:
if(!sqlsrv_num_rows($qresult)) {
die('Query failed.');
}
Instead of:
if($qresult === false) {
die('Query failed.');
}

It does not display "Query Failed" because the query has not failed. It just returns 0 rows. So, the solution will be to use:
$row_count = sqlsrv_num_rows( $qresult);
if ($row_count > 0){
// display stuff
}
else{
// throw exception
}

Thanks. I got it to work using sqlsrv_has_rows() function.
if($qresult !== NULL) {
$rows = sqlsrv_has_rows($qresult);
if($rows === true) {
//display success
} else {
//display error
}
}
For some reason I couldn't get the sqlsrv_num_rows() to work properly for me.

Related

$connection->query($mysearch) not working

The error occurs like that, when i try to connect to DB to search something, it doesn't connects... here is the code below
$connection = new mysqli($db_server,$db_user,$db_pass,$db_name);
if($connection->connect_errno)
{
die ("Connection Failed");
}
$selcap = "SELECT * FROM captcha_codes ORDER BY RAND() LIMIT 1";
$seldcap = $connection->query($selcap);
if($seldcap === true)
{
while ($capdata = $seldcap->fetch_array(MYSQLI_BOTH))
{
$imglink = $capdata['image'];
$idcap = $capdata['id'];
$codecap = $capdata['code'];
}
} else {
$msgreg = "Couldn't connect to Captcha, please contact admin!";
}
The result is Couldn't connect to Captcha, please contact admin!
Use the less strict == comparison here: if($seldcap === true), that should solve the issue.
So the condition would look like: if($seldcap == true)
As mentioned by others, you could also check the number of results as well.
See the docs for mysqli::query() for more information on the results of that function.
If you want to check either query returns result or not use num_rows :
$seldcap = $connection->query($selcap);
if($seldcap->num_rows > 0)
{
//your while stuff
}
else{
//your error stuff
}

Why is php skipping the if statement?

The basics of what I want to do is check the user values.
If they are there return true and go back to the page otherwise return false and print null values.
$query = sprintf("SELECT * from Users where username = ? and password = ?");
$params1 = array( $username, $password);
$stmt = sqlsrv_query($conn, $query, $params1);
if ($stmt === false)
{
die(print_r(sqlsrv_errors(), true));
}
$Users = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$username1 = $row['username'];
$password1= $row['password'];
}
$Users["username"] = $username1;
$Users["password"] = $password1;
//echo json_encode($Users);
echo "you are here";
if ($username1==null)
{
return false;
echo "null values";
}
else {
return true;
if (!empty($_SERVER['HTTP_REFERER']))
header("Location: ".$_SERVER['HTTP_REFERER']);
else
echo "No referrer.";
}
echo "\n\nyou're at the end though";
sqlsrv_free_stmt($stmt);
sqlsrv_close( $conn );
}
else {
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
As you can see I am trying to debug the program and see where the program is going. It gets to the point
//echo json_encode($Users);
echo "you are here";
After that nothing else seems to work and I don't know why.
Directly after your working echo you have:
if ($username1==null)
{
return false;
...
}
else
{
return true;
...
}
...
So nothing after this will get executed because of the return statements. From the manual:
If called from within a function, the return statement immediately
ends execution of the current function, and returns its argument as
the value of the function call. return also ends the execution of an
eval() statement or script file.
If called from the global scope, then execution of the current script
file is ended.
Also note that you should check for the number of rows returned from your query, now you will get undefined variable warnings if no row was found.
before you enter thw while statment you need to check the row count in if statment if its not 0 return true else return false something like this
if(sqlsrv_num_rows($stmt)
{
// your code be here
return true;
}else{
// your code be here
return false;
}
http://php.net/manual/en/function.sqlsrv-num-rows.php

if else condition 'else' is not working

/MY CODE/
The if part is working properly but else is not working.
i even tried $variable instead of direct echo but still it is not working 'else'
Updated
<?php
$db = new mysqli('localhost', 'root' ,'', 'timeline');
if(!$db) {
echo 'Could not connect to the database.';
} else {
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
if(strlen($queryString) >0) {
$query = $db->query("SELECT collegename FROM college WHERE collegename LIKE '$queryString%' LIMIT 10");
if(isset($query)) {
echo '<ul>';
while ($result = $query ->fetch_object()) {
echo '<li onClick="fill(\''.addslashes($result->collegename).'\');">'.$result->collegename.'</li>';
}
echo '</ul>';
} else {
echo 'create some'; // this part is not working
}
} else {
// do nothing
}
} else {
echo 'There should be no direct access to this script!';
}
}
?>
help me out.....
even read lots of like problem on stackoverflow but no real return
If you are using mysqli::query then your if(isset($query)) statement will always be evaluated as true, as $query would be either FALSE or a mysqli_result object. isset returns TRUE for both these values, so your else code will never be called.
Documentation on isset:
Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
Use if($query !== false) instead.
Update
It also seems like you are checking $query to see whether or not there was a hit in the database. You need to check the number of rows in the result for that, e.g:
if ($query !== false && $query->num_rows > 0) {
// Query was ok and at least one row was returned
}
else {
// Will be reached if query was bad or there were no hits
}
Try
if($query_run = $db->query("SELECT collegename FROM college WHERE collegename LIKE '$queryString%' LIMIT 10")){
echo '<ul>';
while ($result = $query ->fetch_object()) {
echo '<li onClick="fill(\''.addslashes($result->collegename).'\');">'.$result->collegename.'</li>';
}
echo '</ul>';
} else {
echo 'create some';
}

MYSQli select not working

I am not actually very good at it, but I never got this kind of error. I am trying to select GB entries and I can't get it working.
gb.php
<?php
$conn = new mysqli('localhost','ab','somepassword','gb');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);}
else {echo 'connected';}
$sql = "SELECT * FROM `posts`";
if ($conn->query($sql) === TRUE) {
echo 'done';
}
else{echo 'sql not working';}
?>
Table snapshot
Result:
connectedsql not working
One more thing the INSERT & UPDATE statements are working from same folder.
The return value of MySqlI->query() is defined like:
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.
So you must check for not equal to false
if ($result !== false) {
you can also check on this condition
$res=$conn->query($sql);
if($res)
{
}
else
{
}
mysqli_query/ $mysqli->query does not return True if the query executed succesfully but return false if not executed..Try with -
$result = $conn->query($sql);
if ($result !== false) {
echo 'done';
}
else{echo 'sql not working';}

PHP $result = mysql_query($query) returns true even if there is no value in database

I have the following code.
$query = "SELECT HealthStatus FROM healthstatus where HealthStatus=$HealthStatus";
$result = mysql_query($query);
echo $HealthStatus;
if($result = false)
{
//do something
}
else
{
//print value already exists
}
I don't get any error or warning when the code is executed. But, even if $HealthStatus exists in database, the if part gets executed. When I give echo $HealthStatus, the value fetched is printed correctly.
I have tried using if(!$result). That doesn't work either. Can someone help me.
You have to use mysql_num_rows to know if the query returned any rows, eg:-
if($result && mysql_num_rows($result))
{
// a row exists
}
else
{
// do something
}
also if HealthStatus is a string it needs to be enclosed in quotes eg:-
$query = "SELECT HealthStatus FROM healthstatus where HealthStatus='".$HealthStatus."'";
$result = mysql_query($query);
if($result && mysql_num_rows($result))
{
// a row exists
$row=mysql_fetch_array($result);
echo "Health status was ".$row["HealthStatus"];
}
else
{
// do something
echo "There were no rows found";
}
To understand how much rows were received use mysql_num_rows function.
if(mysql_num_rows($result) > 0) {
} else {
}
Also, you have error in your if:
if($result = false)
{
//do something
}
else
{
//print value already exists
}
You assign false to $result in your if statement.
You have to use if($result == false).
To avoid such mistakes you can change order:
if(false == $result)
This will work, but this:
if(false = $result)
Will cause error.
Hope, this will help.

Categories