Lodi432
Lodi432

Reputation: 35

Sending JSON data to database with PHP

I am learning JSON with PHP and I run into an problem

I am trying to insert my sizes merged string to database products table under sizes column expected result


This Is what I tried:

I have a function that is called saveChangesSizes where I have tried used JSON.stringify() to convert a JavaScript object into a string

$("#saveChangesSizes").click(function(){
    console.log("1");
    var velicine="";
    var niz=new Array();
    for(var i=1; i<=12;i++){
        if($("#size_" + i).val()!=""){
            niz.push({size: $("#size_" + i).val(), qty: $("#qty_" + i).val()});
            velicine+=$("#size_" + i).val() + ":" + $("#qty_" + i).val() + ",";
        }
    }
    console.log(niz);
    if(velicine.length>0){
        velicine=velicine.substring(0,velicine.length-1);
    }
    $("#qtyandsizes").val(JSON.stringify(niz));
    $("#sizes").val(velicine);
     $("#sizesModal").foundation("close");
     return false;
});

After I submit my sizes from modal they are stored in sizes and quantity preview label with correct formating, that is string.

My preview label have an id of "sizes" and value of "$sizes"

With PHP I have defined $sizes in if post condition

 if($_POST){
 $sizes = ((isset($_POST['qtyandsizes']) && $_POST['qtyandsizes'] !='')?sanitize($_POST['qtyandsizes']):'');

I have query for insert to my database :

$insertSql=$veza->prepare("INSERT INTO products (`sizes`) VALUES ('$sizes');");
 $insertSql->execute();

What I am getting into my database is JSON object like so :

[{"size":"medium","qty":"2"},{"size":"large","qty":"3"}]


Update

I should somehow return the value of "velicine" to a php variable since it shows the expected format and result with console.log(velicine)

I tried replacing $_POST['qtyandsizes'] to $_POST['sizes'] but it overwrites anything I manually insert into database size column with empty result


To provide with more information , this is my full code structure:


PHP open and PDO database configuration file included

<?php
include_once "../config.php";

 if(isset($_GET['add']) || isset($_GET['edit'])){
   $sizes = ((isset($_POST['sizes']) && $_POST['sizes'] !='')?sanitize($_POST['sizes']):'');

 if(isset($_GET['edit'])){
   $sizes = ((isset($_POST['sizes']) && $_POST['sizes'] != '')?sanitize($_POST['sizes']):$product['sizes']);

 if($_POST)

   $sizes = ((isset($_POST['sizes']) && $_POST['sizes'] !='')?sanitize($_POST['sizes']):'');

After that comes my query for inserting into the database that I posted above.And where I close my PHP tags.


Opening FORM tags and content bellow :

<form action ="sizes.php?<?=((isset($_GET['edit']))?'edit='.$edit_id:'add=1');?>" method="POST" enctype="multipart/form-data" >

<div class="small-6 large-4 columns ">
   <label>Quantity & Sizes*: </label>
   <button class="button" id="ctl">Quantity & Sizes</button>
</div>
//Id = ctl is used to open my modal where I am inputting sizes

<div class="small-6 large-4 columns ">
  <label for ="sizes">Sizes & Qty Preview</label>
  <input type="text" class="form-control" name="size" id="sizes" value="<?php echo $sizes;?>"readonly> 
</div>

Notice $sizes variable, that is being echoed in correct format to Sizes and Quantaty preview label is what I want to insert into the database, but for some reason it doesn't work.


And my submit button and where my Form ends :

 <input type="submit" value="<?=((isset($_GET['edit']))?'Edit':'Add');?> Product" class="button">


<input type="hidden" name="qtyandsizes" id="qtyandsizes" />

</form>

After this comes my foundation reveal modal for adding sizes with button id saveChangesSizes that outputs the result into preview label.

 <button class="button"  id="saveChangesSizes"> Save Changes

At the end is where javascript saveChangesSizes function is.

Upvotes: 2

Views: 1056

Answers (2)

Joseph_J
Joseph_J

Reputation: 3669

Updated

function getSizes($json){

  $json = urldecode($json);

  $array = json_decode($json, true);

  foreach($array as $key){

  $sizes .= $key['size'] . ':' . $key['qty'] . ',';

  }

  $sizes = rtrim($sizes,',');

  return htmlentities($sizes, ENT_QUOTES, 'UTF-8');

}

echo getSizes($_POST['qtyandsizes']); 

Upvotes: 1

Samir Selia
Samir Selia

Reputation: 7065

You have 2 variables in JS:

1. `niz` which is an `Array`
This `Array` is created in `key value` pair as
size: medium, qty: 2

2. `velicine` which is a `String`
This is created as a concatenated string
medium:2

niz Array is then converted to JSON string and is inserted into products table. velicine is just used to display in a textbox to the user.

[{"size":"medium","qty":"2"},{"size":"large","qty":"3"}]

This is a valid JSON string. If you do not want JSON to be stored, replace it with velicine at the time of insert.

Hope this helps!

Update 1

As per your comment, you want to insert velicine into the database.

To do so, change following snippet

if($_POST){
    $sizes = ((isset($_POST['qtyandsizes']) && $_POST['qtyandsizes'] !='')?sanitize($_POST['qtyandsizes']):'');

to

if($_POST){
    $sizes = ((isset($_POST['sizes']) && $_POST['sizes'] !='')?sanitize($_POST['sizes']):'');

Upvotes: 0

Related Questions