mysql - PHP store, retrieve and edit an array from database -
i have problem arrays, i'm not new in php have little experience manipulating complex arrays 1 need now.
i'm building shopping cart , idea of cart database row every user have , shopping process should go this
when user buys product if product doesn't exist in cart script should add product cart e.g. 1=1
or in array words $cart = [ [1]=>'1' ]
means product id1 quantity 1, if product exist in cart script should update quantity e.g. 1=2
, on higher quantity.
this poor attempt accomplish aforementioned
php
<?php session_start(); require_once('config.php'); $member_id = '1'; // test data $pr_id = filter_input(input_post, 'pr_id', filter_sanitize_string); // sending id jquery/ajax works fine of course $pr_qty = '1'; // start quantity $up_qty = '5'; // test data try { $getcart = $conn->prepare("select cart members member_id = :member_id "); $getcart->bindparam(':member_id', $member_id); $getcart->execute(); $cart = $getcart->fetch(pdo::fetch_assoc); if(array_key_exists($pr_id, $cart)) { $cart[$pr_id] = $up_qty . ','; } else { $cart[$pr_id] = $pr_qty . ','; } $updatecart = $conn->prepare("update members set cart = :cart member_id = :member_id "); $updatecart->bindparam(':member_id', $member_id); $updatecart->bindparam(':cart', implode($cart)); if($updatecart->execute()) { echo '1'; } } catch(pdoexception $error) { echo 'error: ' . $error->getmessage(); } $conn = null; ?>
later on should able retrieve product id's , quantities database when time comes...
i'm working 3 days on , i'm hopeless, searched everywhere, find many tutorials on multidimensional arrays think problem little unique or i'm stupid enough , can't solve it.
thanks in advance, hope we'll solve together, more brains = more knowledge = solution ;)
the implode function use not work cart, because array indices lost, lose product ids. can serialize or json_encode shopping cart array.
$_session['cart'] = array( 1 => 1, 6581 => 4 ); $json = json_encode($_session['cart']);
then can store $json
string member table. when want fetch database later, have json_decode , put function result in $_session['cart']
again.
$_session['cart'] = json_decode($json, true);
as see, have put $cart
variable $_session
. not need retrieve again database when user navigates on site. reduce load on database speed script. shopping website important website load fast possible, customers enjoy shopping , staying on site.
to add new product or increase quantity of existing position this:
function addproduct($id) { if (isset($_session['cart'][$id])) $_session['cart'][$id]++; else $_session['cart'][$id] = 1; }
after calling addproduct should json_encode , update database make cart persistent.
Comments
Post a Comment