How do I insert data from a form into multiple tables? - php

How do I insert data from a form into multiple tables? This is what I have so far :
<?php
require 'db/connect.php';
$Apple = trim($_POST['Apple']);
$Orange = trim($_POST['Orange']);
$Banana = trim($_POST['Banana']);
if (empty($Apple) && empty($Orange) && empty($Banana)){
$error = "Please pick your fruits";
} else {
$insert = $db->prepare("INSERT INTO fruits (Apple, Orange, Banana) Values (?,?,?)");
$insert->bind_param("sss", $Apple, $Orange, $Banana);
?>
//HTML SECTION
<form action="" method="post">
<table>
<tr>
<td><label for="Apple">Apples :</label></td>
<td><input type="text" id="Apple" name="Apple"></td>
</tr>
<tr>
<td><label for="Orange">Oranges:</label></td>
<td><input type="text" id="Orange" name="Orange"></td>
</tr>
<tr>
<td><label for="Banana">Bananas:</label></td>
<td><input type="text" id="Banana" name="Banana"></td>
</tr>
<td>
<button type="submit" class="create" name="create">CREATE</button>
<a class="btn" href="index.php">BACK</a>
</td>
</tr>
</table>
What I would like to do is this - within the form, have another field (say tomatoes), that when the user clicks "submit", apple / orange / banana goes to the fruits table, and "tomato" goes to the "vegetables" table.
Does anyone know how to achieve this?

Here is what I finally came up with, I made the mistake of misplacing the binding code for "Tomato". One thing that I am still confused about, and am unsure about how to approach, is how I can make it to where when I click on a form field for the below example, it will populate a popup that shows current contents of the database, and allow you to copy contents of that popup(item) to the form field if needed. Another example would be a customers and products table, you make a form field to take a customer and a product, when you click on "product" form field, it populates with all products, and allows you to click on one of the populated products to assign to that customer.
<?php
require 'db/connect.php';
$Apple = trim($_POST['Apple']);
$Orange = trim($_POST['Orange']);
$Banana = trim($_POST['Banana']);
$Tomato= trim($_POST['Tomato']);
if (empty($Apple) && empty($Orange) && empty($Banana) && empty($Tomato)){
$error = "Please pick your fruits";
} else {
$insert = $db->prepare("INSERT INTO fruits (Apple, Orange, Banana) Values (?,?,?)");
$insert->bind_param("sss", $Apple, $Orange, $Banana);
$insert = $db->prepare("INSERT INTO veggies(Tomato) Values (?)");
$insert->bind_param("s", $Tomato);
?>
//HTML SECTION
<form action="" method="post">
<table>
<tr>
<td><label for="Apple">Apples :</label></td>
<td><input type="text" id="Apple" name="Apple"></td>
</tr>
<tr>
<td><label for="Orange">Oranges:</label></td>
<td><input type="text" id="Orange" name="Orange"></td>
</tr>
<tr>
<td><label for="Banana">Bananas:</label></td>
<td><input type="text" id="Banana" name="Banana"></td>
</tr>
<td>
<button type="submit" class="create" name="create">CREATE</button>
<a class="btn" href="index.php">BACK</a>
</td>
</tr>
</table>

Related

Cant input data to database with PDO

im trying to input data to database with PDO,i make a form for users to input,so forminput -> inputprocess.
But i cant input coz when i press submit its going to proses_input.php and show blank page.
I try to write the code in 1 file but when i press submit it show the input form again.
Here is my form_input.php
<form method="POST" action="proses_input.php">
<table>
<tr>
<td>Nama</td>
<td> : </td>
<td>
<input type="text" name="nama" required>
</td>
</tr>
<tr>
<td>No. Pegawai</td>
<td> : </td>
<td>
<input type="text" name="no_pegawai" required>
</td>
</tr>
<tr>
<td>Bagian</td>
<td> : </td>
<td>
<input type="text" name="bagian">
</td>
</tr>
<tr>
<td>Jabatan</td>
<td> : </td>
<td>
<input type="text" name="jabatan">
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
<button type="submit" value="submit">Input</button>
</td>
</tr>
</table>
</form>
and here is my proses_input.php
<?php
include_once "connect.php";
if (isset($_POST["submit"])) {
$no_pegawai = $_POST['no_pegawai'];
$nama = $_POST['nama'];
$bagian = $_POST['bagian'];
$jabatan = $_POST['jabatan'];
try { //KONDISI
$sql = "INSERT INTO phonebook (no_pegawai, nama, bagian, jabatan)
VALUES (:no_pegawai, :nama, :bagian, :jabatan)";
$input = $conn->prepare($sql);
$input->bindparam(':no_pegawai', $no_pegawai);
$input->bindparam(':nama', $nama);
$input->bindparam(':bagian', $bagian);
$input->bindparam(':jabatan', $jabatan);
$input->execute();
header('location: admin.php');
} catch (PDOException $e) {
echo $e->getMessage();
}
}
?>
IDK why but everytime i input data to my form,its always stuck on proses_input.php with blank page.i already try to put it in one php file but still not works. Pls help me,thanks
As mentioned above you haven't named your button, therefore it won't match the condition isset($_POST["submit"]) because there is no field named "submit" in your $_POST array. Also worth noting that you should not rely on users input. I saw that you are using parameterized query which is nice but don't forget to escape these values when displaying them on the UI to avoid XSS vulnerabilities.

Change textbox based on select

I'm trying to develop a little project and I got a little problem
I'm making a PHP page connected to a MySQL Server. I have a page where only the administrator have access and that page allows him to change users information.
So, I have a select that show all usernames on website and 3 textbox where can be inserted the First Name, Last Name and e-mail.
My database update successfully, but what i'm trying to do is when is select a username on select the 3 textbook auto fill with that username information.
Here is an image that explains better what I would like to do.
Sorry for my english and thanks to all
http://s3.postimg.org/da9srvh5f/table_copy.jpg
<script type="text/javascript">
function reload() {
var val=document.getElementById("c-name").value;
self.location="your_url.php?name=" + val ;
//alert(val);
}
</script>
<form name="data" action="your_url.php" method="post">
<table id="tbl">
<tr>
<td>Name </td>
<td>
<select id="c-name" name="name" onChange="reload()" style="width:340px;">
<option value="">Select Name</option>
<option value="abc">ABC</option>
<option value="xyz">XYZ</option>
<option value="mno">MNO</option>
</select>
</td>
</tr>
<?php
if(isset($_GET['name'])){
$name = $_GET['name'];
$SQL_Data = "select * from client_data where cname = '".$name."'";
$result = mysqli_query($SQL_Data);
while($details = mysqli_fetch_array($result)) {
?>
<tr>
<td>First Name</td>
<td><input type="text" name="fname" class="c1" value="<?=$details['fname']?>" /></td>
</tr>
<tr>
<td>Last Name</td>
<td><input type="text" class="c7" name="lname" value="<?=$details['lname']?>" /></td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" class="c7" name="uname" value="<?=$details['uname']?>" /></td>
</tr>
<?php
} }
?>
<tr><td align="center" colspan="2"><input type="submit" name="submit" value="Submit" /></tr>
</table>
</form>
You could have your PHP backend return JSON data to your frontend. Then, with javascript, do something like:
document.getElementsById('ID').Value = VALUE;
Where ID is the Id of your select and VALUE is the value found in your JSON data.
Alternatively, you could do this purely in PHP/MySQL.

PHP post two values in one field, one of which is hidden

Is there a way that I can post two values at the same time from a single field in a table but hide one from the user?
I would like the following form to post the values ID and reason_name when it is submitted but have the user only be able to see (and edit in the text box) the reason_name.
<form name="add_positioning" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<table border="1" class="autoTable_pos">
<tr>
<td>Positioning</td><td> </td></tr>
<?
$sql= "SELECT * FROM gradeReason WHERE reason_userID = $user_id AND category = 'positioning' AND current = 1";
$result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
while($row = mysqli_fetch_array($result)){?>
<tr>
<td>
<input type="text" name="reason[]" size="25" value="<? echo $row['reason_name']; ?>"/>
</td>
<td>
<input type="button" value="Delete" class="delRow_pos"/>
</td>
</tr>
<?
}
?>
<tr>
<td>
<input type="text" name="reason[]" size="25"/>
</td>
<td>
<input type="button" value="Delete" class="delRow_pos"/>
</td>
</tr>
<tr>
<td colspan="2" align="right">
<input type="submit" value="Save" name="save_reasons"/>
</td>
</tr>
</table>
</form>
The form POST action so far (basic echo at the moment for my own sanity to check that it posts the values correctly, which it does...)
if(isset($_POST['save_reasons'])) {
foreach($_POST['reason'] as $item) {
echo $item.'<br/>';
}
}
This table displays the values that are held in a database but enables the user to add more values by dynamically adding a new row (using JQUERY I haven't included) to the table when they type in an empty one at the bottom and also allows them to edit or delete existing values.
For each value posted I intend to check if the ID value is empty, if it is it means that it is a new value and enter a new record into the database, if it isn't update the existing record in the database with the corresponding ID. I don't have a problem writing that bit, I just can't think how to get the ID value posted as well as the reason_name while keeping ID hidden from the user.
Add the ID to the name attribute of the Text boxes of the reasons loaded from the DB. Leave the other Text boxes added using JQ without the ID.
E.g.
Text box which shows the existing reason loaded from the DB
<input type="text" name="reason[][ID]" size="25"/>
Text box added with JQ
<input type="text" name="reason[]" size="25"/>
Then once you submit the form you get you will get the following array.
array
'reason' =>
array
0 =>
array
14 => string 'VAL1' (length=4)
1 => string 'VAL2' (length=5)
By checking for an array in the each element in the "reason" array, you can differentiate two type of Text Boxes.
Here is the complete code I have tested.
<?PHP
//var_dump($_POST);
foreach($_POST['reason'] as $item=>$value)
{
if(is_array($value)){
foreach($value as $ID=>$reason)
{
echo "Existing Reason : ".$ID." - ".$reason."<br>";
}
}
else{
echo "New Reason : ".$item." - ".$value.'<br/>';
}
}
?>
<form action="" method="POST">
<input type="text" name="reason[][14]" size="25" value="aaaa"/>
<input type="text" name="reason[]" size="25" value="bbbbb"/>
<input name="" type="submit">
</form>
Assuming the id is at $row['reason_id'] I think you want:
$i = 0;
while($row = mysqli_fetch_array($result)){?>
<tr>
<td>
<input type="hidden" name="reason_id[<? echo $i; ?>]" size="25" value="<? echo $row['reason_id']; ?>"/>
<input type="text" name="reason[<? echo $i; ?>]" size="25" value="<? echo $row['reason_name']; ?>"/>
</td>
<td>
<input type="button" value="Delete" class="delRow_pos"/></td></tr>
<? $i++ } ?>
This way you can later
if(isset($_POST['save_reasons'])) {
foreach($_POST['reason'] as $key => $item) {
$id = $_POST['reason_id'][$key];
echo $id . " " . $item.'<br/>';
}
}

Can't figure out foreach loop

How can I use foreach to insert multiple data in my database. I have a drop-down menu from my form that will be used to add and delete rows by js function. I would like to insert data from the new row (added in the form) into my database.
This is my form:
<form action="insert.php" method="POST">
<input type="button" value="Add Row" onClick="addRow('tableID')"/>
<input type="button" value="Delete Row"
onClick="deleteRow('tableID')"/>
<table class="table" bgcolor="#CCCCCC">
<thead>
<tr>
<td></td>
<td><center>Item Description</center></td>
<td><center>Price (RM)</center></td>
<td><center>Month</center></td>
<td><center>Amount (RM)</center></td>
</tr>
</thead>
<tbody id="tableID">
<tr>
<td><input type="checkbox" name="chk"></td>
<td>
<select name="item_description">
<option value="deposit">Deposit</option>
<option value="rental">Rental</option>
<option value="stamp">Stamp Duty</option>
<option value="process">Process Fee</option>
<option value="ap">AP</option>
</select>
</td>
<td><input id="price" name="price" type="text"></td>
<td><input id="month" name="qty" type="text"></td>
<td><input id="amount" name="amount" type="text"></td>
</tr>
</tbody>
</table>
</form>
This is my insert query:
<?php
//some connection code here
if(isset($_POST['submit']))
{
$item = array(
'item_description' => '',
'price' => '',
'qty' => '',
'amount' => '',
);
foreach ($item as $key => $value){
$value = $_POST[$key];
}
}
$last_insert_payment_id=mysql_insert_id();
$sql1="INSERT INTO payment_item (payment_id, payment_item_id, item_description, price, qty, amount)
VALUES
('$last_insert_payment_id','NULL','$_POST[item_description]','$_POST[price]','$_POST[qty]','$_POST[amount]')";
if (!mysql_query($sql1,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
?>
Hope someone can help me to figure this out. Thank you.
So you mean when you click 'Add row' and enter extra rows of data and then click 'Submit', only the last row gets inserted into the database?
I'm guessing that when you click 'Add Row', the following HTML is added to your table (same as the row in your question)
<tr>
<td><input type="checkbox" name="chk"></td>
... and so on
In this case, your $_POST['price'], $_POST['chk'] etc are probably getting overwritten for each row, because you now have multiple inputs with hane chk.
Try setting your input id="chk[]" instead of input id="chk", and then $_POST['chk'] will be an array, one for each row.
You could access each row via $_POST['chk'][i].
There are also the other recommendations in the comments about making your code safe to SQL injection, and the fact that $_POST[price] (like you have in your SQL statement) is invalid syntax; you probably want $_POST['price']. (Daedalus, Marc B, Los Frijoles).

How to show the result when I click the submit button? (Like View history)

Here's the concept. The users will input the data from the text bar.. And when click the submit button, the data will be saved to the "VIEW HISTORY" menu bar. View history is where the data's inputted from the home.php are being made.
E.g:
Home.php
(data1)
Enter Name: (I type..)Black Cat
Age: (I type..)21
Job: (I type..)Spy
(data2)
Enter Name: (I type..)Black Dog
Age: (I type..)24
Job: (I type..)Cook
Submit Button (I click it) and it says the data is submitted to my database.
Then when I click the "View History Menu Bar".. The ff will be shown:
DATA1
DATA2
<Click next to view next page.. etc>
When I click data1, the whole name, age and job from data1 will appear. And so is from data2.. and so on.. :)
That's my only problem.. I can't show those data :( Please help! I have some codes in here.. But I dunno how to fix it :( I hope you can give some samples so I can imitate the moves, or better if we help on fixing this. :( THANKS Y'ALL!
<?php
$cfccon = include("E:/xampp/conn1/cfmscsd.php");
//This is about the localhost, username, password stuff
$query="SELECT * FROM contents";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
$i=0;
while ($i < $num) {
$B1=mysql_result($result,$i,"B1");
$B2=mysql_result($result,$i,"B2");
$B3=mysql_result($result,$i,"B3");
$B4=mysql_result($result,$i,"B4");
$B5=mysql_result($result,$i,"B5");
$B6=mysql_result($result,$i,"B6");
$B7=mysql_result($result,$i,"B7");
$B8=mysql_result($result,$i,"B8");
$B9=mysql_result($result,$i,"B9");
$B10=mysql_result($result,$i,"B10");
$i++;
}
?>
<html>
<tr>
<td bgcolor="#bfb9a7"><span class="style77">CCC</span></td>
<td bgcolor="#CCCCCC"><div align="center" class="style66"><input name="B1" type="text" size="18" id="B1" value="<?php echo $B1;?>" disabled="disabled"/></div></td>
<td bgcolor="#CCCCCC"><div align="center" class="style66"><input name="B2" type="text" size="18" id="B2" value="<?php echo $B2;?>" disabled="disabled"/></div></td>
<td bgcolor="#CCCCCC"><div align="center" class="style66"><input name="B3" type="text" size="18" id="B3" value="<?php echo $B3;?>" disabled="disabled"/></div></td>
<td bgcolor="#CCCCCC"><center><div class="style66"><input type="button" onclick="tbsp1()" value="<?php echo $tbsp1;?>add" disabled="disabled"/></center></td>
<td bgcolor="#FEEDD8"><div align="center" class="style66"><input name="B4" type="text" size="18" id="B4" value="<?php echo $B4;?>" disabled="disabled"/></div></td>
</tr>
<tr>
<td><span class="style77">SCC</span></td>
<td><div align="center" class="style66"><input name="B5" type="text" size="18" id="B5" value="<?php echo $B5;?>" disabled="disabled"/></div></td>
<td><div align="center" class="style66"><input name="B6" type="text" size="18" id="B6" value="<?php echo $B6;?>" disabled="disabled"/></div></td>
<td><div align="center" class="style66"><input name="B7" type="text" size="18" id="B7" value="<?php echo $B7;?>" disabled="disabled"/></div></td>
<td><center><input type="button" onclick="tbsp2()" value="<?php echo $tbsp2;?>add" disabled="disabled"/></center></td>
<td bgcolor="#FEEDD8"><div align="center"><input name="B8" type="text" size="18" id="B8" value="<?php echo $B8;?>" disabled="disabled"/></div></td>
</tr>
<tr>
<td bgcolor="#bfb9a7"><span class="style77">NCC</span></td>
<td bgcolor="#CCCCCC"><div align="center" class="style66"><input name="B9" type="text" size="18" id="B9" value="<?php echo $B9;?>" disabled="disabled"/></div></td>
<td bgcolor="#CCCCCC"><div align="center" class="style66"><input name="B10" type="text" size="18" id="B10" value="<?php echo $B10;?>" disabled="disabled"/></div></td>
</tr>
</html>
First of all, I recommend that you rename your table columns, B1, B2, B3 etc are very very bad names, instead use something descriptive like name, age, email, etc. That will make your code a lot easier to read and debug.
To achieve what you're asking for, do something like this:
1) When the user clicks the submit button, do a form post to a script on your site, e.g
<form method=post action=home.php>
Enter data: <input type=text name=data>
<input type=submit value=Submit />
</form>
2) When the user clicks the submit button, you could get the data he posted in $_POST, e.g $_POST['data']. Save this to a mysql database. You should give the user a unique user ID. Each row in your table should have these fields:
dataId (int,primary, auto_increment)
userID (int)
name (varchar 255)
age (int)
etc...
Then you should have a different table for users, called a user table. Each user who visits the website should have a unique userId. You can store this userId in $_SESSION, I recommend you read about session handling.
Then whenever the user submits his form, you add a new row to your data table with his info, and the userId field with the given user's id.
3) When the user clicks 'next' to see the data, you would do something like this:
$userId = $_SESSION['userId'];
$sql = "SELECT * FROM data WHERE userId='$userId'";
$result = mysql_query($sql) or die(mysql_error());
$history = array();
while ($row = mysql_fetch_assoc($result))
{
$history[] = $row;
}
4) Then simply loop through the $rows using foreach and display the history.

Categories