check while loop out put any data from query - php

$query=$db->prepare("SELECT *...
while($data=$query->fetch(PDO::FETCH_ASSOC)){...}
I have a query use while loop print out the data.
How can I check if while loop didn't fetch out any data(0 row from db), so I can print "0 result" on screen.
I don't want to make extra query for COUNT(*), is any way do check from while loop?

You have to use $sth = $query->execute() (and $sth->fetch() instead of $query->fetch() ) first, then $sth->rowCount will give you the number of results.

Just put a flag inside the loop to ensure you entered at least once.
Something like:
$flag = false;
$query=$db->prepare("SELECT *...");
while($data=$query->fetch(PDO::FETCH_ASSOC)){
$flag = true;
}
if ($flag) {} //entered
Added semicolon, thanks #Fred -ii

So you want to count the amount of results you get. In that case, you can just count a var up inside the loop:
while($data=$query->fetch(PDO::FETCH_ASSOC)){
$i++;
//your code here
}
If you want to check if you got no data, you can check $data:
while($data=$query->fetch(PDO::FETCH_ASSOC)){
if($data === false) {
echo "0 result";
}
}

Related

in_array Finding first Value Only

What I'm trying to do is to assign variables based upon a sql query.
The field "County" is a varchar containing the names of Counties.
$sql="SELECT County from GAINLP WHERE SpeciesName LIKE '%Actias_luna%'";
($result=mysqli_query($connect,$sql));
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
if (in_array("Porter", $row)) {
$Porter='Present';
}
else {$Porter='Not Present';
};
echo $Porter;
What happens is that in_array is only detecting the very first county in the array. If I echo $row, I get this:
OwenPikeParkeOwenOwenScottMorganGreeneHendricksLawrenceSt.JosephWashingtonVigoMorganOwenDuboisJeffersonSwitzerlandMadisonGreeneFayetteMarionOrangeParkeClarkJeffersonFayetteFountainMontgomeryHendricksHowardOwenElkhartMarionHendricksWashingtonTippecanoePutnamWashingtonBrownHendricksJenningsOwenWhitleyKosciuskoPorterVermillionHendricks
If I assign the needle as "Owen," echo $Porter returns "Present". All other values echo "Not Present." If I loop it, even "Owen" returns "Not Present" to $Porter. What am I doing wrong here?
This also does not work:
$sql="SELECT County from GAINLP WHERE SpeciesName LIKE '%Actias_luna%'";
($result=mysqli_query($connect,$sql));
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
if (in_array("Porter", $row)) {
$Porter='Found it';
}
else {$Porter='Didn\'t Find it';
}};
echo $Porter;
the line
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
will only retrieve the first row of the database.
If you want to check every row to see if ANY of them are Porter, then you will need to set the flag to a default of "no", loop your results, and set the flag if you find it:
$Porter="Not Present";
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
if($row['County'] == "Porter"){
$Porter = "Present";
}
}
echo $Porter;
(this is just a basic example; you can optimize it farther by breaking out of the loop when you first find the result for example, but this will do the job)
mysqli_fetch_array only fetches one row. Use while loop to go over all rows:
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
If you don't want to check per row but want to check if the value exists in any of the rows use mysqli_fetch_all:
$sql="SELECT County from GAINLP WHERE SpeciesName LIKE '%Actias_luna%'";
$result=mysqli_query($connect,$sql);
$rows=mysqli_fetch_all($result,MYSQLI_ASSOC);
if (in_array("Porter", $rows)) {
$Porter='Present';
} else {
$Porter='Not Present';
};
echo $Porter;

PHP/SQL can't use data from query after while loop

$sql = mysql_query("SELECT * FROM table WHERE user='$user'" );
while($data=mysql_fetch_array($sql)){
echo $data['user']; //this is fine
}
echo $data['user'];
$data=mysql_fetch_array($sql);
echo $data['user'];
The last two echos are empty?
I need to have an array outside of the loop that is equivalent to the 'last' loop cycle.
The while loop keeps fetching data, until there is no more data and therefore false is returned by mysql_fetch_array. This last value, false, is still in $data after the loop has ended, but simply printing it using echo, won't print anything you can see. The same goes for the next call of mysql_fetch_array and echo. You can check this by doing a var_dump of the $data variable. This will show you that it contains the boolean false.
If you want to be able to use the data after the loop has ended, you can save all the data you fetch into one big array. That might be a bad option though if you're fetching a lot of data, but from there you should be able to change it yourself so you can save and use the useful data. To store all the data in an array, change the loop into this:
$alldata = array();
while($data=mysql_fetch_array($sql))
{
echo $data['user'];
$alldata[] = $data;
}
You can then for example iterate over $alldata to go over the results again.
Update: In your last comment you said you want to access the last record that was fetched. You can do that like this:
$lastdata = array();
while($data=mysql_fetch_array($sql))
{
echo $data['user'];
$lastdata = $data;
}
$lastdata will then contain the last record in your result.
Because of the following:
while($data = mysql_fetch_array($sql)) {
// mysql_fetch_array returned something 'not false' and this value
// is assigned to $daat
}
// mysql_fetch_array() returned false, because there are no more rows
// false is assigned to $data, and because the statement within while(...)
// isn't true anymore the loop is stopped.
Use
$data = mysql_fetch_array($sql);
if (!$data) {
echo "User don't exists";
}
for example to handle this situation

while loop is not working upon selecting multiple colums from a table

i have a table with 5 columns like TABLE(a,b,c,d,e).
now i want to select all the columns from TABLE.but the script is not workling once the while loop starts.
my php code is:
include_once $_SERVER['DOCUMENT_ROOT'].'/include/db.inc.php' ;
$sql="select * from TABLE";
$result = mysqli_query($link,$sql );
if (!$result)
{
include_once "wall.html.php";
echo'<tr><td align="center"> OOOOPPPPPSSS!!!SORRY,UNABLE TO DISPLAY LATEST 25 TOPICS</td></tr>';
exit();
}
while ($row = mysqli_fetch_array($result))
{
$as[]=$row['a'];
$bs[]=$row['b'];
$cs[]=$row['c'];
$ds[]=$row['d'];
$es[]=$row['e'];
}
foreach($as as $x)
{
$name=$x;
}....................and so on
i have checked and debuged in many ways.what i noticed the script is not executing after while loop.
you forgot to write $ before variables:
$as[]=$row['a'];
^------------
bs[]=$row['b'];
cs[]=$row['c'];
ds[]=$row['d'];
es[]=$row['e'];
What about using array_push()? Also, use print_r() for $as[] and all the arrays you got and paste the output here so we get a clearer idea of what the issue exactly is.
Try this and tell what print_r() function is printing so that we can identify the problem.
while ($row = mysqli_fetch_array($result))
{
$as[]=$row['a'];
$bs[]=$row['b'];
$cs[]=$row['c'];
$ds[]=$row['d'];
$es[]=$row['e'];
}
print_r($as);
foreach($as as $x)
{
$name=$x;
}
First remove the brackets from $as[], the result of $row['a'] will not be an array.
And that's the reason the foreach is not working, you're not getting an array back.
If the resulting $as is empty, but there is something in your database, make sure the rownames are valid.
Use $row[0] instead of $row['A'].
Debug your code using print_r($row) to the see the contents of the results.

PHP How to compare each array value with my specified value?

Say for example this is my code:
$query = "SELECT * FROM ...";
$exec_query = mysql_query($query, $db_connect);
$fetchdetails = mysql_fetch_array($exec_query);
I am using an if condition like this:
if ($fetchdetails['field_name'] == 3) {
do something;
}
else {
}
But in this, only 1 row is compared from the fetchdetails array. What can I do to compare each row in that array with 3? I don't want any OOP's solutions, please, I want to stick with traditional coding. Thank you.
You should try this:
while($fetchdetails = mysql_fetch_array($exec_query)) {
if ($fetchdetails['field_name'] == 3) {
do something;
}
else {
}
}
That's because, with the while(...) condition, you'll iterate over all db (selected) records.
The loop will stop in an automatic way as soon as mysql_fetch_array finish record.
I'll remember you that mysql_fetch_array
Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows. (from manual)
and that will allow "you" to stop iteration process.
If you mean that you want to compare every row of the $fetchdetails array, then
foreach($fetchdetails as $index => $value) {
if($value == 3) {
// do something
}
}
Should do it! If you want to iterate over every SQL value, see the other answer.

Disappear the arrays generated with mysql_fetch_array() after use?

I have a typical database query:
$query = mysql_query('SELECT titulo,referencia FROM cursos WHERE tipo=1 AND estado=1');
and I can convert it in an array and print the data:
while ($results=mysql_fetch_array($query)): ?>
echo $results['referencia'];
// and so...
endwhile;
but in some cases I need to print the same data in another part of the web page, but the $results array seems to be empty (I use var_dump($results) and I get bool(false)). I plan to use what I learned reading Create PHP array from MySQL column, but not supposed to mysql_fetch_array() creates an array? So, what happen?
Tae, the reason that your $result is false at the end of the while loop is that mysql_fetch_array returns false when it reaches the end of the query set. (See the PHP Docs on the subject) When you reach the end of the query set $results is set to false and the while loop is exited. If you want to save the arrays (database row results) for later, then do as Chacha102 suggests and store each row as it is pulled from the database.
$data = array();
while($results = mysql_fetch_array($query)) {
$data[] = $results;
}
foreach ($data as $result_row) {
echo $result_row['referencia'];
... etc.
}
Try this
while($results = mysql_fetch_array($query))
{
$data[] = $results;
}
Now, all of your results are in $data, and you can do whatever you want from there.
As Anthony said, you might want to make sure that data is actually being retrieved from the query. Check if any results are being returned by echo mysql_num_rows($query). That should give you the number of rows you got

Categories