I want to insert JSON parameters in my phpmyadmin database. I tried with below code but it didn't work. Kindly help me in this.
my JSON parameters are:
`$ "address" = "bharuch"
"customer_id" = "108"
"products" = "[{"product_id":"1","product_name":"Potato","category_id":"1","subcategory_id":"1","product_memberprice":"11","product_nonmemberprice":"14","product_minquantity":"500 gms","product_image":"http:\/\/gaubharat.in\/gaubharat\/images\/potato.png","product_brand":"","sub_total":"28","user_qty":"2"},{"product_id":"2","product_name":"Tomato","category_id":"1","subcategory_id":"1","product_memberprice":"15","product_nonmemberprice":"18","product_minquantity":"500 gms","product_image":"http:\/\/gaubharat.in\/gaubharat\/images\/tomato.png","product_brand":"","sub_total":"18","user_qty":"1"}]"
"pincode" = "392025"
"order_totalamount" = "46"`
and my PHP code is:
<?php
require("config.inc.php");
$address = $_POST['address'];
$customerid = $_POST['customer_id'];
$amount = $_POST['order_totalamount'];
$pincode = $_POST['pincode'];
$product = json_decode($_POST['products']);
foreach( $product as $key => $val)
{
$product_id = $val['product_id'];
$product_name = $val['product_name'];
$category_id = $val['category_id'];
$subcategory_id = $val['subcategory_id'];
$product_memberprice = $val['product_memberprice'];
$product_nonmemberprice = $val['product_nonmemberprice'];
$product_minquantity = $val['product_minquantity'];
$product_image = $val['product_image'];
$product_brand = $val['product_brand'];
$sub_total = $val['sub_total'];
$user_qty = $val['user_qty'];
$query = "INSERT INTO `order`(cm_id,product_id,product_quantity,sub_total,order_totalamount,order_id,address,pincode,order_date) VALUES ('$customerid','$product_id','$user_qty','$sub_total','$amount','1','$address','$pincode',CURDATE())";
if(!mysqli_query($db,$query))
{
die('Error : ' . mysql_error());
}
else{
$response["success"] = 1;
$response["message"] = "You order placed successfully!";
echo json_encode($response);
}
}
?>
Kindly help me out in this.
You need to add json_decode function for $_POST['products'] as:
$address = $_POST['address'];
$customerid = $_POST['customer_id'];
$amount = $_POST['order_totalamount'];
$pincode = $_POST['pincode'];
$products = json_decode($_POST['products']);
foreach($products as $key => $val){
...
UPDATE 1:
You have an issue in your query. You are using 9 columns and insert 10 values.
$query = "INSERT INTO `order`(cm_id,product_id,product_quantity,sub_total,order_totalamount,order_id,address,pincode,order_date) VALUES ('$customerid','$product_id','$user_qty','$sub_total','$amount','1','$address',,'$pincode',NOW())";
What is this ,, after $address?
UPDATE 2:
Modified code:
<?php
require("config.inc.php");
$address = $_POST['address'];
$customerid = $_POST['customer_id'];
$amount = $_POST['order_totalamount'];
$pincode = $_POST['pincode'];
$product = json_decode($_POST['products']);
$values = array();
foreach($product as $key => $val)
{
$product_id = $val->product_id;
$product_name = $val->product_name;
$category_id = $val->category_id;
$subcategory_id = $val->subcategory_id;
$product_memberprice = $val->product_memberprice;
$product_nonmemberprice = $val->product_nonmemberprice;
$product_minquantity = $val->product_minquantity;
$product_image = $val->product_image;
$product_brand = $val->product_brand;
$sub_total = $val->sub_total;
$user_qty = $val->user_qty;
$values[] = "('$customerid','$product_id','$user_qty','$sub_total','$amount','1','$address','$pincode',CURDATE())";
}
if(count($values) > 0){
$query = "INSERT INTO `order` (cm_id,product_id,product_quantity,sub_total,order_totalamount,order_id,address,pincode,order_date) VALUES ";
$query .= implode(",",$values);
if(!mysqli_query($db,$query))
{
echo "Error";
}
else
{
$response["success"] = 1;
$response["message"] = "You order placed successfully!";
echo json_encode($response);
}
}
?>
Related
I'm unable to change an input string($prima = $_POST['id'];) and a db query result ($systemuser['id'];) into an array
which will be used for pattern matching using one single character at a time and then trying to
find a match in the database "id" row that is queried. The point is to use two-third of an id(supposedly incomplete id of a user of a system) to query and find the complete id. Please see my code. I'd appreciate some help. Thanks
I'm getting "undefined offset:0 through 9" error.
<?php
session_start();
include_once('server.php');
$error = false;
$gat = "";
$get = "";
$rt1 = "";
$rt2 = "";
$rt3 = "";
$rt4 = "";
$rt5 = "";
$rt6 = "";
$rt7 = "";
$rt8 = "";
$rt9 = "";
$rt0 = "";
if(isset($_POST['btn-login'])){
$firstname = $_POST['firstname'];
$firstname = trim($firstname);
$firstname = trim($_POST['firstname']);
$firstname = htmlspecialchars(strip_tags($firstname));
$lastname = $_POST['lastname'];
$lastname = trim($lastname);
$lastname = trim($_POST['lastname']);
$lastname = htmlspecialchars(strip_tags($lastname));
$id = $_POST['id'];
$id = trim($id);
$id = trim($_POST['id']);
$id = htmlspecialchars(strip_tags($id));
$gender = $_POST['gender'];
if(!$error) {
//search data if no errors
$query = "select * from subscribers";
$conditions = array();
if(! empty($firstname)){
$conditions[] = "firstname='$firstname'";
}
if(! empty($lastname)){
$conditions[] = "lastname='$lastname'";
}
if(! empty($gender)){
$conditions[] = "gender='$gender'";
}
$sql = $query;
if(count($conditions) > 0){
$sql .= " WHERE " . implode(' AND ', $conditions);
}
$result = mysqli_query($conn, $sql);
while($systemuser = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$systemuser['id'];
$gat = $systemuser['id'];
}
//convert user input to array
$prima = $_POST['id'];
$prima = array();
$rt1 = $prima[0];
$rt2 = $prima[1];
$rt3 = $prima[2];
$rt4 = $prima[3];
$rt5 = $prima[4];
$rt6 = $prima[5];
$rt7 = $prima[6];
$rt8 = $prima[7];
$rt9 = $prima[8];
$rt0 = $prima[9];
//retrieve and convert db data into array
$gat = array();
foreach( $gat as $get ){
$rt1 = $prima[0];
if (preg_match("/[$rt1]+/", $gat));{
$get += 1;
}
$rt2 = $prima[1];
if (preg_match("/[$rt2]+/", $gat)){
$get += 1;
}
$rt3 = $prima[2];
if (preg_match("/[$rt3]+/", $gat)){
$get += 1;
}
$rt4 = $prima[3];
if (preg_match("/[$rt4]+/", $gat)){
$get += 1;
}
$rt5 = $prima[4];
if (preg_match("/[$rt5]+/", $gat)){
$get += 1;
}
$rt6 = $prima[5];
if (preg_match("/[$rt6]+/", $gat)){
$get += 1;
}
$rt7 = $prima[6];
if (preg_match("/[$rt7]+/", $gat)){
$get += 1;
}
$rt8 = $prima[7];
if (preg_match("/[$rt8]+/", $gat)){
$get += 1;
}
$rt9 = $prima[8];
if (preg_match("/[$rt9]+/", $gat)){
$get += 1;
}
$rt0 = $prima[9];
if (preg_match("/[$rt0]+/", $gat)){
$get += 1;
}
if ($get > 9){
echo 'match found!';
}
else{
echo 'match not found!';
}
}
}
}
?>
I started to refactor but there is just too much that is wrong.
You are getting that Undefined offset: 0 notice because...
<?php
$prima = array();
$rt1 = $prima[0];
Is referencing offset zero on an empty array. The code makes no sense. You seem to frequently assign a value and then overwrite in on the next line.
FWIW: strings in PHP can behave much like an array...
UPDATE:
I'm a little confused about crux here honestly. If I wanted to reference the first and second letters in a string I would do:
$str = "I like PHP";
$firstLetter = (isset($str[0])) ? $str[0] : '';
$secondLetter = (isset($str[1])) ? $str[1] : '';
See if you can follow this example:
$str = 'I like PHP';
for ($i=0; $i<strlen($str); $i++) {
echo $str[$i] . "|";
}
And then... are you looking to do a WHERE foo LIKE 'a%' type query? A "wildcard" search?
I need to find duplicated details in the existing table while uploading a Excel file that contains some details,i need to find that by phone number and customer name. I am using mattexcel to upload the data into database.
I don't want to insert that details if it is in there but other details must insert into that table
Controller
public function importExcel(Request $request)
{
if ($request->hasFile('import_file')) {
Excel::load($request->file('import_file')->getRealPath(), function ($reader) {
foreach ($reader->toArray() as $key => $row) {
$data['customername'] = $row['customername'];
$data['chassis'] = $row['chassis'];
$data['model'] = $row['model'];
$data['branchcode'] = $row['branchcode'];
$data['delivery'] = $row['delivery'];
$data['customerid'] = $row['customerid'];
$data['phone'] = $row['phone'];
$data['invoicedate'] = $row['invoicedate'];
$data['dse'] = $row['dse'];
$data['branch'] = $row['branch'];
$data['finance'] = $row['finance'];
$data['dono'] = $row['dono'];
$data['invoice'] = $row['invoice'];
$data['zsm'] = $row['zsm'];
$data['sm'] = $row['sm'];
$data['agm'] = $row['agm'];
$data['dsecode'] = $row['dsecode'];
$data['address'] = $row['address'];
$data['email'] = $row['email'];
$data['color'] = $row['color'];
$data['extendedwarrenty'] = $row['extendedwarrenty'];
$data['autocaddownload'] = $row['autocaddownload'];
$data['numberplate'] = $row['numberplate'];
$data['mcpstatus'] = $row['mcpstatus'];
$data['plandt'] = $row['plandt'];
$data['planok'] = $row['planok'];
$data['fasttag'] = $row['fasttag'];
// $data['settilment_pdf_path'] = $row['settilment_pdf_path'];
$data['rcstatus'] = $row['rcstatus'];
$branch = Branch::where([['branch_code', $row['branchcode']], ['status', 0]])->first();
$registration_id = Registration::orderBy('registration_id', 'desc')->take(1)->get();
if (count($registration_id) > 0) {
$regid = $registration_id[0]->registration_id;
$regid = $regid + 1;
} else {
$regid = 1;
}
$register = new Registration();
$register->registration_id = $regid;
$register->customername = $row['customername'];
$register->chassis = $row['chassis'];
$register->model = $row['model'];
$register->branchcode = $row['branchcode'];
$register->delivery = $row['delivery'];
$register->customerid = $row['customerid'];
$register->phone = $row['phone'];
$register->invoicedate = $row['invoicedate'];
$register->dse = $row['dse'];
$register->branch = $row['branch'];
$register->finance = $row['finance'];
$register->dono = $row['dono'];
$register->invoice = $row['invoice'];
$register->zsm = $row['zsm'];
$register->sm = $row['sm'];
$register->agm = $row['agm'];
$register->dsecode = $row['dsecode'];
$register->address = $row['address'];
$register->email = $row['email'];
$register->color = $row['color'];
$register->extendedwarrenty = $row['extendedwarrenty'];
$register->autocaddownload = $row['autocaddownload'];
$register->numberplate = $row['numberplate'];
$register->mcpstatus = $row['mcpstatus'];
$register->plandt = $row['plandt'];
$register->planok = $row['planok'];
$register->fasttag = $row['fasttag'];
$register->rcstatus = $row['rcstatus'];
$register->dealership = $branch->dealership_id;
$register->zone = $branch->zone_id;
$register->dh = $branch->dh_id;
$register->status = '0';
$register->created_user_id = Session::get('created_id');
$register->save();
$regidn = Registration::orderBy('registration_id', 'desc')->get();
$regidd = $regidn[0]->registration_id;
$ssitrack = new Ssi_track();
$ssitrack->registration_id = $regid;
$ssitrack->ssi_track_id = $regid;
$ssitrack->save();
$ssitrackk = Ssi_track::orderBy('ssi_track_id', 'desc')->get();
$ssitrackk = $ssitrackk[0]->registration_id;
}
});
}
return back()->with('success', 'Your File Is Successfully Uploaded To Database!');
}
Option 1. You can add unique values combination in migration.
Schema::table('your_table_name', function (Blueprint $table) {
$table->unique(['phone ','customername ']);
});
This won't let you insert same combination values for these column combination, however it also throws error stopping you import function.
Option 2 (Better).
Check if value already exits and ignore import for that column.
$old_customer = Regiter::where('phone', $row['phone'])->where('customername', $customername )->first();
//Inser only if customer not found
if(is_null($old_customer))
{
//INSERT QUERY
}
To decrease number of query you can pluck name and phone with single query or use any other optimization tricks.
<?php
include 'dbh.php';
session_start();
if (isset($_GET['gmail'])) {
$gname = $_GET['gmail'];
}
$gname = mysqli_real_escape_string($connect, $gname);
$_SESSION['myusername'] = $gname;
$today = date("d.m.y");
$k=0;
$sql = "SELECT cart_fext FROM cart WHERE cart_sess = '$sess'";
$result=mysqli_query($connect, $sql);
$kode[$k] = array();
$kame[$k] = array();
$kesc[$k] = array();
$kail[$k] = array();
$kid[$k] = array();
$kate[$k] = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
extract($row);
$k = $k + 1;
$cname=$row['cart_item_name'];
$csize=$row['item_size'];
$cdesc=$row['cart_desc'];
$cfpath=$row['cart_fpath'];
$cfext=$row['cart_fext'];
$ccode=$row['cart_itemcode'];
$cuserid=$row['cart_usrid'];
$kode[$k] = $ccode;
$kame[$k] = $cname;
$kesc[$k] = $cdesc;
$kail[$k] = $gname;
$kid[$k] = $cuserid;
$kate[$k] = $today;
}
for($i=1; $i<=$k; $i++) {
$sqlsal = "INSERT INTO sales (s_code, s_name, s_desc, s_mail, s_userid, s_date) VALUES ('$kode[$i]', '$kame[$i]', '$kesc[$i]', '$kail[$i]', '$kid[$i]' ,'$kate[$i]')";
$result=mysqli_query($connect, $sqlsal);
}
header("location:makedir.php");
?>
my table sales is just not accepting data, dbh.php is to connect to the database
I don't understand what is wrong with this script?
please help?
I have checked your insert query it is running fine but I think the problem is with your SELECT query
SELECT cart_fext FROM cart WHERE cart_sess = '$sess'
please print the result of the query. I think that it may not be giving any result.
it supposed to be value 1 or other than zero and that makes it unable to insert data into my database cart when i click a product. My ajax statement was working successfully if i click the product but it does not insert anything data into the database table cart.
this is my init.php
<?php
$db = mysqli_connect ('127.0.0.1','root','','tutorial');
if(mysqli_connect_errno()) {
echo 'Database connection failed with following error: '. mysqli_connect_error();
die();
}
session_start();
require_once $_SERVER['DOCUMENT_ROOT'].'/tutorial/config.php';
require_once BASEURL. 'helpers/helpers.php';
$cart_id = '';
if(isset($_COOKIE[CART_COOKIE])){
$cart_id = sanitize($_COOKIE[CART_COOKIE]);
}
if(isset($_SESSION['SBUser'])){
$user_id = $_SESSION['SBUser'];
$query = $db->query("SELECT * FROM users WHERE id = '$user_id'");
$user_data = mysqli_fetch_assoc($query);
$fn = explode(' ', $user_data['full_name']);
$user_data['first'] = $fn[0];
$user_data['last'] = $fn[1];
}
if(isset($_SESSION['success_flash'])){
echo '<div class="bg-success"><p class="text-success text- center">'.$_SESSION['success_flash'].'</p></div>';
unset($_SESSION['success_flash']);
}
if(isset($_SESSION['error_flash'])){
echo '<div class="bg-danger"><p class="text-danger text-center">'.$_SESSION['error_flash'].'</p></div>';
unset($_SESSION['error_flash']);
}
this is config.php
<?php
define('BASEURL', $_SERVER['DOCUMENT_ROOT'].'/tutorial/');
define('CART_COOKIE','SBwi72UCklwiqzz2');
define('CART_COOKIE_EXPIRE',time() + (86400 *30));
this is add_cart.php
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/tutorial/core/init.php';
$product_id = sanitize($_POST['product_id']);
$size = sanitize($_POST['size']);
$available = sanitize($_POST['available']);
$quantity = sanitize($_POST['quantity']);
$item = array();
$item[] = array(
'id' => $product_id,
'size' => $size,
'quantity' => $quantity,
);
$domain = ($_SERVER['HTTP_HOST'] != 'localhost')?'.'.$_SERVER['HTTP_HOST']:false;
$query = $db->query("SELECT * FROM products WHERE id = '{$product_id}'");
$product = mysqli_fetch_assoc($query);
$_SESSION['success_flash'] = $product['title']. 'was added to your cart.';
//check to see if the cart cookie exist
if($cart_id != ''){
$cartQ = $db->query("SELECT * FROM cart WHERE id = '{$cart_id}'");
$cart = mysqli_fetch_assoc($cartQ);
$previous_items = json_decode($cart['items'],true);
$item = 0;
$new_items = array();
foreach($previous_items as $pitem){
if($item[0]['id'] == $pitem['id'] && $item[0]['size'] == $pitem['size']) {
$pitem['quantity'] = $pitem['quantity'] + $item[0]['quantity'];
if($pitem['quantity'] > $available){
$pitem['quantity'] = $available;
}
$item_match = 1;
}
$new_items[] = $pitem;
}
if($item_match != 1){
$new_items = array_merge($item,$previous_items);
}
$items_json = json_encode($new_items);
$cart_expire = date("Y-m-d H:i:s",strtotime("+30 days"));
$db->query("UPDATE cart SET items = '{$items_json}', expire_date = '{$cart_expire}' WHERE id = '{$cart_id}'");
setcookie(CART_COOKIE,'',1,"/",$domain,false);
setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false);
}else{
//add the cart to the database and set cookie
$items_json = json_encode($item);
$cart_expire = date("Y-m-d H:i:s",strtotime("+30 days"));
$db->query("INSERT INTO cart (items,expire_date) VALUES ('{$items_json}','{$cart_expire}')");
$cart_id = $db->insert_id;
setcookie(CART_COOKIE,$cart_id,CART_COOKIE_EXPIRE,'/',$domain,false);
}
?>
if i change this part on file add_cart.php
$domain = ($_SERVER['HTTP_HOST'] != 'localhost')?'.'.$_SERVER['HTTP_HOST']:false;
into $domain = false;
it still give me the value cookie = 0 when i inspect it in the developer tools chrome. can anyone had idea how to fix this so that im able to insert product details into my cart database.
I need to insert multple records i have this right now.
Its adds also the empty field because i dont know how to exclude them from inserting:
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
/* as_factuurregel */
$product1 = $_POST['product1'];
$product2 = $_POST['product2'];
$product3 = $_POST['product3'];
$product4 = $_POST['product4'];
$product5 = $_POST['product5'];
$product6 = $_POST['product6'];
$aantal1 = $_POST['aantal1'];
$aantal2 = $_POST['aantal2'];
$aantal3 = $_POST['aantal3'];
$aantal4 = $_POST['aantal4'];
$aantal5 = $_POST['aantal5'];
$aantal6 = $_POST['aantal6'];
$sql = "INSERT INTO as_factuurregel (productid, factuurid, aantal)
VALUES ('$product1', 'test', '$aantal1'),('$product2', 'test', '$aantal2'),('$product4', 'test', '$aantal3'),('$product5', 'test', '$aantal5'),('$product5', 'test', '$aantal5')";
Thanks for helping.
Greetings
Try this:
$product1 = $_POST['product1'];
$product2 = $_POST['product2'];
$product3 = $_POST['product3'];
$product4 = $_POST['product4'];
$product5 = $_POST['product5'];
$product6 = $_POST['product6'];
$array_one = array($product1,$product2,$product3,$product4,$product5,$product6);
$aantal1 = $_POST['aantal1'];
$aantal2 = $_POST['aantal2'];
$aantal3 = $_POST['aantal3'];
$aantal4 = $_POST['aantal4'];
$aantal5 = $_POST['aantal5'];
$aantal6 = $_POST['aantal6'];
$array_two = array($aantal1,$aantal2,$aantal3,$aantal4,$aantal5,$aantal6);
$newArray = array();
foreach ($array_one as $key => $value) {
if($value != '' && $array_two[$key] != '')
{
$newArray[] = "('$value','test','$array_two[$key]')";
}
}
$values = implode(",",$newArray);
$sql = "INSERT INTO as_factuurregel (productid, factuurid, aantal)
VALUES ".$values;
You can optimize this solution if you optimize your input fields and move them in an array.