Displaying 5 rows of data from query - php

I have a simple table (mgap_orders) with customer orders in it. Multiple have the the same id (mgap_ska_id) and I simply want to pull 5 records from the table and display all five.
I can easily get one record with the following query and PDO, but how can I display 5 rows instead of only one row?
$result_cat_item = "SELECT * FROM mgap_orders WHERE mgap_ska_id = '$id' GROUP BY mgap_ska_id";
while($row_cat_sub = $stmt_cat_item->fetch(PDO::FETCH_ASSOC))
{
$item=$row_cat_sub['mgap_item_description'];
$item_num=$row_cat_sub['mgap_item_number'];
$item_type=$row_cat_sub['mgap_item_type'];
$item_cat=$row_cat_sub['mgap_item_catalog_number'];
$item_ven=$row_cat_sub['mgap_item_vendor'];
$item_pur=$row_cat_sub['mgap_item_percent_purchased'];
$item_sales=$row_cat_sub['mgap_item_sales'];
}

Use limit 5 then put the results in an array, like this:
$result_cat_item = "SELECT * FROM mgap_orders WHERE mgap_ska_id = '$id' GROUP BY mgap_ska_id LIMIT 5";
$items = array();
while($row_cat_sub = $stmt_cat_item->fetch(PDO::FETCH_ASSOC))
{
$items['item'] = $row_cat_sub['mgap_item_description'];
$items['item_num'] = $row_cat_sub['mgap_item_number'];
$items['item_type'] = $row_cat_sub['mgap_item_type'];
$items['item_cat'] = $row_cat_sub['mgap_item_catalog_number'];
$items['item_ven'] = $row_cat_sub['mgap_item_vendor'];
$items['item_pur'] = $row_cat_sub['mgap_item_percent_purchased'];
$items['item_sales'] = $row_cat_sub['mgap_item_sales'];
}
Then you can do:
foreach($items as $item) {
// echo $item['item'] or whatever
}
EDIT: Or you can skip putting them in the array and just use the while() to do what you need to do with the data.

Related

Is there a better way to run multiple SQL queries to the same table using PHP?

I have a query that requests an ID (the PK) and an order number and throws them into an array. I then loop through the returned data in the array and run two more queries to find the number of times the order number shows up in the database and to get the invoice numbers that belong to that order number. The problem I'm seeing with this setup is that it is taking a while (around 9 seconds) to return the compiled data array. Is there a faster way to get the returned results I'm looking for?
I've tried to find some articles online and came across mysqli_multi_query. Is this the better route to make multiple queries to gather the type of data I am trying to get?
<?php
require 'config.php';
$sql = "SELECT id,internal_order_number FROM orders GROUP BY internal_order_number ORDER BY created_date desc LIMIT 0 ,50";
$query=mysqli_query($mysqli, $sql);
if (!$query) {
throw new Exception(mysqli_error($mysqli)."[ $sql]");
}
$data = array();
while( $row=mysqli_fetch_array($query) ) { // preparing an array
$nestedData=array();
$nestedData['line_id'] = $row["id"];
$nestedData['internal_order_number'] = $row["internal_order_number"];
$data[] = $nestedData;
}
$compiled_data = array();
// Loop through data array with additional queries
foreach($data as $line){
$new_data = array();
// Get item counts
$item_counts = array();
$get_count = " SELECT internal_order_number FROM orders WHERE internal_order_number = '".$line['internal_order_number']."' ";
$count_query=mysqli_query($mysqli, $get_count);
while ($counts=mysqli_fetch_array($count_query)){
if (isset($item_counts[$counts['internal_order_number']])) {
$item_counts[$counts['internal_order_number']]++;
} else {
$item_counts[$counts['internal_order_number']] = 1;
}
}
$product_count = $item_counts[$line['internal_order_number']];
// Get invoice numbers
$invoice_array = array();
$get_invoices = " SELECT invoice_number FROM orders WHERE internal_order_number = '".$line['internal_order_number']."'";
$invoice_query=mysqli_query($mysqli, $get_invoices);
while ($invoice=mysqli_fetch_array($invoice_query)){
if(!in_array($invoice['invoice_number'], $invoice_array)){
$invoice_array[] = $invoice['invoice_number'];
}
}
$invoices = implode(", ",$invoice_array);
$new_data['order_number'] = $line['internal_order_number'];
$new_data['count'] = $product_count;
$new_data['invoices'] = $invoices;
$compiled_data[] = $new_data;
}
mysqli_close($mysqli);
print_r($compiled_data);
?>
What, why are you doing basically the same query 3 times. You first one selects them all, you second query requires the same table making sure the first tables order number == the tables order number and the last just grabs the invoice number...?
Just do one query:
SELECT internal_order_number, invoice_number FROM table WHERE ...
Then loop through it and do what you need. You don't need 3 queries...

PHP/SQL: Faster Way to Combine Query Results

I'm joining data from two SQL queries and I'm wondering if there is a faster way to do this as a single SQL query because there is a lot of looping involved. I've got two queries that look for different string values in the "option_name" field:
$sql01= "SELECT user_id, option_value FROM wp_wlm_user_options WHERE option_name = 'wpm_login_date' ORDER BY user_id";
$sql02 = "SELECT user_id, option_value FROM wp_wlm_user_options WHERE option_name ='stripe_cust_id' ORDER BY user_id ";
Then I create two arrays:
//Process the 1st SQL query data into an Array
$result_array01 = array();
$j = 0;
while($r = mysql_fetch_assoc($result01)) {
if(!empty($r['option_value'])){
//User Id and Last Login
$result_array01[$j]['user_id'] = $r['user_id'];
$result_array01[$j]['last_login'] = $r['option_value'];
$j++;
}
}
//Process the 2nd SQL query data into an Array
$result_array02 = array();
$k = 0;
while($s = mysql_fetch_assoc($result02)) {
if(!empty($s['option_value'])){
//User Id and Stripe Customer Id
$result_array02[$k]['user_id'] = $s['user_id'];
$result_array02[$k]['cust_id'] = $s['option_value'];
$k++;
}
}
And finally, I combine the arrays:
//Combine the SQL query data in single Array
$combined_array = array();
$l = 0;
foreach($result_array01 as $arr01){
// Check type
if (is_array($arr01)) {
//mgc_account_print("hello: " . $arr01['user_id'] . "\r\n");
foreach($result_array02 as $arr02){
// Check type
if (is_array($arr02)) {
//Check if User Id matches
if($arr01['user_id'] == $arr02['user_id']){
//Create Array with User Id, Cust Id and Last Login
$combined_array[$l]['user_id'] = $arr01['user_id'];
$combined_array[$l]['last_login'] = $arr01['last_login'];
$combined_array[$l]['cust_id'] = $arr02['cust_id'];
$l++;
}
}
}
}
}
Why you doing in two different queries?
Use mysql IN('val', 'val2');
$sql01= "SELECT tbl1.user_id, tbl1.option_value FROM wp_wlm_user_options as tbl1 WHERE tbl1.option_name = 'wpm_login_date'
union all
SELECT tbl2.user_id, tbl2.option_value FROM wp_wlm_user_options as tbl2. WHERE tbl2.option_name ='stripe_cust_id' ";
But using OR/AND will your help you in your case , I didnt see at first that you want combined same table. I didnt delete my answer to help you for another solution
Also you should use DISTINCT to avoid multiple records.
SELECT DISTINCT USER_ID, OPTION VALUE FROM TABLE

Select data from the database before or after a defined value

I am having problems achieving the query to select data from a table in the db after a defined value has been met.
My code to do this is:
$fi = 'first_segment'
$im = popo.jpg
$sqls = "SELECT * FROM $fi,news_pictures
WHERE $fi.pi_id = news_pictures.pi_id
AND news_pictures.i_name = '$im'
GROUP BY news_pictures.id DESC";
I wasn't able to achieve the result with that query.
Basically, I want the query to confirm if news_pictures.i_name = '$im' and if true, return starts from the value of $im followed by other data in the table depending on news_pictures.id DESC.
The sample data and output:
Table news_pictures:
id i_name
-- ------
1 coco.jpg
2 lolo.jpg
3 popo.jpg
4 dodo.jpg
Since $im = popo.jpg, I want my query to display all values starting from popo.jpg with id DESC, i.e. popo.jpg, lolo.jpg, coco.jpg.
I got to solve the question with the help of a friend.
$fsqls = "SELECT * FROM $fi,news_pictures WHERE $fi.pi_id = news_pictures.pi_id AND news_pictures.i_name = '$im' GROUP BY news_pictures.id";
$rres = mysqli_query($connection, $fsqls) or print(mysqli_error($connection));
while($row = mysqli_fetch_assoc($rres))
{
$rnm = $row["id"];
}
$sqls = "SELECT * FROM news_pictures WHERE news_pictures.id <= $rnm ORDER BY news_pictures.id DESC";

PHP inserting array into an object

I am trying to inject an array into an object but it's just not working. This is what I am doing:
1) Get a specific Match record from the database
2) Get all the Player records from the database that are associated with that match
3) Add them players to the Match object
Code:
$matchQuery = "SELECT * FROM matches where new = 1 order by date asc limit 1";
$matchResult = mysql_query($matchQuery,$link) or die('Errant query: '.$matchQuery);
/* create one master array of the records */
$matches = array();
if(mysql_num_rows($matchResult)) {
while($match = mysql_fetch_assoc($matchResult)) {
$playersQuery = "SELECT p.* FROM match_players mp
LEFT JOIN players p on p.id = mp.player_id
WHERE mp.match_id = '$match->id'";
$playerResult = mysql_query($playersQuery,$link) or die('Errant query: '.$playersQuery);
$players = array();
if(mysql_num_rows($playerResult)) {
while($player = mysql_fetch_assoc($playerResult)) {
$match->players[] = $player; //<-- This doesn't seem to work
}
}
$matches[] = $match;
}
}
The objects within Match are being spat out, BUT, the Players are not.
$match is an array, the result of the deprecated mysql_fetch_assoc(). So $match->players[] = $player; is not going to work.
If there is no players key in the sql result, you can add it to the array:
$match['players'][] = $player;
Otherwise you would have to use a different key.
Another problem is your query in the loop: You use $match->id and that should be $match['id'] as $match is an array.
By the way, doing sql queries in a loop is never a good idea, you should try to get your results in one query joining the different tables.
$match["players"] = array();
while($player = mysql_fetch_assoc($playerResult)) {
$match["players"][] = $player;
}

slow results using while loop with mysql_fetch_array

I'm getting terribly slow results from the following code. I've been trying to troubleshoot it for hours but with no results. I've included only the relevant code.
Edit:
I am trying to select an id from a database and then use that id to get all the images associated with it. I am then narrowing that group of images down to one. Once I have that image I am resizing it through an external file.
I've tried removing various parts of the code to identify the problem and it seems as if the slow down is being caused by the second query but I am not sure why. Thanks for your help.
$getworks = mysql_query ("SELECT a_id from artists where display_works = '1' and active = '1' order by project_year desc, fullname desc");
while ($getworksrow = mysql_fetch_assoc($getworks)){
$totalimages=1;
$addstyle = "";
$id = $getworksrow["a_id"];
$getimages = mysql_query ("SELECT a_id, image_id from images where a_id = '". $id ."' order by position asc LIMIT 1");
$getimagesrow = mysql_fetch_assoc($getimages);
foreach ($getimagesrow as $getimagesrows){
extract($getimagesrow);
if($totalimages > 1){ $addstyle = 'style="display:none;"'; }
else {
$myimagename = "http://artist.com/$a_id/images/$image_id" . "_large.jpg";
list($width, $height, $type, $attr) = getimagesize("$myimagename");
$myimagename = "http://artist.com/artists/resize.php/$a_id/images/$image_id" . "_large.jpg?resize(157x2000)";
if($getworksrows["layout"] == "vert"){$pl = "_vertical";}else if($getworksrows["layout"] == "website"){$pl = "-s";}else if($getworksrows["layout"] == "video"){$pl = "_video";}else{$pl = "_horizontal";}
echo "<li class='thumbnail_container' $addstyle> <a class='thumbnail' href=\"../works$pl.php?a_id=" . $getworksrows["a_id"] . "\"><span><img src=\"$myimagename\" /></span>\n</a></li>\n";
}
$totalimages++;
}
}
It's a a big performance overhead to execute queries like this specially when parent query have large no. of records.
You should use join artists table with images table and get all data by single query.
Later on make 2D array of per artists and images. and loop according to 2D array to display data
Below is join query you should use:
SELECT * from artists as art
left join images as img on art.a_id=img.a_id
where display_works = '1' and active = '1'
order by project_year desc, fullname desc
In While make data array:
while ($getworksrow = mysql_fetch_object($getworks)){
$data['a_id']['img_id']=$getworksrow->image; //Make 2D array
........
........
}
looping and display data :
foreach($data as $id=>$images)
{
foreach($images as $val){
// Do your stuff for displaying data
}
}
So please do required changes.

Categories