I am trying to build an array of cart items that has a mix of a la carte items and package deals. I want to pull the products from the packages and enter the products into my order table. Below is what I have. It pulls the data, but will only add the last record of the inner array (package products) to the outer array. The a la carte items are fine.
$sql = "SELECT id, item_id, package
FROM cart WHERE user_id = $userId";
$result = dbQuery($sql);
$arrCartContent = array();
while ($row = dbFetchAssoc($result)) {
if ($row['package'] == 1) {
// Add Product Credits to Company and Order
$arrProductData = fetchProductDataByPackage($row['item_id']);
$numItem = count($arrProductData);
if ($numItem > 0) {
for ($i = 0; $i < $numItem; $i++) {
extract($arrProductData[$i]);
$row['product_id'] = $product_id;
$row['description'] = $pack_product_name;
}
}
} else {
$itemDetails = fetchProductDetails($row['item_id']);
$row['product_id'] = $row['item_id'];
$row['description'] = $itemDetails['name'];
}
$arrCartContent[] = $row;
}
if(!empty($arrCartContent)) {
foreach ($arrCartContent as $cartData) {
$product_id = $cartData['product_id'];
$description = $cartData['description'];
$sqlInsert = "INSERT INTO shop_order_x_product
(order_id, product_id, description)
VALUES
($orderId, $product_id, '$description')";
$resultInsert = dbQuery($sqlInsert) or die('Cannot add order products: ' . mysql_error());
}
}
You mixed it up a bit, your general approach is fine, maybe streamlining it a bit will make this a breeze and prevent you from overwriting the $row variable inside the loop:
$arrCartContent = array();
while ($row = dbFetchAssoc($result))
{
if ($row['package'] == 1)
{
// Add Product Credits to Company and Order
$arrProductData = fetchProductDataByPackage($row['item_id']);
foreach($arrProductData as $productData)
{
$new = array();
$new['product_id'] = $productData['product_id'];
$new['description'] = $productData['description'];
$arrCartContent[] = $new;
}
}
else
{
$itemDetails = fetchProductDetails($row['item_id']);
$new = array();
$new['product_id'] = $row['item_id'];
$new['description'] = $itemDetails['name'];
$arrCartContent[] = $new;
}
}
You're overwriting the $row array elements with each iteration. Try...
if ($row['package'] == 1) {
// Add Product Credits to Company and Order
$arrProductData = fetchProductDataByPackage($row['item_id']);
$numItem = count($arrProductData);
if ($numItem > 0) {
for ($i = 0; $i < $numItem; $i++) {
extract($arrProductData[$i]);
$row['product_id'] = $product_id;
$row['description'] = $pack_product_name;
$arrCartContent[] = $row;
}
}
} else {
$itemDetails = fetchProductDetails($row['item_id']);
$row['product_id'] = $row['item_id'];
$row['description'] = $itemDetails['name'];
$arrCartContent[] = $row;
}
Related
I have a problem with my shopping cart functionality of my restaurant website.
For example, if i add an item to the cart, then i add another item, then if I delete the one I added last and add it again, it's adding itself doubled in the session. Here I have the functions for adding and removing the items in the shopping cart:
function AddProd($id_prod, $quant) {
if(isset($_SESSION['cart'])){
$_SESSION['cart'].=$id_prod.'>'.$quant.",";
} else {
$_SESSION['cart']=$id_prod.'>'.$quant.",";
}
}
function RemoveFromCart($id_prod) {
if(isset($_SESSION['cart'])) {
$n = $_SESSION['cart'];
$prod_id = substr($n, 0, -1);
$ids = explode(',', $prod_id);
$prods = '';
foreach ($ids as $id) {
$i = explode('>', $id);
if($i[0] != $id_prod) $prods = $prods.''.$id.',';
}
$_SESSION['cart'] = $prods;
}
}
Here i have the function which sets the quantity of the item:
function SetCartNumber($conn) {
if(isset($_SESSION['cart'])) {
$n = $_SESSION['cart'];
$prod_id = substr($n, 0, -1);
$ids = array_map('trim', explode(',', $prod_id));
foreach ($ids as $id) {
$i = explode('>', $id);
$total = $total + $i[1];
}
return $total;
}
return 0;
}
Here it inserts into databse:
function LastId($conn, $tbl){
$s = 'SELECT `id` FROM `'.$tbl.'` ORDER BY `id` DESC LIMIT 1';
if ($r = mysqli_query($conn, $s)) {
$rowd = mysqli_fetch_array($r, MYSQLI_NUM);
return $rowd[0];
}
return -1;
}
$t_price = (empty(GetPromotion($connect))) ? $total_price : '<span style="color: white; font-weight: bold;">'.SetPromotion($connect).'</span> <span style="text-decoration: line-through; color: red;">'.$total_price.'</span>';
if(isset($_POST['delete_prod'])) {
RemoveFromCart($_POST['delete_prod']);
echo '<script type="text/JavaScript"> setTimeout("location.href = \'cart\';",100); </script>';
}
if(isset($_POST['decrease_prod'])) {
ProdsDecrease($_POST['decrease_prod']);
echo '<script type="text/JavaScript"> setTimeout("location.href = \'cart\';",100); </script>';
}
if(isset($_POST['increase_prod'])) {
ProdsIncrease($_POST['increase_prod']);
echo '<script type="text/JavaScript"> setTimeout("location.href = \'cart\';",100); </script>';
}
if (!empty($_POST['trimite']))
{
$str_name = ($str_name[strlen($str_name)-2] == ',') ? substr($str_name, 0, -2) : $str_name;
$str_name2 = ($str_name2[strlen($str_name2)-2] == ',') ? substr($str_name2, 0, -2) : $str_name2;
$price = (empty(SetPromotion($connect))) ? SetCartPrice($connect) : SetPromotion($connect);
$price = (!empty(GetPromotion($connect))) ? $price.' lei(Promotie activa: '.GetPromotion($connect).'%)' : $price;
$prods = MailProds($connect);
$quantity = SetCartNumber($connect);
$price1 = (empty(SetPromotion($connect))) ? SetCartPrice($connect) : SetPromotion($connect);
$price1 = floatval($price1);
$quantity = floatval($quantity);
$email = filter_input(INPUT_POST, 'email');
$telefon = filter_input(INPUT_POST, 'telefon');
$mentiuni = filter_input(INPUT_POST, 'mentiuni');
$tacamuri = filter_input(INPUT_POST, 'tacamuri');
if(!empty(get())) { $email = getEmail($connect); }
$sql = "INSERT INTO `comenzi`(`name`, `pret`, `cantitate`, `adresa_mail`, `nr_telefon`, `mentiuni`, `tacamuri`) VALUES ('$prods', '$price1', '$quantity', '$email', '$telefon', '$mentiuni', '$tacamuri')";
How could I solve the issue?
the problem is in addProd funtion function. you session must contains unique prodId values. but when you are adding the same product again. you are not deleting the first then you will face the problem.
so you should check if the product is already is in session or not, before adding it.
or you should update it.
I'm want string out of the column data.
But it failed.
<?php
$conn = mysql_connect("localhost", "nantawat", "12345678") or die(mysql_error());
$select_db = mysql_select_db("my_db", $conn) or die(mysql_error());
$select_tbl = mysql_query("SELECT * FROM log", $conn);
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
if (!isset($i[1])) {
for ($j = 0; $j <= 200; $j++) {
$i[$j] = null;
}
}
$name = $i[0];
$mama = $i[1];
$no = $i[2];
$a = $i[3];
$b = $i[4];
echo $name . "</br>";
echo $mama . $no . $a . $b . "</br>";
}
while ($data = mysql_fetch_object($select_tbl)) {
echo $data->data . "<br>";
}
?>
But i want output =
bus
car
bike
aabus
car
bike
aabus
car
bike
aabus
ddd
ee
And i not
Notice: Undefined offset: 3 in C:\xampp\htdocs\logs\New folder
(2)\explode.php on line 21
Notice: Undefined offset: 4 in C:\xampp\htdocs\logs\New folder
(2)\explode.php on line 22
Thank You.
You should just do what you want to do.
You want to connect to database then do it:
$conn = mysql_connect("localhost", "nantawat", "12345678") or die(mysql_error());
I suggest you to use mysqli library instead of mysql (mysql is deprecated in new php versions and totally removed in php7)
$conn = mysqli_connect("localhost", "nantawat", "12345678", "my_db") or die(mysql_error());
You want to query on log table, then do it:
$select_tbl = mysqli_query($conn, "SELECT * FROM log");
You want to fetch info from your result, then do it:
while ($row = mysqli_fetch_array($select_tbl)) {
echo $row['id_user'];
echo $row['id_doc'];
echo $row['date'];
echo $row['data'];
}
You want to explode data, then do it:
while ($row = mysqli_fetch_array($select_tbl)) {
echo $row['id_user'];
echo $row['id_doc'];
echo $row['date'];
$data = explode(',', $row['data']);
foreach ($data as $d) {
if ($d !== '') { // because before first comma or after last can be empty
echo $d . PHP_EOL;
}
}
}
If you want to save database result in variables:
If you are getting only one row of database, you can save them in variables directly:
$id_user = '';
$id_doc = '';
$date = '';
$data = array();
id ($row = mysqli_fetch_array($select_tbl)) {
$id_user = $row['id_user'];
$id_doc = $row['id_doc'];
$date = $row['date'];
$tempData = explode(',', $row['data']);
foreach ($tempData as $d) {
if ($d !== '') {
$data[] = $d;
}
}
}
And if you have multiple rows of database you need to save them all in a total array:
$array = array();
id ($row = mysqli_fetch_array($select_tbl)) {
$id_user = $row['id_user'];
$id_doc = $row['id_doc'];
$date = $row['date'];
$data = array();
$tempData = explode(',', $row['data']);
foreach ($tempData as $d) {
if ($d !== '') {
$data[] = $d;
}
}
$array[] = array(
'id_user' => $id_user,
'id_doc' => $id_doc,
'date' => $date,
'data' => data,
);
}
And finally use this to see what structure your final array has:
echo '<pre>';
pront_r($array);
echo '</pre>';
First off it is not wise to store comma seperated values in a single cell and you are using deprecated mysql_ functions. I think your solution can be found in using a foreach instead of the isset part:
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
foreach ($i as $q){
echo $q . '<br/>';
}
}
If you still want to access your variables $name, $mama, $no and $ab, you can use isset for those specifically.
while ($fetch = mysql_fetch_object($select_tbl)) {
$r = $fetch->data;
$i = explode(",", $r);
if (isset($i[0])){
$name = $i[0];
echo $name . '<br>'; //only echo if it exists
}
if (isset($i[1])){
$mama= $i[1];
echo $mama. '<br>'; //only echo if it exists
}
//try it yourself for $no and $ab
}
Try:
while ($row = mysqli_fetch_array($select_tbl)) {
extract($row);
/* Using extract method can get the array key value as variable
Below variables are available
$id_user;
$id_doc;
$date;
$data; */
}
Below is my code:
$id = $_GET['id'];
$qty = $_GET['qty'];
$product_id=$_GET['product_id'];
This is how I receive in the browser
http://example.com/shopping_cart.php?id=17,18&qty=4,5&product_id=3
$_SESSION['test'][]= array('product_id'=>$product_id,array('id'=>$id,'qty'=>$qty));
//print_r($_SESSION['test']);
foreach($_SESSION['test'] as $item=>$value)
{
echo "Main Array ID=". $item;
echo "<br/>";
foreach($value as $v=>$v1)
{
if(is_array($v1))
{
echo "Sub Array ID=". $v;
echo "<br/>";
echo "size id=". $v1['id'];
echo "<br/>";
echo "Quantity=". $v1['qty'];
echo "<br/>";
}
}
}
Output:
Main Array ID=0
Sub Array ID=0
size id=12,13
Quantity=1,2
Main Array ID=1
Sub Array ID=0
size id=17,18
Quantity=4,5
Since size_id and quantity are in implode form, I mean they have a comma ',' in between the value. I need to explode them and use foreach to display one by one.
I mean something like this:
$size_id1=explode(',',$v1['qty']);
foreach($size_id1 as $size_id2)
{
echo $size_id2;
}
$qty1=explode(',',$v1['qty']);
foreach($qty1 as $qty2)
{
echo $qty2;
}
What I need is, I want to display matching size_id and qty. For example, instead of displaying:
size_id 1
size_id 2
Qty 1
Qty 2
It should display:
Size_id 1 Qty 1
Size_id 2 Qty 2
How can I achieve this?
$ids = $_GET['id']
$qtys = $_GET['qty']
$product_id = $_GET['product_id'];
$tmp_result = array();
$ids = explode(',',$ids );
$i = 0;
foreach($ids as $id)
{
$tmp_result[$i]['id'] = $id;
$i++;
}
$i = 0;
$qtys =explode(',',$qtys );
foreach($qtys as $qty)
{
$tmp_result[$i]['qty'] = $qty;
$i++;
}
$_SESSION['tmp_results'][$product_id] = $tmp_result;
$temp_arr = array();
$id_str = '17,18';
$qty_str = '4,5';
foreach(array_combine(explode(',', $id_str), explode(',', $qty_str)) as $k => $v) {
$temp_arr[]['id'] = $k;
$temp_arr[]['qty'] = $v;
}
diffrence betwen 2 implode fetch from database
<?php
$select_tbl=mysql_query("select * from user_reg where uid='". $_SESSION['user1']."'");
while($fetch=mysql_fetch_object($select_tbl))
{
$r=$fetch->specialised;
$i=explode(",",$r);
$length = count($i);
for ($x=0; $x<$length; $x++)
{
echo $i[$x]; }
}?><tbody>
<?php
mysql_connect("localhost","root","");
mysql_select_db("freelancer");
$query=mysql_query("select * from post_proj where status = 1 and payment = '' ") or die(mysql_error());
$j = 1;
while($result=mysql_fetch_array($query))
{
if($result['uid'] == "")
{$d2 = $result['proj_skill'];
$pantry_food1 = explode(",",$d2);
$count_total1 = count($pantry_food1);
for ($counter=0; $counter<$count_total1; $counter++){
$line1 = each ($pantry_food1);
// echo $pantry_food1[$counter];
} $rrt = array_intersect($i,$pantry_food1);
Trying to get the result of my query send it back to controller and return it to a view and access it there. I can't seem to display the value at my view so I tried echoing out what I got as a result from controller. It keeps stating undefined offset 1...please tell me how to access model return value properly
Model
$output = $this->db->query("SELECT * from incoming ORDER BY incomingId LIMIT 20");
return $output->result();
Controller
$data = $this->search_form->searchIdIncoming($searchQuery);
echo $data[0][1];
$this->load->view("searchIncoming", $data);
View
if(isset($incomingId))
echo "Primary key is available";
Try
echo $data[0]["Your Database field name"]; instead of echo $data[0][1];
like
echo $data[0]["id"];
If you want to display the result from model in view the most appropriate way is like this:
1) Return the resultant records from the model as an array like:
$output = $this->db->query("SELECT * from incoming ORDER BY incomingId LIMIT 20");
return $output->result();
2) Access this value in Controller by calling the function for this model query say (as you have not detailed well, I am not sure which function you are using),
$data['details'] = $this->search_form->searchIdIncoming($searchQuery); // store the result in an array
and pass the array to the view
$this->load->view("searchIncoming", $data);
3) In the view file, you can display the records with
if(!empty($details))
{
foreach($details as $row)
{
if($row->incomingId!=0)
echo "Primary key is available";
...........
}
}
I finally made it work by replacing the result() function with the result_array() function in codeigniter added a few other stuff to properly get table functions but here's the result I got:
$rows[] = array();
$rows2[] = array();
$rows3[] = array();
$i = 0;
$companyName = $this->db->query("SELECT id, name from company");
foreach($companyName->result_array() as $row2){
$rows2[$i]['id'] = $row2['id'];
$rows2[$i]['name'] = $row2['name'];
$i++;
}
//get all company names
$i = 0;
$staffName = $this->db->query("SELECT id, surname, firstName, middleInitial from employee");
foreach($staffName->result_array() as $row3){
$rows3[$i]['id'] = $row3['id'];
$rows3[$i]['name'] = $row3['surname'].", ".$row3['firstName']." ".$row3['middleInitial'];
$i++;
}
//get all employee names
$i= 0;
$output = $this->db->query("SELECT * from incoming ORDER BY incomingId LIMIT 20");
if ($output->num_rows() > 0) {
foreach($output->result_array() as $row){
$count = 0;
$j = 0;
$rows[$i]['incomingId'] = $row['incomingId'];
$rows[$i]['referenceNo'] = $row['referenceNo'];
$rows[$i]['documentTypeId'] = $row['documentTypeId'];
$rows[$i]['documentDate'] = $row['documentDate'];
$rows[$i]['dateReceived'] = $row['dateReceived'];
$rows[$i]['sender'] = $row['sender'];
while($count < sizeof($rows2)){
if($rows2[$j]['id'] != $row['companyId']){
$j++;
}else{
$rows[$i]['companyName'] = $rows2[$j]['name'];
break;
}
$count++;
}
$j= 0;
$count = 0;
while($count < sizeof($rows3)){
if($rows3[$j]['id'] != $row['responsibleStaffId']){
$j++;
}else{
$rows[$i]['responsibleStaffName'] = $rows3[$j]['name'];
break;
}
$count++;
}
$rows[$i]['subject'] = $row['subject'];
$rows[$i]['actionDone'] = $row['actionDone'];
$rows[$i]['track'] = $row['track'];
$rows[$i]['completed'] = $row['completed'];
$rows[$i]['remarks'] = $row['remarks'];
$i++;
}
return $rows;
}
return false;
I have this being put into a table listing and what it does is the first function populates the first three rows and then the second function populates the 4th row based on the match of the first function.
public function function1($start = 0, $max = 10, $use_result = false) {
$sql = 'SELECT itemnum, descrip FROM TABLENAME
WHERE itemnum LIKE "__-_____"
AND cms_item_id IS NULL
ORDER BY itemnum ASC
LIMIT ' . (int)$start . ',' . (int)$max .'';
$result = $this->registry->db->query($sql);
$return = array();
while($row = $result->fetch_assoc()) {
$return[] = $row;
}
return $return;
}
/**
* Get matches
* #return array
*/
public function function2(){
$product = $this->getList();
foreach($product as $key) {
$sku = $key['itemnum'];
list(, $sku) = explode("-", $sku);
}
$sql = 'SELECT product_sku, long_name
FROM TABLENAME
WHERE product_sku = "' . $sku . '"';
$result = $this->registry->db->query($sql);
$return = array();
while($row = $result->fetch_assoc()) {
$return[] = $row;
}
return $return;
}
What is happening is the 3 rows are returning fine. But the 4th row is only returning the last $sku not anything matching. I know the foreach loop is being overwriting each time and the final one is being put into the variable $sku...but how else could I do this to get what I need?
Make an array of all the SKUs, and use IN instead of = to match them.
public function function2(){
$product = $this->getList();
$skus = array();
foreach($product as $key) {
$sku = $key['itemnum'];
list(, $sku) = explode("-", $sku);
$skus[] = $sku;
}
$sku_string = implode(', ', array_map(function($x) {return "'$x'"; }, $skus));
$sql = 'SELECT product_sku, long_name
FROM TABLENAME
WHERE product_sku IN (". $sku_string .")';
$result = $this->registry->db->query($sql);
$return = array();
while($row = $result->fetch_assoc()) {
$return[] = $row;
}
return $return;
}
Perhaps a better solution would be to combine your queries into one:
SELECT itemnum, descrip, long_name
FROM table1 t1
JOIN table2 t2 ON t2.product_sku = substring_index(itemnum, '-', -1)
WHERE itemnum LIKE "__-_____"
AND cms_item_id IS NULL
ORDER BY itemnum ASC
LIMIT ' . (int)$start . ',' . (int)$max
try this:
public function function2(){
$product = $this->getList();
$sku = array(); //Make an empty $sku array
foreach($product as &$key) {
$sku = $key['itemnum'];
list(, $sku) = explode("-", $sku);
$key['sku'] = $sku;
$skus[] = $sku;
}
$selectValues = implode(',', $skus);
$sql = "SELECT product_sku, long_name FROM TABLENAME WHERE product_sku IN($selectValues)";
$result = $this->registry->db->query($sql);
$return = array();
$long_names = array();
while($row = $result->fetch_assoc()) {
$long_names[$row['product_sku']] = $row['long_name'];
}
foreach ($product as &$key) {
$key['long_name'] = $long_names[$key['sku']];
}
return $product;
}