JSON Decode to MYSQL Database - php

I am having JSON POST like this.
{"item_sku":["016","APL","017"],"item_quantity":[2,4,1]}
I want to insert it into mysql database table and in column named 'item_sku' and 'item_quantity'. I guess this will insert three rows.
HTML Page:
<form id="form1" class="p-md col-md-6" ng-submit="addOrder()">
<ul class="list-group m-b-sm md-whiteframe-z0" ng-repeat="item in cart.items">
<li class="list-group-item">
<a ui-sref="app.product({productSku: item.sku})" class="pull-right w-56"><img ng-src="http://192.168.0.228/app/{{ item.image || 'img/default_product.jpg' }}" alt="{{item.sku}}" class="img-responsive"></a>
<div class="clear">
<b>{{item.name}}</b><br>
<span style="color:#666;font-size:12px;">{{item.description}}</span><br>
<span style="color:#666;font-size:12px;">SKU# {{item.sku}}</span>
<input type="text" ng-model="sku[$index]" ng-init="sku[$index]=item.sku">
<br><br>
</div>
<div>
<!-- use type=tel instead of to prevent spinners -->
<button
class="form-control btn btn-grey" type="button" style="width:34px;background-color:#ddd;"
ng-disabled="item.quantity <= 1"
ng-click="cart.addItem(item.sku, item.name, item.price, -1)">-</button>
<input
class="form-control btn btn-grey" size="2" style="width:44px" type="tel"
ng-model="item.quantity"
ng-change="cart.saveItems()" />
<button
class="form-control btn btn-grey" type="button" style="width:34px;background-color:#ddd;"
ng-disabled="item.quantity >= 100"
ng-click="cart.addItem(item.sku, item.name, item.price, +1, $index)" >+</button>
<input type="text" ng-model="quantity[$index]" ng-init="quantity[$index]=item.quantity">
</div>
</li>
<div class="p b-t b-t-2x">
<a style="color:#666;" ng-click="cart.addItem(item.sku, item.name, item.price, -10000000)" >
<i class="icon mdi-action-delete i-20" style="color:#666;"></i>Remove</a>
<span class="pull-right">{{item.price * item.quantity | currency:' ₹ ':2}}</span>
</div>
</ul>
<button type="submit" class="btn btn-info m-t" >Submit</button>
</form>
Controller:
app.controller('OrderCtrl', function($scope, $location, $http ) {
$scope.sku = [];
$scope.quantity = [];
$scope.addOrder = function(){
$http.post(serviceURL+'submit_order.php', {
'item_sku':$scope.sku,
'item_quantity':$scope.quantity
})
.success(function(data,status,headers,config){
$location.path('app/feedbackthankyou');
});
};
});
PHP Code:
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
include "db.php";
// Using Static Data from POST -- Just for testing
$a='{"item_sku":["016","APL","017"],"item_quantity":[2,4,1]}';
$data = json_decode($a);
var_dump($data);
foreach ($data as $value)
{
echo $value->item_sku;
echo $value->item_quantity;
}
?>
I guess details are enough now. BTW I am using AngularJS to create CART. Please help.

The shape of your data complicates the database insertion a bit. Data that should go in the same row is divided into two separate objects: $data->item_sku and $data->item_quantity.
It would be simpler if everything that should go in one row were together in one variable or one array element. I would change the shape of the data I submit. Instead of a item_sku and item_quantity, I would just submit items.
Javascript
var items=[];
for(var i=0; i<$scope.sku.length; i++){
items.push({'sku':$scope.sku[i], 'qty':$scope.quantity[i]});
}
$http.post(serviceURL+'submit_order.php', {items:items})
Then on the PHP side
$data = json_decode($_POST['items'],true);
Now $data is an array of items with the shape:
[
['sku'=>'016','qty'=>2],
['sku'=>'APL','qty'=>4],
];
This can be more easily inserted in your database because the data is already organized in rows. You said you already know how to do DB inserts so I'll let you work out that part.

Related

Insert URL in database Codeigniter 3

I got a website delivered to me, and the dev doesn't reply to me anymore. As a beginner I am trying to find a solution by my own but I can't figure it out.
I would like to add a feature and maybe you guys can help me.
To explain our users can write some comments on a single page, before to be published our moderator is validating the comment, as soon as it is done the user is receiving an email saying your comment Blablabla has been validated.
We would like to add to the email a link to the page where he wrote his comment, as we have a lot of single pages with different URL, it will be easier for him to found his comment back.
So our goal is to save the URL into the database and then I will extract that URL to put it in the email.
I have added in the our user_comment DB the column url_link to store the URL.
Here is my controller, I have added urllink
public function add_comment(){
if ($this->session->userdata('user_id')){
$comment = $this->security->xss_clean($this->input->post('comment'));
$pageid = $this->security->xss_clean($this->input->post('page_id'));
$urllink = $this->security->xss_clean($this->input->post('url_link'));
$data = array(
'user_id' => $_SESSION['user_id'],
'page_id' => $pageid,
'url_link' =>$urllink,
'comment' => $comment,
'created' => date("Y-m-d H:i:s"),
'modified' => date("Y-m-d H:i:s")
);
echo $query = $this->page_model->add_comments($data);die;
}else{
redirect();
}
}
My model
public function add_comments($data){
if($this->db->insert('user_comment',$data)){
return 'true';
}else{
return 'false';
}
}
My view for the comment section
<h3>Post a Comment</h3>
<?php if ($this->session->userdata('user_id')){?>
<div class="textarea_editor" style="clear:left; ">
<div class="textarea_editorinner">
<div id="editor" data-id="<?php if(!empty($_SESSION['user_id'])){ echo $_SESSION['user_id'];}else{ echo '';}?>"></div>
<textarea name="comment" style="display:none" id="hiddenArea" class="add_comment"></textarea>
</div>
<?php }else{?>
<div class="write-comment">
<input style="margin-left:10px; " type="text" data-toggle="modal" data-target="#user_login" placeholder="Type your comment" class="add_comment">
<?php }?>
<?php
if ($this->session->userdata('user_id')){?>
<button class="sendmessage sendmessageclick" data-d-id="<?php echo $pages[0]->pageId;?>"><span class="far fa-paper-plane">
</span><span class="d-none d-block-sm">Send</span></button>
<?php }?>
</div>
</div>
My common.js
$('.sendmessageclick').click(function(){
$('#hiddenArea').val(quill.container.firstChild.innerHTML);
$.ajax({
type:'post',
async: false,
data:{page_id:$(this).attr('data-d-id'),comment:$('.add_comment').val()},
url: static_url+'/pages/add_comment',
success: function(result){
$('.add_comment').val('');
if(result == 'true'){
$('.comment_alert').show();
setTimeout(function() {
$('.comment_alert').hide();
location.reload();
}, 3000);
}else{
alert('Error');
location.reload();
}
console.clear();
}
});
});
Everything is working perfectly, except URL, for sure I am missing something to indicate the URL to be stored in the DB.
Thanks for your support.
As I can see your controller collect three POST variables they are 'comment', 'page_id', and 'url_link'. However, if you look at your view code only 'comment' is sent.
A simple solution would be to add two additional input boxes having the name 'page_id', and 'url_link'.
<h3>Post a Comment</h3>
<?php if ($this->session->userdata('user_id')){?>
<div class="textarea_editor" style="clear:left; ">
<div class="textarea_editorinner">
<div id="editor" data-id="<?php if(!empty($_SESSION['user_id'])){ echo $_SESSION['user_id'];}else{ echo '';}?>"></div>
<textarea name="comment" style="display:none" id="hiddenArea" class="add_comment"></textarea>
<input type='hidden' name='page_id' value='<<Page ID value added by PHP>>'>
<input type='text' name='url_link' value=''>
</div>
<div class="write-comment">
<input style="margin-left:10px; " type="text" data-toggle="modal" data-target="#user_login" placeholder="Type your comment" class="add_comment">
<?php }?>
<?php
if ($this->session->userdata('user_id')){?>
<button class="sendmessage sendmessageclick" data-d-id="<?php echo $pages[0]->pageId;?>"><span class="far fa-paper-plane">
</span><span class="d-none d-block-sm">Send</span></button>
<?php }?>
</div>
</div>

How to pass and catch variable when the method is POST then the route is GET?

I'm developing a web application, and I want to pass variable called ID when the form method is post that linked to open other form but in the config/routes I'm using $routes[page_A][get] = 'Controller' not $routes[page_A][post] = 'Controller'.
I'm using Codeigniter framework here, I've tried to change the controller with $this->input->get('id') but it doesn't work and I don't have any idea whats really happen in my codes.
The Sender Form View code
<form action="<?= base_url().'progres_save'; ?>" method="POST">
<div class="form-group">
<div class="form-row">
<label for="idJobOrder">ID Job Order</label>
<input type="text" name="idJobOrder" class="form-control" value="<?php echo $rd[0]->kodejobglobal; ?>" readonly>
</div>
</div>
<div class="form-group">
<div class="form-row">
<a class="btn btn-primary col-xl-1 col-sm-1 mb-1 ml-auto mr-0 mr-md-2 my-0 my-md-3" href="job" id="back" role="button"><i class="fas fa-fw fa-arrow-left"></i> Back</a>
<button class="btn btn-primary btn-block col-xl-1 col-sm-1 mb-1 mr-0 mr-md-2 my-0 my-md-3">Save <i class="fa fa-fw fa-arrow-right"></i></button>
<input type="hidden" name="id" value="<?php echo $rd[0]->kodejobspesifik ?>">
</div>
</div>
</form>
The Sender Form Controller code
public function save()
{
$idglobal = $this->input->post('idJobOrder');
$data = array('jobnya' => $idglobal );
$this->Model_joborder->save_pg($data,'lapharian');
redirect('progres_material');
}
The Config Routes code
$route['progres_save']['get']='error';
$route['progres_save']['post']='save';
$route['progres_material']['get']='matused';
$route['progres_material']['post']='error';
The Recipient Form Controller code
public function matused()
{
$id = $this->input->get('id');
$data['rd'] = $this->Model_joborder->tampil2($id);
$data['fb'] = $this->Model_joborder->data_cbb();
$this->load->view('matused', $data);
}
The Recipient Form View code
<form method="POST" action="<?= base_url().'matsave'; ?>">
<div class="form-group">
<div class="form-row">
<?php if (isset($rd[0])) {?>
<input type="hidden" value="<?php echo $rd[0]->jobspesifiknya; ?>" name="idClient" class="form-control" placeholder="First name" readonly>
<?php } ?>
</div>
</div>
</form>
What I expect is the input id value from Sender will be passed and catch on Recipient form as input idClient. Can anyone her help me to find out the solution? Thank you.
You can use PHP global variable $_REQUEST to capture the data if you are not sure about the request type like this,
public function matused()
{
$id = $_REQUEST['id'];
$data['rd'] = $this->Model_joborder->tampil2($id);
$data['fb'] = $this->Model_joborder->data_cbb();
$this->load->view('matused', $data);
}
You forgot to include the id data on the redirect after the save() method is called, so you will not get anything by calling $this->input->get('id').
To solve this, pass the id data along with the redirect :
redirect('progres_material?id=' . $this->input->post('id'));
But that of course it will gives you an extra parameter on the url. If you don't want additional parameter, you could alternatively use session to pass id data while redirecting, on CodeIgniter there is a method called set_flashdata to do this :
$this->session->set_flashdata('id', $this->input->post('id'));
redirect('progres_material');
And to get the id session data on the matused() method, use the following code :
$id = !empty($this->session->flashdata('id')) ? $this->session->flashdata('id') : $this->input->get('id');

jquery-the output is always in the first item only

I am trying to create a web store and I use Jquery in radio button for selecting a category but the output is always on the first item only not in each items.
here is the jquery code
function populateswatches() {
var swatchesName = $('input[name=optradio]:checked').val();
$.getJSON('getdata.php', {swatchesName: swatchesName}, function(swatch) {
var html = '';
$.each(swatch, function(index, array) {
html = html + '<div class="col-md-3 w3-margin-top"><div class="w3-display-container w3-hover-opacity"><div class="w3-center"><input type="radio" name="swatches_code" value="' + array['swatches_code'] + '" required></div><div class="w3-display-middle w3-display-hover"><button type="button" class="btn btn-primary"><i class="fa fa-search fa-lg" aria-hidden="true"></i></button></div><img src="../backend/functions/images/'+array['images']+'" style="width:100%"><div class="w3-center">' + array['swatches_code']+'</div></div></div>';
});
$('#swatches').html(html);
});
}
$(function() {
$(this).change(function() {
populateswatches();
});
});
here is the code for php. it is not complete though.
$priceSQL="SELECT * FROM price WHERE id_item='$IDitem'";
$priceRES=mysqli_query($conn,$priceSQL);
while($priceROW=mysqli_fetch_assoc($priceRES)){
$id_categ=$priceROW["id_category"];
$catSQL="SELECT * FROM category WHERE id_category='$id_categ'";
$catRES=mysqli_query($conn,$catSQL);
while($catROW=mysqli_fetch_assoc($catRES)){
echo '
<div class="radio">
<label><input type="radio" name="optradio" value="'.$priceROW["price"].'-'.$id_categ.'" required>'.$catROW["swatches_category"].'- ₱'.formatMoney($priceROW["price"]).'</label>
</div>
';
}
}
</li>
</ul>
<h4>SWATCHES</h4>
<div class="form-group">
<span id="swatches"></span>
</div>
<input type="hidden" value="'.$IDitem.'" name="id_item">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-success">Add to Cart</button>
here is the output
here is the image output for it
Reason:-
id is treated as unique identifier in jQuery.Since all spansin your code have same id, that's why code only working for first-one.
Solution:-
Convert id to class in your HTML code like below:-
<span class="swatches"></span>
And change # to . in jQuery like below:-
$('.swatches').html(html);
Note:- class is treated as a group identifier in jQuery and work on each element which share same class.

codeigniter : Cant display value from input text using $_POST to SQLcode inside model

the function sumqtyin() inside codeigniter model
function sumqtyin(){
$kdbahan = $_POST['kode_bahan_baku']; //i wanna echo a value from the input text kode_bahan_baku but it always says error "undefined index kode_bahan_baku"
$datenow = date("Y-m-d");
return $this->db->query("
SELECT IFNULL(SUM(qty_in),0) AS qty_in
FROM trans_stock_movement
WHERE tanggal_movement='$datenow'
AND status_aktif='YES' AND kode_bahan_baku = '$kdbahan' ");
}
my view input text for kode_bahan_baku inside a post form
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Bahan Baku</label>
<div class="col-sm-2">
<div class="input-group">
<input type="text" class="form-control" id="nama_bahan_baku" name="nama_bahan_baku" placeholder="Bahan Baku" value="" style="width:150px" required="required">
<input type="text" id="kode_bahan_baku" name="kode_bahan_baku" value="" class="form-control">
<div class="input-group-btn">
<button type="button" class="btn btn-info btn-flat" data-toggle="modal" id="btnMenu" data-target="#menuModal">
<i class="fa fa-fw fa-search"></i>
</button>
</div>
</div>
</div>
</div>
please help :(
Your controller is the go-between of your view and your model, as such, you should be grabbing the data out using $this->input->post('kode_bahan_baku') in the controller and passing those details through to the model:
Controller:
$kdbahan = $this->input->post('kode_bahan_baku');
$dbResultObj = $this->yourLoadedModel->sumqtyin($kdbahan);
then use the object $dbResultObj like: $dbResultObj->qty_in to get out the result
Model:
function sumqtyin($kdbahan){
$datenow = date("Y-m-d");
return $this->db->select('SUM(IFNULL(qty_in,0)) AS qty_in')
->where('tanggal_movement', $datenow)
->where('status_aktif', 'YES')
->where('kode_bahan_baku', $kdbahan)
->get('trans_stock_movement')
->result();
}
Please Follow the MVC structure , Before you make any manipulation on database you just have to follow the MVC method .
VIEW => CONTROLLER => MODEL => CONTROLLER => VIEW
like #Brian Ramsey did . check out the guidelines of codeigniter
https://www.codeigniter.com/user_guide/

Retrieving Id to display image using laravel

I am trying to retrieve an image from the database to be displayed in a modal for that selected user. However my attempts to display the image has proved futile. My problem is that I am unable to retrieve the id for that selected user image to be displayed. Any assistance would be GREATLY appreciated.
HTML (User list)
<table>
<tbody>
#foreach($users as $key => $u)
<tr class="id-here" data-id="{{$u->id}}">
<input type="hidden" class="avatar" value="{{$u->avatar}}">
<td class="firstname">{{$u->firstname}}</td>
<td class="lastname">{{$u->lastname}}</td>
<td class="email">{{$u->email}}</td>
<td class="project">{{$project->countProject($u->id)}}</td>
<td class="level">{{ucfirst($u->level)}}</td>
<td class="status"><span class="label label-{{$u->confirmed_email==0?'default':'success'}}">{{$u->confirmed_email==0?'unconfirmed':'confirmed'}}</span></td>
<td class="register">{{date("M j, Y g:i a", strtotime($u->created_at))}}</td>
<td>
{!!$u->level=='regular'?'<a class="btn btn-round btn-info edit get-id" title="edit" data-toggle="modal" data-target="#editModal"><i class="glyphicon glyphicon-edit"></i></a>':''!!}
<i class="glyphicon glyphicon-eye-open"></i>
{!!$u->level=='regular'?'<i class="glyphicon glyphicon-trash"></i>':''!!}
</td>
</tr>
#endforeach
</tbody>
</table>
{!! str_replace('/?', '?', $users->render()) !!}
Attempts
Attempt 1. HTML-- MODAL(Loops through data but returns all image paths)
<div class="form-group col-xs-6">
<div class="uploader pull-right">
<div class="pic-uploader">
<input id="file-1" class="edit-user-avatar" type="file" multiple="true" value='{{ROOT}}<?php
$all_users = \DB::table('users')->where('level', '=', 'regular')->get();
foreach ($all_users as $key => $value)
{
$id = $value->id;
$userImagePath = \DB::table('users')->where('id', '=', $id)->first(["avatar"]);
if(preg_match("/^https/", $userImagePath->avatar))
{
$pic = $userImagePath->avatar;
}
else
{
echo $pic = $userImagePath->avatar;
}
}
?>'>
</div>
<div style="margin-top:-40px;">
<small>File types allowed: <b>JPG</b>, <b>JPEG</b>, <b>PNG</b> or <b>GIF</b> • <b>1MB</b> file limit</small><br>
<small>At least 1024x768 pixels • 4:3 aspect ratio</small>
</div>
</div>
<input type="hidden" name="type" id="upload-type" value="user_avatar">
</div>
Attempt 2. HTML--MODAL(Stores id in hidden input but unable to retrieve the ID)
<div class="form-group col-xs-6">
<input type="hidden" name="userid" id="userid" value="<?php echo $userid = old('id')?>">
<div class="uploader pull-right">
<div class="pic-uploader">
<input id="file-1" class="edit-user-avatar" type="file" multiple="true" value='{{ROOT}}<?php
$id = $userid;
$userImagePath = \DB::table('users')->where('id', '=', $id)->first(["avatar"]);
if(preg_match("/^https/", $userImagePath))
{
$pic = $userImagePath;
}
else
{
echo $pic = $userImagePath;
}
?>'>
</div>
<div style="margin-top:-40px;">
<small>File types allowed: <b>JPG</b>, <b>JPEG</b>, <b>PNG</b> or <b>GIF</b> • <b>1MB</b> file limit</small><br>
<small>At least 1024x768 pixels • 4:3 aspect ratio</small>
</div>
</div>
<input type="hidden" name="type" id="upload-type" value="user_avatar">
</div>
JQUERY
$('.edit').click(function(){
var obj = $(this).parent().parent();
var fname = $(obj).find('.firstname').html();
var lname = $(obj).find('.lastname').html();
var status = $(obj).find('.status span').html();
var avatarImg = $(obj).find('.avatar').html();
var level = $(obj).find('.level').html().toLowerCase();
var id = $(obj).attr('data-id');
$('#edit-first-name').val(fname);
$('#edit-last-name').val(lname);
$('.edit-user-avatar').val(avatarImg);
$('#userid').val(id); // retrieves id to store in hidden input
if(status =='confirmed')
{
$('#edit-status').attr('checked','true');
}
else
{
$('#edit-status').removeAttr('checked');
}
//$('select#edit-title > option[value='+name[0].toLowerCase()+']').attr('selected','selected');
$('select#edit-level > option[value='+level+']').attr('selected','selected');
$('#uid').val(id);
$('#user-password').removeAttr('checked');
$('#user-data').attr('checked', 'checked');
$('#edit-password').css('display','none');
$('#edit-data').css('display','block');
});
Taken from the Bootstrap documentation:
$('#editModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // link that triggered the modal
var imageid = button.data('imageid') // Extract info from data-* attributes
var modal = $(this)
modal.find('.edit-user-avatar').val(imageid)
});
You'll just need to change you edit link to include the data-imageid attribute with the image ID as the value:
{!!$u->level=='regular'?'<a class="btn btn-round btn-info edit get-id" title="edit" data-imageid="{{ID GOES HERE}}" data-toggle="modal" data-target="#editModal"><i class="glyphicon glyphicon-edit"></i></a>':''!!}

Categories