PHP foreach and after that while loop - php

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'];
}
}

Related

while looping vs foreach looping

Im trying to print it in excel but I dont get it why the foreach loop give me an Warning: Illegal string offset but in while loop it just run smoothly
this is the while loop
EDITED
include 'db.php';
$sql = "SELECT * FROM customer";
$result = mysql_query($sql);
$excel = array();
while($row = mysql_fetch_array($result)){
$wew = $row["fname"]."\t".$row["lname"]."\t".$row["email"];
array_push($excel,$wew);
}
echo implode("\n",array_values($excel));
This is my foreach loop
include 'db.php';
$sql = "SELECT * FROM customer";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$excel = array();
foreach($row as $r){
$wew = $r["fname"]."\t".$r["lname"]."\t".$r["email"];
array_push($excel,$wew);
}
echo implode("\n",array_values($excel));
Im trying to understand it but couldn't find how solve this one.
Your $r is of string type and not an array so:
foreach($row as $r){
$wew = $row["fname"]."\t".$row["lname"]."\t".$row["email"];
array_push($excel,$wew);
}
OR
$wew = "";
foreach($row as $r){
$wew .= $row["fname"]."\t".$row["lname"]."\t".$row["email"];
}
array_push($excel,$wew);

retrieve from all row and display it

$query = "SELECT * FROM main";
if ($result = $db->query($query)) {
while ($row = $result->fetch_assoc()) {
$name= $row["name"];
$image = $row["image"];
}
}
then somewhere in my code I print it out using like echo $name; but I got only one result, which is the last row. I know I have to do foreach but what variable should I put?
foreach($result as $results) ? like this?
On every iteration, you reassign the values to $name and $image, causing it to show only the last value when it leaves the loop.
You can either echo them right away in the loop, or populate an array or an object with them, so they will be available later.
Example:
$data = array();
while ($row = $result->fetch_assoc()) {
$data[] = array('name'=>$row["name"], 'image'=>$row["image"]); // push into the array
}
var_dump($data); // it's all here now
And to echo the data later, one of the ways is foreach:
foreach($data as $row) {
echo "Name: ", $row['name'], "; Image: ", $row['image];
}
$query = "SELECT * FROM main";
$result = $db->query($query);
$row = $result->fetch_assoc();
foreach ($row as $rows) {
echo $rows['name'] ." ". $rows['image'];
}

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.

array_push key=>value , how can do it?

I want to push key and value in array , but I can't
$con = mysqli_connect('localhost','root','','wp') or die (mysqli_error('Error:'));
$query = mysqli_query($con,'set names utf8')or die (mysql_error());
$qy = mysqli_query($con,"SELECT ID,post_title FROM wp_posts WHERE post_type='page' AND post_status='publish'")or die (mysql_error());
$arr = array();
while ($row = mysqli_fetch_array($qy)){
$id = "?page_id=".$row['ID'];
$title = $row['post_title'];
$arr[] = $id . "=>" . $title;
array_push($arr, "$id" => "$title");
}
plz help me ..
thanks ^_^
Here's what I would do instead:
$arr = array();
while ($row = mysqli_fetch_assoc($qy)){
$id = $row['ID'];
$arr[$id] = $row['post_title'];
}
And then when you need to print them:
foreach ($arr as $id => $title) {
echo "?page_id={$id}'>{$title}</a>";
// or whatever, depends on how you want to print it
}
Don't store unnecessary information (ie: ?page_id=) in arrays.
Do you want to do $arr[$id] = $title? Or do you want this:
if (!isSet($arr[$id])) {
$arr[$id] = array();
}
$arr[$id][] = $title;
The former will make it so that $arr contains $id=>$title. The latter will make it so that $arr contains $id=>array($title1,$title2,$title3) etc if there are multiples.

PHP Functions with multiple MySQL results only returning one record

This is the function that im calling.
function GetSubmissions($coach){
$result = mysql_query("SELECT * FROM `ptable` WHERE coach = '$_SESSION[username]'") or trigger_error(mysql_error());
while($row = mysql_fetch_array($result)){
foreach($row AS $key => $value) { $row[$key] = stripslashes($value); }
$id = $row['id'];
$teampre = $row['team'];
$eventpre = $row['event'];
$statuspre = $row['status'];
$eventarray = DecodeEvent($eventpre);
$event = $eventarray[0];
$cat = $eventarray[1];
$subcat = $eventarray[2];
$division = $eventarray[3];
$type = $eventarray[4];
$teamarray = explode(",", $teampre);
foreach ($teamarray AS $tkey => $tvalue){
$result = mysql_query("SELECT * FROM `students` WHERE id = '$tvalue'") or trigger_error(mysql_error());
while($row = mysql_fetch_array($result)){
foreach($row AS $skey => $svalue) { $row[$skey] = stripslashes($svalue); }
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$teamgo .= "$firstname $lastname<br/>";
}
}
$push .= "<div id=submission><div id=event>$event</div><div id=status>$statuspre</div><div id=subinfo>$cat $subcat $division $type</div><div id=team>$teamgo</div></div>";
}
return $push;
}
It works, except its only returning a single result. Ive made little tweaks here and there, but im not seeing any positive changes in the output. Any ideas where im going wrong?
You have nested $result variables. You should try to avoid using the same variable name twice. Renaming the second one inside your second foreach loop would probably do the trick.
You use the same $result for inner loop.

Categories