I have a method where this method is discussed previously and successful but the data are entered only one when more than one can not get into the database
this is my programs
my PHP FORM :
<form class="form-horizontal" id="form-produk">
<div class="control-group" >
<label class="control-label" for="kelas">Kategori</label>
<div class="controls">
<select class='form-control' name='id_kategori'>
<?php
$tampil=mysql_query("SELECT * FROM kategori ORDER BY nama_kategori");
if ($id_kat==0){
echo "<option value=0 selected>- Pilih Kategori -</option>";
}
while($w=mysql_fetch_array($tampil)){
if ($id_kat==$w[id_kategori]){
echo "<option value=$w[id_kategori] selected>$w[nama_kategori]</option>";
}
else{
echo "<option value=$w[id_kategori]>$w[nama_kategori]</option>";
}
}?>
</select>
</div>
</div>
<div class="control-group">
<label class="control-label" for="produk">Nama Produk</label>
<div class="controls">
<?php if($id_kat > 0){
?>
<input type="text" name="editprod" class="form-control" value="<?php echo $nama_prod;?>"/>
<?php } else{
?>
<input name='add_btn' class="btn btn-primary" value='Tambah Record' id='add_btn' type='button'><br><br>
<div id='container1'></div>
<?php } ?>
</div>
</div>
</form>
<script type="text/javascript">
$(document).ready(function() {
var count = 0;
$("#add_btn").click(function() {
count++;
$('#container1').append(
'<div class="records">' + '<textarea id="' + count + '" name="' + count + '" type="text" size="100" class="form-control nma_prod"></textarea>' + '<div class="hrgini"><span class="input-group-addon">Rp</span><input style="text-align:right" id="' + count + '" name="' + count + '" class="form-control hrg_prod" type="text" placeholder="Harga Produk"><span class="input-group-addon">,00</span></div>' + '<button class="remove_item btn btn-danger" >Hapus</button>' + '<br><br></div>'
);
});
$('body').on('click', ".remove_item", function(ev) {
$(this).parents(".records").fadeOut();
$(this).parents(".records").remove();
});
});
</script>
my javascript :
$("#simpan-produk").bind("click", function(event) {
var url = "pages/produk/produk.input.php";
var data =[];
$('.records').each(function(index, item) {
var nma_prod = $(item).find('.nma_prod').val();
var hrg_prod = $(item).find('.hrg_prod').val();
data.push({
kat_prod: v_kat,
nma_prod: nma_prod,
hrg_prod: hrg_prod
});
});
var v_kat = $('select[name=id_kategori]').val();
// mengirimkan data ke berkas transaksi.input.php untuk di proses
$.post(url, {
data: JSON.stringify(data), kat: v_kat, id: id_produk
}, function() {
// tampilkan data mahasiswa yang sudah di perbaharui
// ke dalam <div id="data-mahasiswa"></div>
$(".msg").html("<div class='alert alert-success alert-dismissable' id='alerts'> Data Sukses di Simpan</div>");
$(".msg").fadeIn(3500);
$(".msg").show();
$(".msg").fadeOut(5500);
$("#data-produk").load(main);
// sembunyikan modal dialog
$('#myModal').modal('hide');
// kembalikan judul modal dialog
$("#myModalLabel").html("Tambah Data produk");
});
});
my PHP Process :
$data = $_REQUEST['data'];
$data = json_decode($data, true);
$query = '';
foreach($data as $item ){
$kat= $item['kat_prod'];
$nma_prod = $item['nma_prod'];
$hrg_prod = $item['hrg_prod'];
$query .="INSERT INTO `produk` VALUES('','$_POST[kat]','$nma_prod','$hrg_prod')";
}
if ($query) {
$exec = mysql_query($query);
if ($exec) {
echo json_encode(array('msg' => 'Data inserted successfully!'));
exit;
} else {
echo json_encode(array('msg' => 'Something went wrong!'));
exit;
}
} else {
echo json_encode(array('msg' => 'Nothing to Insert!'));
exit;
}
this method work's with one data but not with multiple data ? any suggestion please ?
You should use single quote around the variables. I.E. it should be like this-
echo "<option value='{$w[id_kategori]}' selected>'{$w[nama_kategori]}'</option>";
You seem to concatenate several INSERT
statements one after another. This doesn't work with mysql_query()
. You'd better send the INSERT
s individually. Even if you'd try this in a mysql console, you'd at least have to separate the statements with semicolons.
The mysql_
-type functions are deprecated, by the way. They will disappear in the next PHP version (7). They are also vulnerable to SQL-injection and shouldn't be used for security reasons. Consider to switch to mysqli or PDO for your database access.
Try this:
$data = $_REQUEST['data'];
$data = json_decode($data, true);
$query = '';
foreach($data as $item ){
$kat= $item['kat_prod'];
$nma_prod = $item['nma_prod'];
$hrg_prod = $item['hrg_prod'];
$query = "INSERT INTO `produk` VALUES('','$_POST[kat]','$nma_prod','$hrg_prod')";
if ($query) {
$exec = mysql_query($query);
if ($exec) {
$out = json_encode(array('msg' => 'Data inserted successfully!'));
} else {
die( json_encode(array('msg' => 'Something went wrong!')) );
}
} else {
die( json_encode(array('msg' => 'Nothing to Insert!')) );
}
}
echo $out;
To execute multi-statements as the original code is trying to do perhaps mysqli_multi_query
would be the best solution. This does, of course, mean that you would need to create the db connection using mysqli
rather than mysql
functions/methods.
/* mysqli_multi_query example */
$data = $_REQUEST['data'];
$data = json_decode($data, true);
$query = '';
foreach( $data as $item ){
$kat= $item['kat_prod'];
$nma_prod = $item['nma_prod'];
$hrg_prod = $item['hrg_prod'];
$kat = $_POST['kat'];
/* string concatenation, terminate each with semi-colon */
$query .= "INSERT INTO `produk` VALUES ( '', '{$kat}', '{$nma_prod}', '{$hrg_prod}' );";
}
if( $query ) {
$exec = mysqli_multi_query( $conn, $query );
if( $exec ) {
exit( json_encode( array( 'msg' => 'Data inserted successfully!') ) );
} else {
exit( json_encode( array( 'msg' => 'Something went wrong!') ) );
}
} else {
exit( json_encode( array( 'msg' => 'Nothing to Insert!') ) );
}
Alternatively you could continue using mysql_query
( though it is highly discouraged these days because of sql injection ) and execute each query in the first loop that process the array or in a separate loop like this.
$data = isset( $_REQUEST['data'], $_POST['kat'] ) ? $_REQUEST['data'] : false;
if( $data ){
$data = json_decode( $data, true );
$query = array();
foreach( $data as $item ){
$kat= $item['kat_prod'];
$nma_prod = $item['nma_prod'];
$hrg_prod = $item['hrg_prod'];
$kat = strip_tags( trim( $_POST['kat'] ) );
$query[]="INSERT INTO `produk` VALUES ( '', '{$kat}', '{$nma_prod}', '{$hrg_prod}' );";
}
if( !empty( $query ) ) {
$msgs=array('msg'=>'multiple messages');
foreach( $query as $i => $sql ){
$res = mysql_query( $sql, $conn );
$msgs[ 'stmt'.$i ]=$res ? 'Data inserted successfully!' : 'Something went wrong!';
}
exit( json_encode( $msgs ) );
} else {
exit( json_encode( array( 'msg' => 'Nothing to Insert!') ) );
}
mysql_close( $conn );
}
mysqli
and it's associated methods offer better protection against sql injection when you use prepared statements - there are lots of articles on StackOverflow from which to choose.