I'm trying to get the values from a Query String and add them to an array inside of an array. The output Query String is something like:
add_to_cart.php?product_id=4&product_name=Pizza&quantity=1&additional_id[]=1&additional_quantity[]=3&additional_id[]=4&additional_quantity[]=5
I'm getting each additional_id and additional_quantity variables presents in the Query String with the code below. I compare each of the additional_id with the IDs that I have in database table additionals and insert all into an array. The following code exists in my file add_to_cart.php file:
if(isset($_SESSION['cart']))
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$columns = array
(
'product_id_session' => $product_id_session,
'product_id' => $product_id,
'product_name' => $product_name,
'product_price' => $product_price,
'quantity' => $quantity,
'additionals' => array()
);
if(isset($_GET['additional_id']) && $_GET['additional_id'] != "")
{
foreach($_GET['additional_id'] as $additional => $value)
{
$additional_id = $value;
if(isset($_GET['additional_quantity'][$additional]))
{
$additional_quantity = $_GET['additional_quantity'][$additional];
if($additional_quantity <= 0 || $additional_quantity > 5)
{
$additional_quantity = null;
}
else
{
$sql2 = "SELECT additional_id, additional_name, additional_price FROM additionals WHERE additional_id LIKE '{$additional_id}'";
$stmt2 = $connection->prepare($sql2);
$stmt2->execute();
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$columns['additionals'][]['additional_id'] = $additional_id;
$columns['additionals'][]['additional_name'] = $additional_name;
$columns['additionals'][]['additional_price'] = $additional_price;
$columns['additionals'][]['additional_quantity'] = $additional_quantity;
}
}
}
}
}
$_SESSION['cart'][$product_id_session] = $columns;
}
header('Location: products.php?action=added&product_name=' . $product_name);
}
Once everything is added in the cart SESSION, in the cart.php page I'm trying to show the products with their selected additionals and quantities with:
foreach($_SESSION['cart'] as $product)
{
echo "<tr>";
echo "<td>{$product['product_name']}</td>";
echo "<td>${$product['product_price']}</td>";
echo "<td>{$product['quantity']}</td>";
echo "<td>";
foreach($product['additionals'] as $additional)
{
echo "<p>{$additional['additional_quantity']}x{$additional['additional_name']} - {$additional['additional_price']}</p>";
}
echo "</td>";
echo "</tr>";
}
But I'm doing something wrong, I think these two codes are not working properly.
My output is embarrassed, something like this:
Am I doing it by the right way? Maybe I'm not looping right with foreach, or the additionals are not being added with success? Sorry for the mistakes, I never worked with multidimensional arrays before. Is there a way to do what I am intending to? Thanks!
solution as per the comments-
Your issue is caused by $columns['additionals'][] as it is causing each value to being added as its own array. This is solved by added $additional as the array key -
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$columns['additionals'][$additional]['additional_id'] = $additional_id;
$columns['additionals'][$additional]['additional_name'] = $additional_name;
$columns['additionals'][$additional]['additional_price'] = $additional_price;
$columns['additionals'][$additional]['additional_quantity'] = $additional_quantity;
}
or you could also do-
while ($row = $stmt2->fetch(PDO::FETCH_ASSOC))
{
extract($row);
$columns['additionals'][] = array('additional_id' => $additional_id,
'additional_name' => $additional_name,
'additional_price' => $additional_price,
'additional_quantity' => $additional_quantity);
}
Related
I have 2 results set
$result_a = #pg_query($rquery_a);
$result_b = #pg_query($rquery_b);
I have 2 arrays to host and display the data on an html page:
$datas_a = array();
$datas_b = array();
$datas_a gets this data:
$i=0;
while ($row = #pg_fetch_assoc($result_a)){
$datas_a[$i] = array('s1' => $row['salle'],
'duree_occu' => $row['duree_resa']);
$i++;
}
and $datas_b gets this data:
$i=0;
while ($row = #pg_fetch_assoc($result_b)){
$datas_b[$i] = array('s1' => $row['salle'],
'duree_cours' => $row['duree_cours']);
$i++;
}
From these 2 existing arrays with same number of rows and same keys, I would like 3 columns, 1 column is the same for both arrays ($datas_a and $datas_b), the second column is from $datas_a and the third column is from $datas_b
It currently looks like this for $datas_a
$datas_a
It currently looks like this for $datas_b
$datas_b
It should look like this
merging columns
Now, I have used
$dataComb = array_merge($datas_a, $datas_b);
but it puts one array on top of the other while I would like to just add a column
try
$i=0;
foreach ($datas_a as $data) {
$dataComb[$i]["s1"] = $data["s1"];
$dataComb[$i]["duree_resa"] = $data["duree_resa"];
$i++;
}
$i=0;
foreach ($datas_b as $data) {
$dataComb[$i]["duree_cours"] = $data["duree_cours"];
$i++;
}
Edit - 2021-08-20
Or for something more robust given it's a basic way I only know to do this
$datas_a = array(); // associative array
$datas_b = array();
$dataComb = []; // indexed array
$i=0;
while ($row = #pg_fetch_assoc($result_a)){
$datas_a[$i] = array('s1' => $row['salle'],
'duree_resa' => $row['duree_resa']);
$i++;
}
$i=0;
while ($row = #pg_fetch_assoc($result_b)){
$datas_b[$i] = array('s1' => $row['salle'],
'duree_cours' => $row['duree_cours']);
$i++;
}
$i=0;
if($a>=$b){
foreach($datas_a as $dataa) {
$dataTmp[$i][0] = $dataa["s1"];
$dataTmp[$i][1] = $dataa["duree_resa"];
foreach($datas_b as $datab) {
if($dataa["s1"] == $datab["s1"] ){
$dataTmp[$i][2] = $datab["duree_cours"];
}
}
$i++;
}
}
elseif($a<$b){
foreach($datas_b as $datab) {
$dataTmp[$i][0] = $datab["s1"];
$dataTmp[$i][1] = $datab["duree_resa"];
foreach($datas_a as $dataa) {
if($datab["s1"] == $dataa["s1"] ){
$dataTmp[$i][2] = $dataa["duree_cours"];
}
}
$i++;
}
}
$nb_lig = $a>=$b ? $a : $b;
for ($row=0; $row<=$nb_lig; $row++) {
$dataComb[$row]["s1"] = $dataTmp[$row][0];
$dataComb[$row]["duree_resa"] = $dataTmp[$row][1];
$dataComb[$row]["duree_cours"] = $dataTmp[$row][2];
}
And there is $dataComb as an associative array that combines the data from previous arrays with matching records
foreach ($dataComb as $data){
echo '<tr>';
echo '<td>'.$data["s1"].'</td>';
echo '<td>'.$data["duree_resa"].'</td>';
echo '<td>'.$data["duree_cours"].'</td>';
echo '</tr>';
}
Succesfully solved: Working code is noted at the bottom of this Post.
I'm currently trying to run a SQL command to grab all the data out of a database table and send it over a API call using the variable names.
The problem I'm having is assigning the values of the fields under "$row" to separate variables so I can then place them in my foreach loop and send them all over to the API call. Can anyone enlighten me to what I'm doing wrong
I'm sure the line that I'm going wrong is my commandbuilder and then assigning the variables to the data inside row.
I feel like the problem line could be
while ($row = mysql_fetch_assoc()) {
$emails = $row['email_address'];
$names = $row['forename'];
}
the full code is below.
public function actionImportSubscribers($cm_list_id){
//need to pass through cm_list_id instead
$cm_list_id = Yii::app()->getRequest()->getQuery('cm_list_id');
$model =$this->loadModelList($cm_list_id);
$listID = $model->cm_list->cm_list_id;
$row = Yii::app()->db->createCommand()
->select('email_address, forename')
->from('tbl_cm_subscribers')
->where('cm_list_id=:id', array(':id' => $cm_list_id))
->queryAll();
while ($row = mysql_fetch_assoc()) {
$emails = $row['email_address'];
$names = $row['forename'];
}
$customFieldArray = array();
$addFieldsToList = array();
foreach (array_combine($emails, $names) as $name => $email) {
$addFieldsToList[] = array('EmailAddress' => $email,'Name' => $name,'CustomFields' => $customFieldArray);
}
$auth = array('api_key' => '');
$wrap = new CS_REST_Subscribers($listID, $auth);
$result = $wrap->import(array($addFieldsToList), false);
Working code is below
public function actionImportSubscribers($cm_list_id){
//need to pass through cm_list_id instead
$cm_list_id = Yii::app()->getRequest()->getQuery('cm_list_id');
$model =$this->loadModelList($cm_list_id);
$listID = $model->cm_list->cm_list_id;
$result = Yii::app()->db->createCommand()
->select('email_address, forename')
->from('tbl_cm_subscribers')
->where('cm_list_id=:id', array(':id' => $cm_list_id))
->queryAll();
$emails=array();
$names=array();
foreach ($result as $row) {
$emails[] = $row['email_address'];
$names[] = $row['forename'];
}
require_once 'protected/extensions/createsend-php-5.0.1/csrest_subscribers.php';
$auth = array('api_key' => '');
foreach (array_combine($emails, $names) as $email => $name) {
$wrap = new CS_REST_Subscribers($listID, $auth);
$result = $wrap->import(array(
array(
'EmailAddress' => $email,
'Name' => $name,
),
), false);
}
echo "Result of POST /api/v3.1/subscribers/{list id}/import.{format}\n<br />";
if($result->was_successful()) {
echo "Subscribed with results <pre>";
var_dump($result->response);
} else {
echo 'Failed with code '.$result->http_status_code."\n<br /><pre>";
var_dump($result->response);
echo '</pre>';
if($result->response->ResultData->TotalExistingSubscribers > 0) {
echo 'Updated '.$result->response->ResultData->TotalExistingSubscribers.' existing subscribers in the list';
} else if($result->response->ResultData->TotalNewSubscribers > 0) {
echo 'Added '.$result->response->ResultData->TotalNewSubscribers.' to the list';
} else if(count($result->response->ResultData->DuplicateEmailsInSubmission) > 0) {
echo $result->response->ResultData->DuplicateEmailsInSubmission.' were duplicated in the provided array.';
}
echo 'The following emails failed to import correctly.<pre>';
var_dump($result->response->ResultData->FailureDetails);
}
echo '</pre>';
// }
}
I don't know if this solving your problem but you have few errors there.
mysql_fetch_assoc() requires param , resource returned from mysql_query function.
In part where you creating $emails and $names variables you doing that like if you trying to create array but you will get always single value in that way how you have done it. This is example if you will use mysql_fetch_assoc, you can't combine queryAll() with mysql_fetch_assoc
$emails=array();
$names=array();
$result=mysql_query("SELECT email_address, forename FROM tbl_cm_subscribers where cm_list_id='$cm_list_id'");
while ($row = mysql_fetch_assoc($result)) {
$emails[] = $row['email_address'];
$names[] = $row['forename'];
}
queryAll() method returns array, I don't know Yii but I suppose this is what you need to do
$result = Yii::app()->db->createCommand()
->select('email_address, forename')
->from('tbl_cm_subscribers')
->where('cm_list_id=:id', array(':id' => $cm_list_id))
->queryAll();
$emails=array();
$names=array();
foreach ($result as $row) {
$emails[] = $row['email_address'];
$names[] = $row['forename'];
}
Or if you don't need array of results then use $emails and $names without []
I have the following code:
function resultToArray($result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
// Usage
$query = 'SELECT q17, COUNT(q17) FROM tresults GROUP BY q17';
$result = $mysqli->query($query);
$rows = resultToArray($result);
//print_r($rows); // Array of rows
$result->free();
Brings back the following (only an excerpt):
Array ( [0] => Array ( [q17] => [COUNT(q17)] => 7 ) [1] => Array ( [q17] => Admin & Clerical [COUNT(q17)] => 118 )......etc.
What I am struggling with is how to then return the data, basically, what I need is some code to pull out the data as follows:
WHERE Array = Admin & Clerical BRING BACK THE COUNT(q17) number
How do I search through the array, normally, I'd use something like:
if($rows['q17']==$q[$i]){echo$rows['COUNT(q17)'];}
But this doesn't work - I assume because there are two sets of data within each part of the array? Not sure how to deal with this.
You can achieve this by using MYSQL itself, by using HAVING clause instead of WHERE.
To do this rewrite your query like this.
$query = 'SELECT q17, COUNT(q17) as qcount FROM tresults GROUP BY q17 HAVING q17="Admin & Clerical" ';
echo $row[0]['qcount']; //return 118
if you still want to it with PHP after getting the result from the database, it's how it done:
function get_q17_count($rows, $q17){
foreach ($rows as $onerow) {
if($onerow['q17'] == $q17){
return $onerow['COUNT(q17)'];
}
}
}
function resultToArray($results) {
$rows = array();
while($row = $results->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
// Usage
$querys = 'SELECT q17, COUNT(q17) FROM tresults GROUP BY q17';
$results = $mysqli->query($querys);
$rows = resultToArray($results);
//print_r($rows); // Array of rows
$results->free();
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['q17'] === $id) {
return $val['COUNT(q17)'];
}
}
return null;
}
Called the function using:
$id = searchForId($q[$i], $rows);echo " (".$id.")";
I have a multidimensional array, and I can not update one of these:
public function get_list($query){
if(mysql_query($query,DB::connect())){
$result = mysql_query($query);
if (mysql_affected_rows() != 0) {
while ($row = mysql_fetch_array($result)) {
$list_annunci[] = array(
"id" => $row["id"],
"title" => $row["title"]
);
if(mysql_query($immagini,DB::connect())){
$result_img = mysql_query($immagini);
if (mysql_affected_rows() != 0) {
while ($row_img = mysql_fetch_array($result_img)) {
$list_annunci[] = array(
"img" => $row_img["path_img"]
);
}
}
}
}
how do I insert the record in the array already declared?
tnx stefania
Use your ids as keys for the original array.
$list_annunci[$id] = array(
Make the database query returns those ids as well.
SELECT id, path_img
Then you can inject or update the right group.
$list_annunci[ $id ]["img"] = $row_img["path_img"];
^
|
from $row_img["id"]
I want to echo the values of all arrays that has been returned from a search function. Each array contains one $category, that have been gathered from my DB. The code that I've written so far to echo these as their original value (e.g. in the same form they lay in my DB.) is:
$rows = search($rows);
if (count($rows) > 0) {
foreach($rows as $row => $texts) {
foreach ($texts as $idea) {
echo $idea;
}
}
}
However, the only thing this code echoes is a long string of all the info that exists in my DB.
The function, which result I'm calling looks like this:
function search($query) {
$query = mysql_real_escape_string(preg_replace("[^A-Za-zÅÄÖåäö0-9 -_.]", "", $query));
$sql = "SELECT * FROM `text` WHERE categories LIKE '%$query%'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows['text'] = $row;
}
mysql_free_result($result);
return $rows;
}
How can I make it echo the actual text that should be the value of the array?
This line: echo $rows['categories'] = $row; in your search function is problematic. For every pass in your while loop, you are storing all rows with the same key. The effect is only successfully storing the last row from your returned query.
You should change this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
echo $rows['categories'] = $row;
}
mysql_free_result($result);
return $rows;
to this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
Then when you are accessing the returned value, you could handle it like the following...
foreach ($rows as $key => $array) {
echo $array['columnName'];
// or
foreach ($array as $column => $value) {
echo $column; // column name
echo $value; // stored value
}
}
The problem is that you have a multi-dimensional array, that is each element of your array is another array.
Instead of
echo $row['categories'];
try print_r:
print_r($row['categories']);
This will technically do what you ask, but more importantly, it will help you understand the structure of your sub-arrays, so you can print the specific indices you want instead of dumping the entire array to the screen.
What does a var_dump($rows) look like? Sounds like it's a multidimensional array. You may need to have two (or more) loops:
foreach($rows as $row => $categories) {
foreach($categories as $category) {
echo $category;
}
}
I think this should work:
foreach ($rows as $row => $categories) {
echo $categories;
}
If this will output a sequence of Array's again, try to see what in it:
foreach ($rows as $row => $categories) {
print_r($categories);
}