PHP output contains two spaces even no results found - php

I use below php code to send results of MYSQL databse search to AJAX requests...
$query = $db->query("SELECT name FROM search WHERE qurl = '" . $queryString . "'");
if($query) {
while ($result = $query ->fetch_object()) {
echo $result->name;
}
} else { echo 'no results found'; }
but I never get no results found message even there is no results, all I get if there is no result, two empty spaces - I found that using alert(data.length) in AJAX page, result was 2 which means php output has two empty spaces when there is no results...
but when there are results it works fine...
any way of removing these two spaces or why Im not getting no results found message?

if ($query->num_rows > 0) {
while ...
} else {
echo 'no results found';
}
$db->query() only returns false if there was an error performing the query. An empty result set is not an error.

What you are evaluating is if the statement is valid... which it is, and will always return true. To evaluate the results returned, you'll need to evaluate $query->num_rows

Related

PHP number of results from Oracle query

I am doing a select in my Oracle database and need to take different actions for the result being false (contains no results) or being true (contains one or more results).
However testing the result in the following way gives me a problem. In the cases where I actually have results from my query the if(! naturally validates to false and moves on to the else statement - perfect!
But when doing this test the internal pointer moves in the result and thereby the first result is lost when performing the while statement later.
if (!($row = oci_fetch_array($get_doc_paths, OCI_ASSOC+OCI_RETURN_NULLS))){
do something
}
else {
while ($row = oci_fetch_array($get_doc_paths, OCI_ASSOC+OCI_RETURN_NULLS)){
do something with $row
}
}
How do I test if there are results without moving the internal pointer?
In MySQL I would have used the mysqli_num_rows or simply just reset the pointer. I can't find a way to do this with Oracle.
$status = false;
while($row = oci_fetch_array(...)) {
$status = true;
// Do something with row
}
if(!$status) {
// Do something else
}

Deceptively Simple: Check If Data Is Returned From MySQL In One Query

Here is a simple scenario I am contemplating. I have a query that is executed on a MySQL database from PHP. I would like to check if any data was returned from the query. However, in order to perform that check, it pulls out one of the rows of returned data.
Look at this example, and its comments:
$booksGrabber = ("SELECT * FROM table");
if (!$booksGrabber) {
//Query failed, perhaps a syntax error
exit;
}
if (!mysql_result($booksGrabber, 0)) {
//No data was returned :(
exit;
}
while ($book = mysql_fetch_assoc($booksGrabber)) {
//mysql_result() stole the first row of returned data
//So if I was expecting the loop to display 4 results,
//I only get 3...
}
How can I check if data was returned from the database without running two queries (one to check, the other to display all of the data) or having one of the rows stolen?
Use mysql_num_rows. It was as simple as it looked.
EDIT: If you want more complicated, add mysql_data_seek($booksGrabber,0).
Simple: mysql_query() function that runs the query will return false on error and then you can use mysql_num_rows() for the count. So you can do something like:
$result = mysql_query('SELECT * FROM table');
if (!$result) {
print('Invalid query: ' . mysql_error());
} elseif (mysql_num_rows() == 0) {
print("no results");
} else {
// You can use safely data from the query :)
}

Getting data from MySQL through PHP - am I doing it right?

Simple question I guess, but a fundamental one and I'm not sure of the best practice.
So let's say that I have a database with some IP addresses that I want to display to the user.
Is this a good/secure way/practice?
//--> CONNECT TO DB, etc
$db_query = 'SELECT ip,'
."FROM table "
."GROUP BY ip ";
$result = $db_conn->query($db_query);
echo 'Found '.$result->num_rows.' records';
if($result->num_rows > 0) {
while($row = $result->fetch_array(MYSQLI_BOTH))
{
//POPULATE A HTML TABLE/WHATEVER WITH THE INFO
}
}
I'm mostly concerned about this: $result->num_rows > 0 and this: fetch_array(MYSQLI_BOTH)
I'm asking because I read somewhere that num_rows > 0 can usually mean trouble depending on the situation, for example a user login. In that case I suppose it would num_rows == 1 right?
And also, I haven't fully understood the difference between MYSQLI_BOTH and other forms of fetching.. If you could simple explain them to me and when to use them I would be grateful.
What do you think?
I would add a check to ensure your query was executed OK - and if not output the error :
$result = $db_conn->query($db_query);
// check for error - output the error
if (!$result) {
$message = 'Invalid query: ' . mysqli_error() . "\n";
$message .= 'Whole query: ' . $db_query;
die($message);
}
echo 'Found '.$result->num_rows.' records';
Other than that ... looks OK
EDIT:
To explain MYSQLI_BOTH, the options are MYSQLI_ASSOC, MYSQLI_NUM, or MYSQLI_BOTH ->
MYSQLI_ASSOC = Associative array so the value of the rows can be accessed using $row['column']
MYSQLI_NUM = Numeric array so the values of the rows are accessed using a number $row[n] where n is the number of the column (0 based)
MYSQLI_BOTH = can use both to access values of row either $row[n] or $row['column']
EDIT2:
There is also a function for checking the number of returned rows :
if(mysqli_num_rows($result) == 0){
echo "Sorry. No records found in the database";
}
else {
// loop you results or whatever you want to do
}
EDIT3:
php.net has some excellent docs for the MY_SQLI extension
Two things:
If you only need an associative array, then don't use fetch_array(). Use fetch_assoc().
There's no need to concatenate the query like that, you could use something like:
$sql = "
SELECT
ip
FROM
table
";
This helps with large queries with multiple options in the WHERE clause or JOINs. It's quicker to type out, and you can quickly copy and paste it for checking in phpMyAdmin and the like.

PHP/MySQL: What is returned when no matches are found?

I want to use PHP to find out if no matches are found. I tried the following, but "is_resource()" always returns true.
$result = mysql_query('...');
if(is_resource($result)){
// Results are found
}
mysql_num_rows() will do the trick.
if (mysql_num_rows($result)>0) {
//Results are found
}
http://php.net/manual/en/function.mysql-num-rows.php
So $result will always be a resource as long as you have proper access to the database. And mysql_num_rows() assumes that the query itself ran successfully. I'd say try something like this:
if($result === FALSE) // Query failed due to not having proper permissions on the table
die('Invalid query: ' . mysql_error());
else if(mysql_num_rows($result) >0)) // We have more than 1 row returned which means we have data
// INPUT RESULTS PROCESSING HERE
else // No rows were returned therefore there were no matches
echo 'No rows returned';
Hope that helps a little =)
Look here for more information if you need: http://www.php.net/manual/en/function.mysql-query.php
This is what you want: mysql_num_rows()
If the query fails it mysql_query will return false so you can check your code like this:
if ( $stmt = mysql_query("...") )
{
// Do some things
}
else
{
// Do some other things
}
Or you could use mysql_num_rows like the people above have stated.
But you should really be looking into MySQLi it's a built in database class. Learn it and use it. Your life will be so much easier.

PHP non eof-recordset returning empty values

i'm having a strange problem with php + recordsets.
my code:
$rc = mysql_query("select * from myTable",$db);
if (!$row = mysql_fetch_assoc($rc))
{
$eof=true;
}else{
echo "there is data!<br>";
$rs = mysql_fetch_array($rc);
echo $rs[id];
echo $rs[txt];
}
the strange thing - the query is correct - it's echoing "there is data" but when echoing the actual field values returns empty strings .. :(
any ideas what could be wrong?
In your else block, you are re-fetching some data from the database, using mysql_fetch_array().
But a first row has already been fetched earlier, by mysql_fetch_assoc().
So, basically :
In the if's condition, you are fetching a first row
If it succeed, you enter the else block
where you try to fetch a second row
and using the returned (or not) data, without testing the success of that second fetch.
You should probably do only one fetch -- using either mysql_fetch_assoc or mysql_fetch_array -- but not two.
you already fetched data, use mysql_num_rows() instead
$rc = mysql_query("select * from myTable",$db);
if (mysql_num_rows($rc))
{
echo "there is data!<br>";
$rs = mysql_fetch_array($rc);
echo $rs[id];
echo $rs[txt];
}else{
$eof=true;
}
Be consistent in your use of if mysql_fetch_assoc($rc)...
$rs = mysql_fetch_array($rc);
will return an enumerated array, so $rs['id'] doesn't exist only $rs[0], $rs[1], etc.
Use
$rs = mysql_fetch_assoc($rc);
to return an associative array with $rs['id']
Your first test also fetches and discards a row
And quote the indexes in $rs: $rs['id'] rather than $rs[id]

Categories