PDO - Fetch Assoc in a 'while' loop - php

I'm trying to echo a bit of html within a while loop. I'm getting my stuff with PDO and PDO_ASSOC.
This is what I have:
$stmt = $this->conn->prepare('SELECT * FROM books');
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$book_id = $row['id'];
$book_title = $row['title'];
$book_image = $row['image'];
$book_amz = $row['amazon'];
$book_desc = $row['description'];
$book_rating = $row['rating'];
$book_date = $row['date'];
$book_author = $row['author'];
$book_categorie = $row['categorie'];
$text = "ID: ' . $book_id . '";
}
return $text;
But it gives me only one row of the table. I even tried fetchAll, but it gives me nothing.

So making the assumption that the only element ever seen is the last element it is because what your are returning is being overwritten each loop. There are a few options to resolve this. The simplest is:
$stmt = $this->conn->prepare('SELECT * FROM books');
$stmt->execute();
$text = "";
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$book_id = $row['id'];
$book_title = $row['title'];
$book_image = $row['image'];
$book_amz = $row['amazon'];
$book_desc = $row['description'];
$book_rating = $row['rating'];
$book_date = $row['date'];
$book_author = $row['author'];
$book_categorie = $row['categorie'];
//String concatenation of text will
//give you one big string at the end to return.
$text .= "ID: '{$book_id}'";
}
return $text;
However this will not work well with your real bootstrap html. You need to make sure that the columns add up right.
You will need something a bit more intuitive
Using the actual code it would look something like
$stmt = $this->conn->prepare('SELECT * FROM books');
$stmt->execute();
$bookEcho = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$bookEcho[] = '<div class="col-md-3">
<div class="thumbnail">
<span>' . $book_title . '</span>
<img src="' . $book_image . '">
<div class="book-options">
<span>Bewertung</span><br/>
' . $stars . '
Jetzt lesen
</div>
</div>
</div>';
}
return $bookEcho;
Now in your function what ever it is you can do something like (this is not the most elegant thing I have ever written but should get the job done):
$cols = 4;
$colCount = 1;
foreach ($bookEcho as $book){
if($colCount == 0){//create a row}
echo $book;
$coolCount++;
if($colCount == 0){end a row}
if($colCount == 4){ $colCount = 0;}
}

The problem is that you're overwriting your values in your while loop. The loop is being executed once for each entry in the database, but only the last one will be returned. Instead you want to use arrays:
$stmt = $this->conn->prepare('SELECT * FROM books');
$stmt->execute();
$books = [];
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$book['id'] = $row['id'];
$book['title'] = $row['title'];
$book['image'] = $row['image'];
$book['amz'] = $row['amazon'];
$book['desc'] = $row['description'];
$book['rating'] = $row['rating'];
$book['date'] = $row['date'];
$book['author'] = $row['author'];
$book['categorie'] = $row['categorie'];
$book['text'] = "ID: ' . {$book['id']} . '"; // << Not sure if this is what you actually want. If not, adjust accordingly.
// Append the above values to the $books array
$books[] = $book;
}
return $books;

Use a foreach:
$books = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($books as $book){
$book_id = $book['id'];
$book_title = $book['title'];
// ...
}

Related

fetch_assoc not returning all columns data from mysqli

I have the following code and i get the data for columns except the flag_images and flag_created.
the rows flag_images contain integer 0 but when i try to echo them i get noting.
what might be the issue?
please help
$product = [];
$row_count++;
// echo "\r\n [".$row_count."] " . $data[0] . " <=======\r\n";
$amazon_db = sprintf("select `ratings`,`manufacturer`,`reviews`,`old_price`,`stock`,`asin`,`product_name`,`price`,`description`,`zap_price`,`product_link`,`shipping_o_price`,`images`,`flag_images`,`flag_created` from `amazon-crawler` WHERE `asin` ='%s' limit 0,1", $data[0]);
$amazon_result = $amazon_conn->query($amazon_db);
if (#$amazon_result->num_rows > 0) {
while ($row = $amazon_result->fetch_assoc()) {
$product['asin'] = $row['asin'];
$product['manufacturer'] = $row['manufacturer'];
$product['price'] = $row['price'];
$product['zap_link_price'] = $row['zap_price'];
$product['product_link'] = $row['product_link'];
$product['shipping_o_price'] = $row['shipping_o_price'];
$product['images'] = $row['images'];
**$product['flag_images'] = $row['flag_images'];
$product['flag_created'] = $row['flag_created'];**
echo $product['flag_created'];
echo $product['flag_images'];
$product['stock'] = $row['stock'];
$product['amazon_ratings'] = $row['ratings'];

php pdo loop through row skips 1st row

I am looping my rows from my database and it works except one thing. it skips the 1st id.
it begins from the second record. any idea how to fix this?
this is my code:
<?php
$query = $PDO->prepare('SELECT * FROM pokes');
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC)
?>
<?php
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$n = $row['name'];
$cp = $row['cp'];
echo $id . ' ' . $n . ' ' . $cp . '<br>';
}
?>
<?php
// your first error is here. You are fetching the first row
$row = $query->fetch(PDO::FETCH_ASSOC)
// And here you start from the second, since you already did ones above
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
//...rest of oyur code
}
?>
you have two way to accomplish your task
<?php
// Just add the PDO::FETCH_ASSOC constant while you are looping
while($row = $query->fetch(PDO::FETCH_ASSOC)){
//...Code here
}
// another way is adding the constant before using it
$query->setFetchMode(PDO::FETCH_ASSOC);
while($row = $query->fetch()){
//...Code here
}
?>
Remove
$row = $query->fetch(PDO::FETCH_ASSOC) after $query->execute();
just keep the while($row = $query->fetch(PDO::FETCH_ASSOC)) statement.
Your code should be like this:
<?php
$query = $PDO->prepare('SELECT * FROM pokes');
$query->execute();
?>
<?php
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$id = $row['id'];
$n = $row['name'];
$cp = $row['cp'];
echo $id . ' ' . $n . ' ' . $cp . '<br>';
}
?>
Don't fetch twice for a query.
<?php
$query = $PDO->prepare('SELECT * FROM pokes');
$query->execute();
foreach ($query as $row) {
$id = $row['id']; $n = $row['name']; $cp = $row['cp'];
echo $id . ' ' . $n . ' ' . $cp . '<br>';
}
?>

php mysqli not returning value

Here is the code that is giving me a problem:
$letter = $_POST['artistButton'];
$result = $mysqli->query("SELECT * FROM `Generic` WHERE `songName` LIKE '$letter%'");
$row = $result->fetch_array();
while ($row = $result->fetch_array()) {
$Artist = $row['Artist'];
$songName = $row['songName'];
$Duration = $row['Duration'];
$URL = $row['URL'];
$Genre = $row['Genre'];
echo "<input type='submit' value='$songName' name='artistButton'>";
echo "<br />";
}
The statement is correct I saved it to a variable and printed it to the screen, then ran it from the database and it printed the results I wanted so it definitively is not that. For some reason though it is not displaying. I am guessing it has something to do with something I messed up converting from mysql to mysqli. Thanks -Sam
Clearly some codes are cut, but try to remove that extra:
$row = $result->fetch_array();
And use:
while($row = $result->fetch_assoc()) {
Since you're interested on associative indices anyway.
Important note: Since you're using mysqli_*, use its parameterized queries instead. Don't directly use $_POST values on the query.
$letter = "{$_POST[artistButton]}%";
$stmt = $mysqli->prepare('SELECT * FROM `Generic` WHERE `songName` LIKE ?');
$stmt->bind_param('s', $letter);
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$Artist = $row['Artist'];
$songName = $row['songName'];
$Duration = $row['Duration'];
$URL = $row['URL'];
$Genre = $row['Genre'];
echo "<input type='submit' value='$songName' name='artistButton'>";
echo "<br />";
}

PHP foreach and after that while loop

I currently have a query which fetches data and then runs another query. I then echo out the results of the second query. What I would like to do is to move the echo outside of the foreach loop please but I don't know how to do that.
$ids = 2,3;
$id = explode(",",$ids);
$barcode = array();
foreach($id as $value) {
$sql_query = $db->prepare("SELECT barcode FROM product WHERE id=:value");
$sql_query->bindParam(":value", $value);
$sql_query->execute();
$row = $sql_query->fetch(PDO::FETCH_ASSOC);
$barcode = $row['barcode'];
/* I want to move this part starting from here outside the foreach */
$sql_select_all = $db->prepare("SELECT * FROM inventory WHERE barcode=:barcode");
$sql_select_all->bindParam(":barcode", $barcode);
$sql_select_all->execute();
while($row = $sql_select_all->(PDO::FETCH_ASSOC)){
$name = $row['name'];
$img = $row['image'];
$desc = $row['desc'];
echo $name.$img.$desc;
}
/* ending here */
}
How can I move the echo line out of the foreach loop?
try
foreach($id as $value){
$sql_query = $db->prepare("SELECT barcode FROM product WHERE id=:value");
$sql_query->bindParam(":value", $value);
$sql_query->execute();
$row = $sql_query->fetch(PDO::FETCH_ASSOC);
// make array with the entry
$barcode[] = '"'.$row['barcode'].'"';
}
// after foreach we explode the array and add comma ,
$barcode = explode(',',$barcode)
// using mysql ( [IN][1] ) query instead of ( = )
$sql_select_all = $db->prepare("SELECT * FROM inventory WHERE barcode in ($barcode)'");
$sql_select_all->bindParam(":barcode", $barcode);
$sql_select_all->execute();
while($row = $sql_select_all->(PDO::FETCH_ASSOC)){
$name = $row['name'];
$img = $row['image'];
$desc = $row['desc'];
echo $name.$img.$desc;
using IN() Function
What you need to do is store the results of your second query into an array. Then you can move the echo out of the for loop and run a loop on your new array like this:
$ids = 2,3;
$id = explode(",",$ids);
$barcode = $results = array();
foreach($id as $value){
$sql_query = $db->prepare("SELECT barcode FROM product WHERE id=:value");
$sql_query->bindParam(":value", $value);
$sql_query->execute();
$row = $sql_query->fetch(PDO::FETCH_ASSOC);
$barcode = $row['barcode'];
/*i want to move this part starting from here outside the foreach*/
$sql_select_all = $db->prepare("SELECT * FROM inventory WHERE barcode=:barcode");
$sql_select_all->bindParam(":barcode", $barcode);
$sql_select_all->execute();
while($row = $sql_select_all->(PDO::FETCH_ASSOC)){
$results[] = $row;
//$name = $row['name'];
//$img = $row['image'];
//$desc = $row['desc'];
//echo $name.$img.$desc;
}
/*ending here*/
foreach($results as $row) {
echo $row['name'] . $row['image'] . $row['desc'];
}
}

PHP Iterate through a MySQL result a certain amount of times

At the moment I have this code looping through the whole results of a query:
$result = mysqli_query($con, $sql);
$data = array();
while($row = mysqli_fetch_array($result)) {
$name = $row ['name'];
$desc = $row ['description'];
$cat = $row ['category'];
$price = $row ['price'];
$quantity = $row ['quantity'];
$id = $row ['productID'];
$image = $row ['image'];
$arr = array();
$arr ["id"] = $id;
$arr ["name"] = $name;
$arr ["desc"] = $desc;
$arr ["cat"] = $cat;
$arr ["price"] = $price;
$arr ["quantity"] = $quantity;
$arr ["image"] = $image;
array_push($data, $arr);
}
echo json_encode($data);
I want to change this to only loop through a set amount of results. I have a variable further up the code called $amount which is the amount of results I would like.
I hear I should use mysql_result() and a for loop to count to $amount, but I'm not sure how my existing code will work with that set up! Suggestions please.
EDIT:
#Styphon Pointed out that I don't actually need to change my iteration code for this to be solved. Just needed to add a LIMIT to my SQL query.
$sql = "rest of query...
LIMIT $amount"; //This will limit it to whatever is $amount. Just make sure to have it on the end of your query.
$result = mysqli_query($con, $sql);
$data = array();
while($row = mysqli_fetch_array($result)) {
$arr = array();
$arr["id"] = $row['productID'];
$arr["name"] = $row['name'];
$arr["desc"] = $row['description'];
$arr["cat"] = $row['category'];
$arr["price"] = $row['price'];
$arr["quantity"] = $row['quantity'];
$arr["image"] = $row['image'];
array_push($data, $arr);
}
echo json_encode($data);
Solution is the same whether you use mysql_ or mysqli_ (but you should use mysqli or even pdo). It goes something along this lines:
$num = 0;
$amount = 10;
while ($f = mysql_fetch_array($q)) {
// your code;
$num++;
if ($num==$amount) break;
}
As you mentioned for loops, with for loop you might do something like this
for ($i=0;$i<$amount;$i++) {
$f = mysql_fetch_array($q);
//your code
}
Obviously you should adjust it to suit your needs.
SELECT * FROM tbl
LIMIT 0, $amount
This will limit your result to $amount.

Categories