Insert multiple row from php page into mysql - php

This problem's driving me crazy since yesterday. I have a table consist of 5 columns: kode_barang (item ID), nama_barang (name of item), qty (quantity), harga_beli (price), jumlah (total). User can input 2 items. This is the code of the form:
<HTML>
<?php include "koneksi.php"; ?>
<form action="insert3.php" method="POST">
<table id="theTable" border="1">
<thead>
<tr>
<th> Kode Barang </th>
<th> Nama Barang </th>
<th> Qty </th>
<th> Harga Beli </th>
<th> Jumlah </th>
<tr>
</thead>
<tbody>
<tr>
<td type="text" name="kode_barang" id="kode_barang1"/readonly>
<?php
mysql_connect("localhost","root","");
mysql_select_db("skripsi_1");
$result = mysql_query("select * from input_data_barang");
$met = "var kode_barang = new Array();\n";
echo '<select name="kode_barang" onchange="changeValue1(this.value)">';
echo '<option></option>';
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['kode_barang'] . '">' . $row['kode_barang'] . '</option>';
$met .= "kode_barang['" . $row['kode_barang'] . "'] = {name:'" . addslashes($row['nama_barang']) . "',desc:'".addslashes($row['nama_barang'])."'};\n";
}
echo '</select>';
?>
</td>
<td><input type="text" name="nama_barang" id="nama_barang1"/readonly>
<script type="text/javascript">
<?php echo $met; ?>
function changeValue1(id){
document.getElementById('kode_barang1').value = kode_barang[id].name;
document.getElementById('nama_barang1').value = kode_barang[id].desc;
};
</script>
</td>
<td><input class="valOne" type="text" name="qty"></td>
<td><input class="valTwo" type="text" name="harga_beli"></td>
<td><input class="result" type="text" name="jumlah"></td>
</tr>
<tr>
<td type="text" name="kode_barang" id="kode_barang2"/readonly>
<?php
mysql_connect("localhost","root","");
mysql_select_db("skripsi_1");
$result = mysql_query("select * from input_data_barang");
$jsArray = "var kode_barang = new Array();\n";
echo '<select name="kode_barang" onchange="changeValue2(this.value)">';
echo '<option></option>';
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['kode_barang'] . '">' . $row['kode_barang'] . '</option>';
$jsArray .= "kode_barang['" . $row['kode_barang'] . "'] = {name:'" . addslashes($row['nama_barang']) . "',desc:'".addslashes($row['nama_barang'])."'};\n";
}
echo '</select>';
?>
</td>
<td><input type="text" name="nama_barang" id="nama_barang2"/readonly>
<script type="text/javascript">
<?php echo $jsArray; ?>
function changeValue2(id){
document.getElementById('kode_barang2').value = kode_barang[id].name;
document.getElementById('nama_barang2').value = kode_barang[id].desc;
};
</script>
</td>
<td><input class="valOne" type="text" name="qty"></td>
<td><input class="valTwo" type="text" name="harga_beli"></td>
<td><input class="result" type="text" name="jumlah"></td>
</tr>
<script>
document.getElementById("theTable").addEventListener("input", function(e) {
var row = e.target.parentNode.parentNode
var val1 = row.querySelector(".valOne").value
var val2 = row.querySelector(".valTwo").value
row.querySelector(".result").value = val1 * val2
})
</script>
</tbody>
<td><input type="submit" value="OK"></a>
<input type="reset" value="Reset"></td>
</table>
</form>
</HTML>
And this is the connection to my database:
<?php
include "koneksi.php";
$kode_barang=$_POST['kode_barang'];
$nama_barang=$_POST['nama_barang'];
$qty=$_POST['qty'];
$harga_beli=$_POST['harga_beli'];
$jumlah=$_POST['jumlah'];
$query ="INSERT INTO faktur (kode_barang, nama_barang, qty, harga_beli, jumlah) VALUES ('".$kode_barang."', '".$nama_barang."', '".$qty."', '".$harga_beli."', '".$jumlah."'), ('".$kode_barang."', '".$nama_barang."', '".$qty."', '".$harga_beli."', '".$jumlah."')";
$sql =mysqli_query($connect, $query);
if ($sql){
header ("location: faktur.php");
}else{
echo "Error.";
echo "<br><a href='input_faktur.php'>Back</a>";
}
?>
Notice that my 'Kode Barang' is a dropdown option, and everytime a user click an item ID, name of the item will be shown automatically in 'Nama Barang' column. Everything in this page works perfectly.
But, when I saved it to database, it didn't save both of the items (item in the first row and the second row). Database only saved the second item but saved it twice. When I add a row to the table become 3 rows, database only save the third item and save it three times. When I add [] to the name, like name=kode_barang[], database didn't save the item ID, but only show "Array" text.
Would anybody please help me with this? Thanks.

You are using the same name for both your fields
use a array
name="nama_barang[]" and name="kode_barang[]"
do a loop in the php to save each field individually

Related

selectbox inserting values multiple times

<?php
require '../common/connect-db.php';
require_once 'admin-template.php';
?>
<form id="form1" name="form1" method="post" action="test.php">
<?php
// add button
if(isset($_POST['add_dayoff'])) {
$AddQuery = "INSERT INTO dayoff (fname,lname,datef)
VALUES ('$_POST[select1]')";
mysqli_query($db,$AddQuery);
};
?>
<?php
$query="SELECT DISTINCT fname, lname FROM employees";
$result = $db->query($query);
?>
<table><caption>Dayoff Table</caption>
<tr>
<th>First Name</th>
<th>Employee Dayoff</th>
</tr>
<tr>
<td><select name="select1" id="select1" >
<?php
echo '<option value="">Please select...</option>';
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['fname'] . $row['lname'] . "'>" . $row['fname'] ." ". $row['lname'] . "</option>";
}
?>
<td><input type="date" name="date" required /></td>
</select></td>
<td><input type="submit" name="add_dayoff" /></td>
</tr>
</table>
the primary key is email in employees table, i know it's not a secure way to do it, and i should use prepare statements, but it's just a small project. 'dayoff' has an auto incremented int 'id' as primary key.
So what happens is that all records are inserted more than once. And some records fname and lname are concatenated and stored in fname in dayoff table
You have syntax error
INSERT INTO dayoff (fname,lname,datef) VALUES ($_POST[select1]).$_POST[select1] will contains fnamelname.
Moreover you didn't get date value ie:$_post['date']. Try this and let me know the result
<?php
require_once 'admin-template.php';
?>
<form id="form1" name="form1" method="post" action="test.php">
<?php
// add button
if(isset($_POST['add_dayoff'])) {
$fname=$_POST['select1'];// get the value which stores firstname-lastname
$n=explode('-',$fname);//explode the value with -
$datef=$_POST['date'];
$AddQuery = "INSERT INTO dayoff (fname,lname,datef) VALUES ('$n[0]','$n[1]',$datef)";// query should be like this
mysqli_query($db,$AddQuery);
};
?>
<?php
$query="SELECT DISTINCT fname, lname FROM employees";
$result = $db->query($query);
?>
<table><caption>Dayoff Table</caption>
<tr>
<th>First Name</th>
<th>Employee Dayoff</th>
</tr>
<tr>
<td><select name="select1" id="select1" >
<?php
echo '<option value="">Please select...</option>';
while ($row = mysqli_fetch_array($result)) {
echo "<option value='". $row['fname']."-".$row['lname'] . "'>" . $row['fname'] ." ". $row['lname'] . "</option>";
}
?>
<td><input type="date" name="date" required /></td>
</select></td>
<td><input type="submit" name="add_dayoff" /></td>
</tr>
</table>

How to populate a textbox with the appropriate information related to the item selected from a drop down list in PHP?

I'm creating a form where it allows a user to enter in the number of product rows they would like to have in the form. Then with the corresponding rows, you can select the Product with the Product_ID & Product_Name from a Drop Down List. With the selected item, it should pull the Product_Cost from the table and populate the Unit Price textbox. I can't seem to get the textbox to populate with the correct data. My if statement if (isset($_POST['product' . $i])){ doesn't seem to be working properly, it runs as if the statement were false. I'm trying to say "If a select box has an option selected, take the option selected and find it's corresponding row in the database and take the price found in that row for that product and populate the unit price textbox."
<? require_once("connect_to_DB.php"); //inserts contents of this file here ?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Order Form</title>
<meta charset="utf-8">
</head>
<body>
<?
connectDB();
$sql = "SELECT * FROM product";
$sql2 = "SELECT DISTINCT emp_id, emp_fname, emp_lname FROM employee";
$sql3 = "SELECT DISTINCT status_id FROM salesorder ORDER BY status_id asc";
$sql4 = "SELECT * FROM salesorder ORDER BY order_id desc";
$result = mysqli_query($db, $sql) or die("SQL error: " . mysqli_error());
$result2 = mysqli_query($db, $sql2) or die("SQL error: " . mysqli_error());
$result3 = mysqli_query($db, $sql3) or die("SQL error: " . mysqli_error());
$result4 = mysqli_query($db, $sql4) or die("SQL error: " . mysqli_error());
//This is for the options in the product list box
$options = '<option value="selectProduct">Select Product</option>';
while($row = mysqli_fetch_array($result,MYSQLI_NUM)){
$options .= '<option value="' . $row[0] . '">' . $row[0] . ' - ' . $row[2] . '</option>';
}
$row2 = mysqli_fetch_array($result2);
$row3 = mysqli_fetch_array($result3);
$row4 = mysqli_fetch_array($result4);
?>
<div id="order-wrap">
<form method="post" action="example.php">
<table class="orderInfo"><br>
<tr>
<th class="textCol">Product Rows:</th>
<td class="inputCol"><input type="text" name="rows"></td>
<td><input class="update" type="submit" name="update" value="Update"></td>
<td class="inputCol"></td>
</tr>
</table>
</form><!-- Order Rows -->
<form class="orderform" action ="order-report.php" METHOD = "post">
<h2>Order Form</h2>
</table>
<!-- Where the product rows input show go ??? -->
<table class="bottomTable">
<tr>
<th class="textCol">Product</th>
<th class="textCol">Quantity</th>
<th class="textCol">Unit Price</th>
<th class="textCol">Total Price</th>
</tr>
<?
if (isset($_POST['update']))
{
//Execute this code if the update button is clicked.
$num = $_POST['rows'];
for ($i=0; $i<$num; $i++) { ?>
<tr>
<td class="inputCol2">
<select name="'product<?= $i ?>'">
<?
echo $options;
?>
</select>
</td>
<td class="inputCol2"><input type="text" name="'quantity<?= $i ?>'" ></td>
<? if (isset($_POST['product' . $i])){ ?>
<td class="inputCol2"><input type="text" name="'unit<?= $i ?>'" value="<?= $row[3] ?>" placeholder="$" ></td>
<? } else { ?>
<td class="inputCol2"><input type="text" name="'unit<?= $i ?>'" value="" placeholder="$"></td>
<? } ?>
<td class="inputCol2"><input type="text" name="'total<?= $i ?>'" placeholder="$"></td>
</tr>
<? } ?>
<tr>
<td class="textCol"></td>
<td class="textCol"></td>
<td class="textCol">Total Order:</td>
<td class="inputCol2"><input type="text" name="totalfinal" placeholder="$"></td>
</tr>
</table>
<input class="submit" type="submit" value="Submit" name="orderSubmit"/>
</form>
<? } else {?>
<tr>
<td class="textCol"></td>
<td class="textCol"></td>
<td class="textCol">Total Order:</td>
<td class="inputCol2">$<input type="text" name="totalfinal"></td>
</tr>
</table>
<input class="submit" type="submit" value="Submit" name="orderSubmit"/>
</form>
<? } ?>
<?
mysqli_free_result($result);
mysqli_free_result($result2);
mysqli_free_result($result3);
mysqli_free_result($result4);
mysqli_close($db);
?>
</div>
</body>
There appear to be some syntax errors in there, for instance:
<select name="'product<?= $i ?>'">
<?
echo $options;
?>
</select>
There seems to be several instances where this type of quotation marks are used - I think they ought to be more like:
<select name="product<?= $i ?>">
<?
echo $options;
?>
</select>
Also, in a few places you are not using the correct opening tag for the php blocks though someone might point out different. Generally they ought to be:
<?php
/* statements */
?>
or
<?="print out this string";?>

Select row with radio and update table

I have a table with select row with radio button and when click button, the status updated in mysql table but when I click the button, the last user updated and other user not.
<form method="post" accept-charset="utf-8" name="frmUser" >
<table>
<thead>
<tr>
<th>Status</th>
</tr>
</thead>
<tbody>
<?php
$qr=$mysqli->query("SELECT * FROM `user`");
while($row=$qr->fetch_object()){
?>
<tr>
<td><input type="radio" name="users[]" value="<?php echo $row->id; ?>">
</input></td>
<td class="blck min"><?php echo $row->status; ?></td>
<td><span>
<input type="submit" value="" id="st" name="st">
<?php
if(isset($_POST['st'])){
$rowCount = count($_POST["users"]);
for($i=0;$i<$rowCount;$i++) {
if($row->status == 'ENABLE'){
$mysqli->query("UPDATE `user` SET `status`='DISABLE' WHERE `id`='" . $_POST["users"][$i] . "'");
}
else{
$mysqli->query("UPDATE `user` SET `status`='ENABLE' WHERE `id`='" . $_POST["users"][$i] . "'");
}
}
header("location:users.php");
}
?>
</span></td>
</tr>
<?php}?>
</tbody>
</table>
</form>
Please place below line and check how much count is display:
$rowCount = count($_POST["users"]);
print('<pre>COUNT :: ' . $rowCount . ' >> ');
print_r($_POST["users"]);
print('</pre>');exit;
Above code just display your count value only.
Let me know for more help.!

pull the data from mysqli to dropdown list php

I have been trying to pull the data from database mysqli in the drop down menu. Here is my code for postad.html. I want to pull categories data from categories table with a row name CatName. I also have CatId that shows ctegory id. Thank you in advance.Please help:
<html>
<head>
<title>Post AD</title>
</head>
<body>
<form method="POST" action="postad.php">
<table>
<tr>
<td>AdName:</td>
<td><input type="text" name="adname"></td>
</tr>
<tr>
<td>AdCategory</td>
<td>
//dropdown list
<select name="Categories">
<?php include = connect.php
$sql = "SELECT CatName FROM categories order by CatName";
$result = $db->query($sql);
while($row = $result->fetch_array()) {
echo "<option value='". $row['CatName']."'>."</option>';
}
?>
</select>
</td>
</tr>
<tr>
<td>Contact Number</td>
<td><input type="text" name="contactnumber"></td>
</tr>
<tr>
<td>Image</td>
<td><input type="text" name="image"></td>
</tr>
<tr>
<td>Description</td>
<td><input type="text" name="description"></td>
</tr>
<tr>
<td>Expiration Date</td>
<td><input type="text" name="expirationdate"></td>
</tr>
<tr>
<td id="btn"><input type="submit" value='submit' name="submit"></td>
</tr>
</table>
</form>
</body>
</html>
Looks like you have an error with your menu code. Should be this
echo "<option value=". $row['CatName'] ."></option>';
Opposed to
echo "<option value='". $row['CatName']."'>."</option>';
The result from the table is going to be a string regardless so there is no need to worry about value=''. The real problem was how you muffled up your quotes.
EDIT: Just noticed include = connect.php should be include 'connect.php';
<?php
$mysql_host = '';
$mysql_user = '';
$mysql_pass = '';
$mysql_dbase = '';
$mysql_table = '';
$pdo = new PDO('mysql:host=' . $mysql_host . ';dbname=' . $mysql_dbase, $mysql_user, $mysql_pass);
$sth = $pdo->prepare('SELECT * FROM `' . $mysql_table . '` ORDER BY `id` CatName');
$sth->execute();
$result = $sth->fetchAll();
foreach ($result as $row) {?>
<option value=<?php echo $row['CatName']; ?>></option>;
<?}?>
echo "<option value='". $row['CatName']."'>."</option>';
contains error and also there is no inner html for options
You can use this way for simplicity.
$CatName=$row["CatName"];
echo '<option value="'.$CatName.'">'.$CatName.'</option>';
Ok. Now I have created a new php file called getcategories.php. and this page works well. Here is the code for it:
$sql = "SELECT CatName FROM categories order by CatName";
$result = $db->query($sql);
$options="";
//echo "<select value='categories'>";
while($row = $result->fetch_assoc()) {
$categoryname=$row["CatName"];
// echo '<option value="'.$categoryname.'">'.$categoryname.'</option>';
// echo "</select>";
//echo "$categoryname\n";
$options .= '<option value="'.$categoryname.'">'.$categoryname.'</option>';
}
?>
How should I pull the data of options to the dropdown of html file

how to display two row of database value in textfield when user select one value from drop down list

When a user select the name using drop down list,the stock and price text field should automatically be filled.But it wont.
This is the code
<form action="insertout.php" method="post">
<center>
<table>
<tr>
<td width="116">Medicine name</td>
<td width="221">
<center>:
<select name="name" id="name">
<option>--- Choose Medicine ---</option>
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("arie");
$sql = mysql_query("SELECT * FROM tabelmedicine ORDER BY name ASC ");
if(mysql_num_rows($sql) != 0){
while($row = mysql_fetch_assoc($sql)){
echo '<option value="'.$row['price'].' && '.$row['price'].'">'.$row['name'].'</option>';
}
}
?>
</select >
</center>
</p>
</td>
</tr>
<tr>
<td>
<p>Price</p>
</td>
<td>
<p align="center">:<input type="text" name="price" id="price"value="<?php echo ('priceperunit'); ?>" onClick="checkprice()">
</p>
</td>
</tr>
<tr>
<td>
<p>Stock</p>
</td>
<td>
<p align="center">:<input type="text" name="stock" id="stock"value="<?php echo ('stock'); ?>" onClick="checkprice()">
</p>
</td>
</tr>
<script>
var select = document.getElementById('name');
var input = document.getElementById('price');
var input = document.getElementById('stock');
select.onchange = function(){
input.value = select.value;
}
</script>
i hope u guys can help.i've spent a week just to figured out the code.
Try this below code, below are some notes
Avoid using the Keywords like "name" in select box
Price and Stock Input element attribute are does not have spaced properly.
Avoid using Mysql_connect and start use PDO / MySQLi
Avoid presentational tags and start use css to acheive it like "text-align:center"
Currently its working as you expected without Ajax and its a quick workaround, I have added the value in a comma separated the both value by split function.
<form action="insertout.php" method="post">
<center>
<table>
<tr>
<td width="116">Medicine name</td>
<td width="221">
<center>:
<select name="name" id="name">
<option>--- Choose Medicine ---</option>
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("arie");
$sql = mysql_query("SELECT * FROM tabelmedicine ORDER BY name ASC ");
if(mysql_num_rows($sql) != 0){
while($row = mysql_fetch_assoc($sql)){
// echo '<option value="'.$row['price'].' && '.$row['price'].'">'.$row['name'].'</option>';
$option_value = $row['price'] . ',' . $row['stock'];
echo '<option value="'.$option_value.'">'.$row['name'].'</option>';
}
}
?>
</select >
</center>
</p>
</td>
</tr>
<tr>
<td>
<p>Price</p>
</td>
<td>
<p align="center">:<input type="text" name="price" id="price"value="<?php echo ('priceperunit'); ?>" onClick="checkprice()">
</p>
</td>
</tr>
<tr>
<td>
<p>Stock</p>
</td>
<td>
<p align="center">:<input type="text" name="stock" id="stock"value="<?php echo ('stock'); ?>" onClick="checkprice()">
</p>
</td>
</tr>
<script>
var select = document.getElementById('name');
//var input = document.getElementById('price');
//var input = document.getElementById('stock');
var price = document.getElementById('price');
var stock = document.getElementById('stock');
select.onchange = function(){
// input.value = select.value;
var price_stock = select.value.split(',');
price.value = price_stock[0];
stock.value = price_stock[1];
}
</script>
How about this.......
Main File
<?php
$medOptions = "";
mysql_connect( "localhost", "root", "");
mysql_select_db( "arie");
$sql = mysql_query( "SELECT * FROM tabelmedicine ORDER BY name ASC ");
if(mysql_num_rows($sql) !=0 ) {
while($row = mysql_fetch_assoc($sql)) {
$medOptions .= '<option value="' . $row['id'] . '">' . $row['name'] . '</option>\n';
}
}
?>
<form>
<table>
<tr>
<td class="label" width="55%">Medicine name</td>
<td width="45%">
<select name="med" id="med">
<option disabled="true" selected="true">--- Choose Medicine ---</option>
<?=$medOptions;?>
</select>
</td>
</tr>
<tr>
<td class="label">Price</td>
<td><input type="text" id="price" readonly="true" /></td>
</tr>
<tr>
<td class="label">Stock</td>
<td><input type="text" id="stock" readonly="true" /></td>
</tr>
</table>
CSS
table {
margin: 0 auto;
}
td {
text-align:center;
}
.label {
font-weight:bold;
}
Javascript
var select = document.getElementById('med');
// INSERT AJAX ROUTINE TO RETRIEVE PRICE AND STOCK LEVEL
var medPrice = document.getElementById('price');
var medStock = document.getElementById('stock');
select.onchange = function () {
medPrice.value = response.price;
medStock.value = response.stock;
};

Categories