Add field /column to array - php

From mysqli request I receive a result that contains a table with 5 columns and a number of rows. I would like to perform a calculation with my data that I just received and add the result of my calc in a NEW COLUMN in my array.
So in different words, I would like to add one column to the array and fill this column with results for each row.
My code so far looks as follows and of course only prints the array that I receive from my SQL query:
<?php
error_reporting(0);
require 'init1.php';
if($result = $db->query("Select * from (select * from(SELECT * FROM `scores`
ORDER BY `battle_id` ASC,user_id asc,score desc) as t1 GROUP BY
t1.battle_id, t1.user_id) as t2 order by `battle_id` ASC,score desc")){
if($count = $result->num_rows){
echo '<p>' , $count, '<p>';
while ($row = $result->fetch_object()){
echo $row->battle_id, ' ' , $row->user_id, ' ' , $row->score, '<br>';
}
//instead of just printing the existing array, I would like to perform a
//calculation and add a result in a new column at the end of every single
//row
}
}

If you use an Array you can simply 'define' a new item in your array to store the calculation result.
while ($row = $result->fetch_row()) {
// Calculation and other stuff here
$row['calc_result'] = $calculation_result;
}
Then in order to access it outside the while scope, you would need to store each row in another array, for example:
$stored_data = array();
while ($row = $result->fetch_row()) {
// Calculation and other stuff here
$row['calc_result'] = $calculation_result;
array_push( $stored_data, $row );
}

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...

PDO multiple select queries

I am trying to get rows out of 2 tables. The first query works. But the second doesn't. This is my code:
echo '<table width="100%">';
echo '<tr><td>Product</td><td>Quantity</td><td>Price</td><td>Remove</td></tr>';
foreach ($_SESSION['cart'] as $key => $cartproduct) {
list($productid, $productquantity) = split("\|", $cartproduct, 2);
global $db;
$result = $db->prepare('SELECT name FROM products WHERE ID= :ID LIMIT 1; SELECT price FROM prices WHERE productid = :ID AND quantity = :quantity LIMIT 1');
$result->bindParam(':ID', $productid);
$result->bindParam(':quantity', $productquantity);
$result->execute();
$row = $result->fetch();
if($result->RowCount() == 1){
echo '<tr><td>' . $row['name'] . '</td><td>' . $productquantity . '</td><td>' . $row['price'] . '</td><td>Remove</td></tr>'; //LINE15
}else{
unset($_SESSION['cart'][$key]);
}
}
echo '</table>';
The row name is from the products table and the name price is from the prices table. This is the error I get:
Notice: Undefined index: price in /var/www/html/design2/pages/cart.php on line 15
I am sure the query is working. Can anyone tell my what i am doing wrong?
You are receiving index not defined because of the way your query is structured. You have:
SELECT name FROM products WHERE ID= :ID LIMIT 1; SELECT price FROM prices WHERE productid = :ID AND quantity = :quantity LIMIT 1
This is structured to return 2 result sets. You grab the first result set here:
$row = $result->fetch();
But then you try to access $row['price'] which doesn't exist in that result set. That result set is only the result from the first SELECT. You can see this if you just var_dump($row) and see what your result set looks like.
It looks like you can combine your query so that you get one result set:
SELECT p.name, pp.price FROM products p
INNER JOIN prices pp ON p.ID = pp.productid
WHERE p.ID= :ID AND pp.quantity = :quantity
LIMIT 1;
If you can't combine the queries into one, then you should iterate over your result sets and access the relevant $row index. That would look something like:
while($row = $result->fetch()) {
if(isset($row['name'])) {
//do something
} else if(isset($row['price'])) {
//do something else
}
}
Some things to consider:
You may need a LEFT JOIN instead of an INNER JOIN. This depends on
whether or not products always have a corresponding record in the
prices table.
I'm not sure what you're trying to achieve with
LIMIT 1. You may need to consider and ORDER BY -- unless it really
doesn't matter which record you return in your result.
You should consider testing your variables $productid and $productquantity to verify they have your intended values after splitting $cartproduct. What if one is empty / blank ?
You should test your result before trying to access the result array at a specific index.
For example:
if(isset($row['name']) && isset($row['price'])) {
//echo your results
} else {
//return an error
}

PHP Count Images Search Results

I have a search results page which displays items from a MySQL database (table1). The code I am using to the display the results is:
if (!empty($data)) {
foreach ($data as $item) {
echo '<div class="item">';
if (strlen($item['item_desc']) > 10) {
if (strlen($item['item_link']) > 10) {
echo '<a href="/item.php?id='.$item['item_id'].'">';
} else {
echo 'No Results Found';
}
}
}
}
The images for each search result are stored in a separate table (table2). I am trying to use the code below to count the number of images in table2 for each result and display the number against each result on the search results page, but it returns a 0 value?
$result=mysql_query("SELECT count(*) as total from table2 where id = '" .$item['item_id']. "'");
$query=mysql_fetch_assoc($result);
echo $query['total'];
I am missing some data about your database structure but I can imagine you store your image id as an integer and you are requesting the count with the id being a string.
So, if I'm true this may help. Remove the quotes around the php variable with the item_id
"SELECT count(*) as total from table2 where id = " .$item['item_id'];
you can try this..
$str=$item['item_id'];
mysql_query("SELECT count(*) as total from table2 where id = '$str'");
There is a mysql function to count rows outputted from your mysql query, it is mysql_num_rows(). From what I can understand about your database your code could be this:
$item_id = $item['item_id'];
$result = mysql_query("SELECT * FROM table2 where id = '$item_id'");
$count = mysql_num_rows($result);
echo $count;
This will output how many records match your query.

Displaying 5 rows of data from query

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.

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

Categories