patternphpMinor
Inserting JSON array data into a MySQL database using PHP
Viewed 0 times
arrayintophpjsondatabasemysqlusinginsertingdata
Problem
Here I am parsing a JSON array and inserting it into a MySQL database. The JSON Array comes from my android code.
This is how my JSON array looks like:
This is my php code to parse and insert the data.
This is how my JSON array looks like:
["{custInfo=Ujwal 9975022560, rate=24000, weight=21.00000, desc=GENTS ANGTHI 22k NO STONE, makingAmt=200, vat=RS.3064.38, itemTotal=51073, sum_total=RS.156283.38, barcode=BQSP78BB, net_rate=24200, date=2015-11-30, invoiceNo=1, bill_type=Invoice}",
"{custInfo=Ujwal 9975022560, rate=24000, weight=21.00000, desc=GENTS ANGTHI 22k NO STONE, makingAmt=200, vat=RS.3064.38, itemTotal=51073, sum_total=RS.156283.38, barcode=BQSP78BB, net_rate=24200, date=2015-11-30, invoiceNo=1, bill_type=Invoice}",
"{custInfo=Ujwal 9975022560, rate=24000, weight=21.00000, desc=GENTS ANGTHI 22k NO STONE, makingAmt=200, vat=RS.3064.38, itemTotal=51073, sum_total=RS.156283.38, barcode=BQSP78BB, net_rate=24200, date=2015-11-30, invoiceNo=1, bill_type=Invoice}"]This is my php code to parse and insert the data.
custInfo;
$rate = $inv->rate;
$weight= $inv->weight;
$desc= $inv->desc;
$makingAmt= $inv->makingAmt;
$vat= $inv->vat;
$itemTotal= $inv->itemTotal;
$sum_total= $inv->sum_total;
$barcode= $inv->barcode;
$net_rate= $inv->net_rate;
$date= $inv->date;
$invoiceNo= $inv->invoiceNo;
$bill_type= $inv->bill_type;
$sql = "INSERT INTO selected_items
(custInfo, invoiceNo, barcode, desc,
weight, rate, makingAmt,net_rate,
itemTotal,vat,sum_total,bill_type,date)
VALUES
('$custInfo','$invoiceNo','$barcode','$desc',
'$weight','$rate','$makingAmt','$net_rate',
'$itemTotal','$vat','$sum_total','$bill_type','$date')";
$res = mysqli_query($sql,$con);
echo $res;
if(!$res){
$result = new stdClass();
$result->status = false;
$result->msg = mysql_error();
echo json_encode($result);
exit;
}
}
?>Solution
You are open to SQL Injection. To prevent this, use prepared statements.
You also should not mix
Having variables that are only accessed once is only useful in a limited number of cases, eg when you want to give something a nice name to increase readability. But this is not the case with your variables, so they are really not needed and actually decrease readability. Jut use
You also should not mix
mysql_ and mysqli_ functions; always use mysqli_ (or PDO).Having variables that are only accessed once is only useful in a limited number of cases, eg when you want to give something a nice name to increase readability. But this is not the case with your variables, so they are really not needed and actually decrease readability. Jut use
$inv->custInfo etc directly. This will also severely shorten your code.Context
StackExchange Code Review Q#112331, answer score: 5
Revisions (0)
No revisions yet.