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!';
}
Related
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'];
}
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>";
}
}
?>
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.
How to display only one row at random at the same time from DB. Everything works fine, but all rows are displayed. thanks
<?php
$sql = "SELECT id,name FROM table ";
$rows = array();
$result = $objCon->query($sql);
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
shuffle($rows);
echo '<ol>';
foreach($rows as $row)
{
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
}
echo '</ol>';
?>
Change your SQL request:
SELECT id,name FROM table ORDER BY RAND() LIMIT 1;
You can do it using PHP:
....
shuffle($rows);
$randomRow = reset($rows);
....
But the better way is to change your SQL query:
$query = "SELECT id, name FROM table ORDER BY RAND() LIMIT 1;"
<?php
$sql = "
SELECT id, name
FROM table
ORDER BY RAND()
LIMIT 1 ";
$result = mysql_query($sql);
// As you are only return a single row you do you require the while()
$row = mysql_fetch_array($result);
echo '<ol>';
echo '<li><h3>'.$row['id'].' = '.$row['name'].'</h3></li>';
echo '</ol>';
?>
By adding an ORDER BY RAND() in your sql query you are asking MySQL to randomly order the results then at a LIMIT to restrict the number of rows you would like returned.
The example code is written based on selecting a single row. If you would like more, e.g. 5, you will need to add a while loop.
How can I use PHP to show five rows from a MySQL database, then create a new line and show another five, etc?
Use the LIMIT clause if you want to limit the amount of results returned from the query.
If you want to print an <hr/> after every fifth record you can check it via the modulus operator:
$counter = 1;
while ($row = mysql_fetch_assoc($rst)) {
// print $row stuff
if ($counter % 5 == 0)
print "<hr />";
$counter++;
}
Basically, we have a variable used to count how many records we've printed. Once that counter can be divided by five, and leave no remainder, we print our horizontal-rule.
Something like this may be helpful:
$result = mysql_query($query);
if($result) {
while($row = mysql_fetch_assoc($result)) {
if(++$i%5==0 && $i>0) {
/* do the extra thing... new line some styles */
}
}
}
Err.. you mean something like:
SELECT * FROM `tablename` WHERE ... LIMIT 5
$total = 20;//get total number here;
$limit = 5;
for($i = 0;$i< $total/$limit;$i++)
{
$sql = $result = $rows = "";
$start = $limit * $i;
$sql = "select * from m_table order by id desc limit $start,$limit";
$result = mysql_query($query);
while($rows = mysql_fetch_assoc($result))
{
//print the result here;
}
}
You can fetch 5 rows every time from mysql without fetching all the rows at once.