Checking result/count before outputting while loop - php

I'm looking for a way to SELECT from database, then check the result, and then output rows in a while loop (IF the result was above zero)
I really want to avoid using a separate count query
Right now I use this:
$sql = 'SELECT id, username, usercity, usercountry FROM siteusers WHERE userage > 50';
$STH = $conn->query($sql);
$arr = $STH->fetchAll();
if (count($arr) > 0) {
echo '<div id="users">';
foreach ($arr as $row) {
echo '<h1>'.$row['username'].</h1>';
}
echo '</div>';
}
It works. But isn't there a way I can check result/numrows and loop the rows, without using fetchAll and custom for-each loop?
Or does it not matter at all? (is for-each just as good as while loop?)
If I do it like this, the first row is not included in the while loop:
$sql = 'SELECT id, username, usercity, usercountry FROM siteusers WHERE userage > 50';
$STH = $conn->query($sql);
if ($row = $STH->fetch()) {
echo '<div id="users">';
while ($row = $STH->fetch()) {
echo '<h1>'.$row['username'].</h1>';
}
echo '</div>';
}
EDIT: I DO need to check the result, for dynamic layout purposes

You can use the PDO method rowCount to verify before your foreach if there are rows
$STH = $conn->query($sql);
if ($STH->rowCount())
{echo '<div id="users">';
foreach ($STH->fetchAll() as $row)
{
echo '<h1>'.$row['username'].'</h1>';
}
echo '</div>';
}
http://php.net/manual/en/pdostatement.rowcount.php
note that this uses up a lot of memory as all your results are loaded at once in memory with fetchAll(). if you have very large result sets, consider using a while instead of the foreach
while ($row = $STH->fetch())
{// foo with $row
}

$row is being set to the first row of your results inside of your if statement. This means that your while loop will start at the second row.
$sql = 'SELECT id, username, usercity, usercountry FROM siteusers WHERE userage > 50';
$STH = $conn->query($sql);
echo '<div id="users">';
while ($row = $STH->fetch()) {
echo '<h1>'.$row['username'].</h1>';
}
echo '</div>';
The while loop will run if there is any results to fetch, and if there aren't, then respectively it won't run.

Related

How to get all rows from myslq table by foreach loop in php pdo

I am trying to collect all rows from a table of mySql database. But I am getting 1 row lesser than the original rows. Suppose the table has 3 rows but I am getting data of 2 rows. I am missing the first one always. Here is the image of my table.
Here is my code:
$query = $db->query("SELECT * FROM `POS_refund`");
if($query->fetchColumn() > 0){
foreach($query as $row){
echo $get_prod_id = $row['prod_id'];
$get_prod_qnt = $row['qnt'];
}
}
Where is the fault?
PDOStatement::fetchColumn Returns a single column from the next row of a result set
You should use fetch() or fetchall() in your case
<?php
$query = $db->query("SELECT * FROM `POS_refund`")->fetchall();
foreach($query as $row){
echo $get_prod_id = $row['prod_id'];
$get_prod_qnt = $row['qnt'];
}
?>
If you want to see if there's records returned you could use count() since fetchall() returns array, then just count your array elemenets
<?php
$query = $db->query("SELECT * FROM `POS_refund`");
$results = $query->fetchall();
if(count($results) > 0){
foreach($results as $row){
echo $get_prod_id = $row['prod_id'];
$get_prod_qnt = $row['qnt'];
}
}else{
echo "No results";
}
?>
I would use a while loop. it would look like this:
while ($row = $query->fetchall) {
echo $get_prod_id = $row['prod_id'];
$get_prod_qnt = $row['qnt'];
}

Every X result different while fetch from mysql database

I have simple php foreach loop which fetch some data from MySQL database
$result = $pdo->prepare( "SELECT * FROM table ORDER BY RAND() LIMIT 30");
$result->execute();
foreach ($result as $row)
{
echo 'data';
}
As you can see there is LIMIT 30. Is it possible to to insert different data on every 10th result.Data which is not from database. It's static data and wont be changeable. What I mean is something like
if ( $row=10 )
{
echo $row['name'];
}
else
{
echo '<div> some static text not from database </div>';
}
$counter=0;
foreach ($result as $row)
{
$counter++;
if($counter %10==0){} //10th result
else{} //not 10th result
}
$counter = 0; //This is the counter which we will use to count row numbers.
$result = $pdo->prepare( "SELECT * FROM table ORDER BY RAND() LIMIT 30");
$result->execute();
foreach ($result as $row)
{
$counter++; //We are incrementing the counter.
echo $row['name'];
//If we are at a row which is multiple of 10, we output a static value.
if($counter % 10 == 0)
echo 'Hello World!';
}

Getting number of rows form SQL Server table

I have a problem with getting the right value after I counted the rows from a table. I searched on the web but didn't find an answer.
In the database i have a table with all the categories in it they all have an id, and i would like to count using this column.
I have this PHP code, it works but is there an other and better to get over this?
$sql2 = "SELECT COUNT(id) FROM categories";
$stmt2 = sqlsrv_query($conn, $sql2);
$res = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC);
foreach($res as $row)
{
$rows = $row;
}
//if there are categories display them otherwise don't
if ($rows > 0)
{
$sql = "SELECT * FROM categories";
$stmt = sqlsrv_query($conn, $sql);
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo "<a href='#' class='cat_links'>" . $row['category_name'] . " - <font size='-1'>" . $row['category_description'] . "</font></a>";
}
}
else
{
echo "<p style='text-align: center'>No categories yet.</p>";
}
I think has to be a better way to convert the $stmt2 variable from a SQL resource to an actual number, or to convert the $res variable from an array to an number. If I try to echo the whole array using foreach, it will only print out the number of rows. This is why I use it to count the rows now.
I can't use the sqlsrv_num_rows function because I then get an error, or no answer.

PHP MySQL How to skip displaying a field

I have the table MYTABLE that contains the fields: ID, PASSWORD, COL1, COL2, COL3, DATE
I would like to fetch and display all records in an html table but skipping ID and PASSWORD fields...
I'm using the following code which isn't working:
$query = "SELECT * FROM MYTABLE WHERE 1";
$results = mysql_query($query, $conn) or die(mysql_error());
echo "<tr>";
while ($r = mysql_fetch_assoc($results)) {
foreach ($r as $item) {
// let's not display ID and password
if ($r == 'ID' || $r == 'PASSWORD') continue; // this is the line that I want to figure out
echo "<td>$item</td>";
} // end for loop
} // end while
unset($item);
echo "</tr>";
Obviously there's more than 1 way to do it, for example I can replace the foreach loop with a for loop:
for ($i=0;$i<=6;$i++) {
if ($i == 0 || $i == 1 ) continue;
echo "<td>$r[$i]</td>";
} // end for
This will skip ID and PASSWORD fields but I don't want to use it, because I'm running the code on more than one table (table name is fetched from html select tag) and these tables may not have the same number of fields/columns (but they will always have ID and PASSWORD).
I can also do it with SQL statement (I don't want to), but then I'll have to query into a temp, drop the ID,PASSWORD columns and then fetch from the temp table. (by the way is there a compelling reason as to why I SHOULD in fact do it with SQL rathen than PHP?)
foreach ($r as $k => $item) {
// let's not display ID and password
if ($k == 'ID' || $k == 'PASSWORD') continue;
echo "<td>$item</td>";
}
This meets exactly your request.
I hope this result now useful to you, and after that, you evolve from it.
I would suggest you do it this way:
$query = "SELECT COL1, COL2, COL3, DATE FROM MYTABLE WHERE 1";
Try this:
$query = "SELECT * FROM MYTABLE WHERE 1";
$results = mysql_query($query, $conn) or die(mysql_error());
echo "<tr>";
while ($r = mysql_fetch_assoc($results)) {
foreach ($r as $key => $item) {
// let's not display ID and password
if (!in_array($key, array('PASSWORD', 'ID'))) {
echo "<td>$item</td>";
}
} // end for loop
} // end while
echo "</tr>";
Let it easy..
<?php
$query = "SELECT COL1, COL2, COL3, DATE FROM MYTABLE WHERE ..whatever..";
$result = mysql_query($query);
if ($result) {
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>".$row["COL1"]."</td>";
echo "<td>".$row["COL2"]."</td>";
echo "<td>".$row["COL3"]."</td>";
echo "<td>".$row["DATA"]."</td>";
echo "<tr>";
}
}
?>

PHP Fetch data twice

My function looks like that.
private function generateTree($courseID) {
$q = "SELECT l.id, l.name AS lesson_name, c.name AS course_name FROM lessons AS l, courses AS c WHERE l.course_id=c.id AND c.id=?";
$stmt = $this->db->prepare($q);
$stmt->bind_param("i", $courseID);
$stmt->execute();
$stmt->store_result();
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $lName, $cName);
echo "<li> <a href='#'>$cName</a> <ul>";
while ($stmt->fetch()) <====HERE!!!
echo "<li> <a href='?course=$courseID&lesson=$id'> $lName </a></li>";
echo "</ul> </li>";
}
}
The problem is that I'm starting to fetch data inside a while condition, but I need it before the while, too. Can I fetch data twice? Any other suggestions?
It's been four years, but in case someone stumble upon this question like I did:
while ($stmt->fetch()) {
// do your thing
}
$stmt->data_seek(0);
while ($stmt->fetch()) {
// do something other
}
You can read documentation here
You can use fetchAll() to fetch all the data and iterate over it as many times as you want.
$result = $stmt->fetchAll(); // PDO
$result = $stmt->fetch_all(); // MySQLi
foreach($result as $row) { print $row['lesson_name']; }
foreach($result as $row) { print $row['lesson_name']; }
foreach($result as $row) { print $row['lesson_name']; }
etc...
Update: I'm not entirely sure what you are doing as you seem to have several ideas mixed into your code. Perhaps you want something like this?
$q = "SELECT l.id, l.name AS lesson_name, c.name AS course_name FROM lessons AS l, courses AS c WHERE l.course_id=c.id AND c.id=?";
$stmt = $this->db->prepare($q);
$stmt->bind_param("i", $courseID);
$stmt->execute();
if ($stmt->num_rows > 0)
{
$results = $stmt->fetch_all();
foreach($results as $row)
{
print_r($row);
}
}
I think you can make your database query class in a way that it returns an array of database result. You can use data as many times you want.
You can make an array of the database-resultset like this:
while($row = mysql_fetch_assoc($result))
{
$results[] = $row;
}

Categories