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.
Related
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'];
}
}
i noticed that there are a lot of topics like this in stackoverflow, but the ones that i read are with just 1 variable, and i have two and i'm a little confuse.
so this is my code,
$query = mysql_query("SELECT Provider.provider_id, provider.company_name FROM Provider");
while($row = mysql_fetch_array($query)){
echo "'".$row['provider_id']."':'".$row['company_name']."',";
}
I am using this to generate javascript code for Jeditable.
I need to take out the last comma, so I can wrap up with the rest of the code...
I like to use an array:
$query = ...;
$out = Array();
while($row = mysql_fetch_assoc($query)) {
$out[] = "'".$row['provider_id']."':'".$row['company_name']."'";
}
echo implode(",",$out);
It looks like you're trying to output some kind of JSON though, so perhaps you could use:
$query = ...;
$out = Array();
while($row = mysql_fetch_assoc($query)) {
$out[$row['provider_id']] = $row['company_name'];
}
echo json_encode($out);
So i usually just stack things like this into an array and then implode:
$parts = array();
while($row = mysql_fetch_array($query)){
$parts[] = "'".$row['provider_id']."':'".$row['company_name']."'";
}
echo implode(',', $parts);
That said it looks like youre outputting the body of a JSON string. If so you shouldnt manually build it you should use json_encode instead.
$data = array();
while($row = mysql_fetch_array($query)){
$data[$row['provider_id']] = $row['company_name'];
}
echo json_encode($data);
$query = mysql_query("SELECT Provider.provider_id, provider.company_name FROM Provider");
$result = "";
while($row = mysql_fetch_array($query)){
$result .= "'".$row['provider_id']."':'".$row['company_name']."',";
}
$result = rtrim($result, ',');
OR
$query = mysql_query("SELECT Provider.provider_id, provider.company_name FROM Provider");
$result = array;
while($row = mysql_fetch_array($query)){
$result[] = "'".$row['provider_id']."':'".$row['company_name']."',";
}
$result = implode(',' $result);
OR
get count of records (mysql_num_rows($query)) and when you hit last row just do what you want
I hava a while loop that throught to databases records. Like this:
$query = mysql_query("SELECT * FROM table");
while($articles = mysql_fetch_array($query)){
// something happen here
}
How can I echo each $articles out of the while loop ? So I don't want to have something like
while(...){
echo $articles['article_name'];
}
How can I save all the $articles['article_name'] into an array an echo them back ?
How about this:
$articleList = array();
while(...){
$articleList[] = $articles['article_name'];
}
That will put everything in the array $articleList for you.
You can do something like:
$articles = array();
while ($art = mysql_fetch_array($query)) {
$articles[] = $art;
}
print_r($articles);
$i=0; $articles = array();
$query = mysql_query("SELECT * FROM table");
while($articles[] = mysql_fetch_array($query)){
echo $articles['article_name'][$i];
$i++;
}
$query = mysql_query("SELECT * FROM table");
while($articles = mysql_fetch_array($query)){
$names[] = $articles['article_name'];
}
echo 'array of names are :';
print_r($names);
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.
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.