how to query once and display multiple times with where clause? - php

I want to learn how to query once and display in multiple boxes with
where clause?
like :
if status 1 ? : display in <div class="1"> elseif status 2 ?: <div class="2"> etc. etc.
I know my answer is in my question and I need to do if statements, but I dont know how to display while loop or foreach a few times with same query.
Here is my query :
$stmt = $pdo->prepare("SELECT * FROM categories");
$stmt->execute();
while($row = $stmt->fetch()){
}
I have searched on google got a few examples like this with for loop but I didnt find any examples with where claus.
$i;
$stmt = $pdo->prepare("SELECT * FROM categories");
$stmt->execute();
while($row = $stmt->fetch()){
}
for($i=0; $i<5; $i++){
}
I tried if statment without foreach loop :
if($status == 1){
foreach(){
echo "Display box 1";
}
}
if($status == 2){
foreach(){
echo "Display box 2";
}
}
Displaying only one post need while loop or foreach to display all posts with status 1
Thanks

While you could buffer multiple streams, read the entire dataset into a PHP array and search it or run multiple queries, all are unnecessary and inefficient. Just sort the query. Consider:
$stmt = $pdo->prepare("SELECT * FROM categories ORDER BY status");
$stmt->execute();
$prevstatus=-1;
print "<div style='display:none'>";
while($row = $stmt->fetch()){
if ($row['status']!=$prevstatus) {
$prevstatus=$row['status'];
print "</div><div class='$prevstatus'>";
}
print ....
}
print "</div>";

I don't know if I understand your question but:
$stmt = $pdo->prepare("SELECT * FROM articles");
$stmt->execute();
while($row = $stmt->fetch()){
echo "<div class=\"class_". $row["status"] ."\">div content</div>\n";
}
And - CSS classes can not begin with numbers or have only numbers as a name! In my example I use .class_x (where X is your value from database)

Related

How to echo rows values in php?

I am trying to echo values of each row.
I tried this... while ($row = mysqli_fetch_assoc) {...}
but it prints the last value of row each time in a specific part of the loop.
Also, I created an array an I assigned the values in the while loop but it didn't work.
Can you please help me?
$query= mysqli_query($con, "SELECT * FROM db WHERE user='$user' AND deleted='no' ORDER BY id DESC LIMIT 6");
while ($row = mysqli_fetch_assoc($query)) {
$link="index.php?id=". $row['id']; //wrong value
if ($row["user"] == 'User 1') {
$id=$row['id'];
$tags=$row['tags'];
$token = strtok($tags, ",");
echo "<div class='thisdiv'>
<a href='../games/avery/index.php?id=$id'><img src='../images/games/Preview.png ' ></a><br><p class='font-size-bold'>Tags</p>"; //correct $id
SQL Inject is allowed with your code, use statament for exclude this possible:
$query= $con->prepare("SELECT * FROM db WHERE user=? AND deleted=? ORDER BY id DESC LIMIT 6");
$no='no';
$query->bind_param('ss',$user,$no);
$query->execute();
$result=$query->get_result();
while ($row = $result->fetch_assoc()) {
if ($row["user"] == 'User 1') {
$id=$row['id'];
$tags=$row['tags'];
$token = strtok($tags, ",");
echo "<div class='thisdiv'><a href='../games/avery/index.php?id=$id'><img src='../images/games/Preview.png ' ></a><br><p class='font-size-bold'>Tags</p>"; //correct $id
}
}
Your code is quite limited but will try to break it down for you.
So first things first your query is working. And you get the 6 last results from your table since you order in DESC and LIMIT to 6
You while loop also loops around your fetched results. So your issue is more logical.
The 1st iteration of your while will set value to variable $link like:
$link="index.php?id=". $row['id'];
This will always be executed on every iteration (6 times) and actually your variable will be overwritten, so at the last iteration $link is going to have the id of the last element.
In your code after that you have a check:
if ($row["user"] == 'User 1') {
$id=$row['id'];
$tags=$row['tags'];
$token = strtok($tags, ",");
echo "<a href='../games/avery/index.php?id=$id'><img src='../images/games/Preview.png ' ></a><br><p class='font-size-bold'>Tags</p>";
} // mind the closing bracket, you echo your validated value
That's where i think you are getting it wrong. This echo should be inside your if check but also your variable link should be in there.

Prepared Statement, Fails when re-used

I have this code, works fine when looped through once.
<!-- language: php -->
<?php
$query = "SELECT username FROM users WHERE user_id = ? LIMIT 1";
$stmt = $con->prepare($query) or die(mysqli_error($con));
$stmt->bind_param("s", $user_id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($username);
?>
When I call it for the first time on the page, it loads fine and the data shows as it should.
<!-- language: php -->
<?php
// This one works fine.
while ($stmt->fetch()){
echo 'Welcome '.$username;
}
?>
If I want to re-use the same query somewhere else, it fails wihtout errors. Am I doing it wrong? What is the correct way to re-use the same query multiple time on the same page, Since the data is the same, I don't want to re-query the DB each time.
<!-- language: php -->
<?php
// When re-used somewhere else on the page, it fails. Nothing shows.
while ($stmt->fetch()){
echo 'Welcome '.$username;
}
?>
fetch returns one row after another. Once you fetch all rows, any further call to fetch() method will return false.
You need to re-execute() the query in order to get the same result again. This will go to call database again though. If you want to cache the result, you need to put it into some in-memory cache / global variable / whatever you prefer.
If you really want to get to the beginning of result set again, you can use mysqli_data_seek() for this:
mysqli_data_seek($stmt, 0);
while ($stmt->fetch()){
echo 'Welcome '.$username;
}
You could pull the query result into an array with fetchAll
$users = $stmt->fetchAll();
// this works
foreach($users as $user) {
echo 'Welcome ' . $username;
}
// this works again
foreach($users as $user) {
echo 'Welcome ' . $username;
}
More information here: http://php.net/manual/fr/pdostatement.fetchall.php
What you can do is get the result-set as an ASSOC Array and save the result in a variable. Now you can use this array as many times as you want.
Update your code like this,
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$results = $stmt->fetchAll();
foreach ($results as $r) {
//first time use
}
foreach ($results as $r) {
//second time use
}
I needed to split up the code to achieve what I needed with MySQL(i).
Thanks for your inputs.
<?php
// Preparing the statement
$query = "SELECT username FROM users WHERE user_id = ? LIMIT 1";
$stmt = $con->prepare($query) or die(mysqli_error($con));
$stmt->bind_param("s", $user_id);
$stmt->store_result();
?>
<?php
// Executing it when needed and creating some variables for later re-use
$stmt->execute();
$stmt->bind_result($username);
while ($stmt->fetch()) {
$new_username = $username;
echo 'Welcome '.$new_username;
}
?>
<?php
// It is possible now to re-use the same result set
echo 'Welcome '.$new_username;
?>
You can store the results:
<?
$query = "SELECT username FROM users WHERE user_id = ? LIMIT 1";
$stmt = $con->prepare($query) or die(mysqli_error($con));
$stmt->bind_param("s", $user_id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($col['username']);
$result = array();
for ($i = 0; $i < $stmt->num_rows; $i++){
$stmt->data_seek($i);
$stmt->fetch();
foreach ($col as $key => $value){
$result[$i][$key] = $value;
}
}
?>

How to get all entries out of a table?

I'd like to build a ul by pull the content out of a SQL table. But this code does only gives me the first row. What would be the best solution to get all 10 entries?
$query = "SELECT * FROM `activitys`";
echo '<td><ul>';
if ($result = mysqli_query($link, $query)) {
$row = mysqli_fetch_array($result);
echo "<li>".$row['content']."</li>";
}
echo '<td><ul>';
You need to put it in a loop, like this:
while($row = mysqli_fetch_array($result)) {
echo "<li>".$row['content']."</li>";
}
Wrap it in a while loop. That way it will keep going until the end. An IF only runs once.

How to sum values stacked in different Rows? PHP PDO MYSQL

Let's say we have a very simple while row query script, for example:
<?php
include('conection.php');
$Verd = 'Verduras';
$smt = $con->prepare("select * from prodcts WHERE Type = :Verduras Order by PrdName ASC");
$smt->bindParam(':Verduras', $Verd, PDO::PARAM_STR);
$smt->execute();
while ($smr = $smt->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT))
{
echo '<th>'.nl2br($smr['PrdName']).'</th><th>'.nl2br($smr['SellType']).'</th><th>$'.nl2br($smr['Cost']).'</th>';
}
?>
Question:
How can i make than the results of the $smr['Cost'] Sum it up with the $smr['Cost'] of the rest/some others rows?
Any commentary, suggestion, question for improve the question or any kind of related answer looking to help & improve the question or result in the solution, etc would be much apreciated
Thanks in Advance!
PS: i check for another answers before, but mostly was mysql oriented, nevertheless i wanna check for a PHP more oriented solution, so to have more control about it and try to avoid (if possible) multiple querys.
Before you start the while loop, create a variable. In the while loop increase the variable by the value you want to add.
e.g:
$total = 0;
while ($smr = $smt->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT))
{
echo '<th>'.nl2br($smr['PrdName']).'</th>
<th>'.nl2br($smr['SellType']).'</th>
<th>$'.nl2br($smr['Cost']).'</th>';
$total += $smr['Cost'];
}
At the end, when you call $total, it will contain the sum.
<?php echo $total ?>
Hope it helps
If you need the sum of all rows, you can just create a variable before the while...
$Verd = 'Verduras';
$sum = 0;
$smt = $con->prepare("select * from prodcts WHERE Type = :Verduras Order by PrdName ASC");
$smt->bindParam(':Verduras', $Verd, PDO::PARAM_STR);
$smt->execute();
while ($smr = $smt->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT)) {
echo '<th>'.nl2br($smr['PrdName']).'</th><th>'.nl2br($smr['SellType']).'</th><th>$'.nl2br($smr['Cost']).'</th>';
$sum += $smr['Cost'];
}
echo $sum;
But if you need the value grouped $smr['PrdName'], just create a new array..
$Verd = 'Verduras';
$sum = 0;
$smt = $con->prepare("select * from prodcts WHERE Type = :Verduras Order by PrdName ASC");
$smt->bindParam(':Verduras', $Verd, PDO::PARAM_STR);
$smt->execute();
while ($smr = $smt->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_NEXT)) {
$prd[$smr['PrdName']][$smr['SellType']][0] += $smr['Cost'];
}
After that, you can display each line with a foreach...
It's easily to control using only SQL, but if you need to realize the treatment with PHP, i hope it helps.

How to fetch 2 times in MYSQL PDO without FETCHALL

I have this sample query:
$STH = $DBH->query("SELECT id FROM table");
I want to get the first row and then loop and display all rows. So I use the following to get the first row:
$STH->setFetchMode(PDO::FETCH_ASSOC);
$first_row = $STH->fetch();
$first_row = $first_row['id'];
I use while loop to display all rows again:
while ($list = $STH->fetch()) {
$id = $list['id'];
echo $id;
}
Now the while skips the first row and I want it to be displayed. Is there an equivalent to mysql_data_seek to reset the pointer again to the first row? I know fetchall can be used but it's bad on memory and wasteful. I could also run the query and limit to 1 but this is not recommended as I have a query that joins multiple tables and would be very slow. Is there any other solution?
Thanks
I take that back looks like you can use the cursor orientation contants to select the result... sample code coming... I havent tried this so you may need to play a bit. This is also based on the assumption that a PDO::FETCH_ORI_FIRST acts like a data_seek and leaves the cursor on the first position as opposed to returning it to whatever it was before.
$stmt = $pdo->prepare('SELECT id FROM table', array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$stmt->execute();
$first = $pdo->fetch(PDO::FETCH_ASSOC, PDO::FETCH_ORI_FIRST);
$first_row = $first['id'];
// other stuff
// first iteration we rewind to the first record;
$cursor = PDO::FETCH_ORI_FIRST;
while (false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC, $cursor))) {
$id = $row['id'];
// successive iterations we hit the "next" record
$cursor = PDO::FETCH_ORI_NEXT;
echo $id;
}
I dont think you can rewind a statement... Assuming these blocks arent seprated by a bunch of intermediary logic id just do it in the loop.
$STH->setFetchMode(PDO::FETCH_COLUMN); // no need to pull an array
$count = 0;
while ($id = $STH->fetch()) {
if($count === 0) {
$first_row = $id;
}
echo $id;
$count++;
}
Could you just use a do...while loop instead?
$STH->setFetchMode(PDO::FETCH_ASSOC);
$list = $STH->fetch();
$first_id = $list['id'];
do {
$id = $list['id'];
echo $id;
} while ($list = $STH->fetch());
You can fetch all the result, and then just act on it as an array. So, for instance, you could shift the first result off the front, and then loop over any additional rows:
<?php
$sql = "YOUR QUERY";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
// get first row
$firstRow = array_shift($rows);
// loop over remaining rows
foreach ($rows as $row) {
// do something
}

Categories