I have one form which need to submit data into two different tables in same DB.
at past time, i have asked how to submit form into two tables, but it impossible.
Then, I try to submit this form use two submit buttons with different destination.
Could you give some advise to submit this form after click them?
Javascript:
function button1click() {
yourForm.action = "ajax1.php";
yourForm.submit();
}
function button2click {
yourForm.action = "ajax2.php";
yourForm.submit();
}
HTML:
<form action='' method='post'>
<input type='input' id='blah' name='blee' />
<button type='button' onclick='button1click()'>Button 1</button>
<button type='button' onclick='button2click()'>Button 2</button>
</form>
why dear ?
if($_POST['submit'])
{
$sql1="insert into table 1";
mysql_query($sql1);
$sql2="insert into table 2";
mysql_query($sql2);
}
This should work..
one submit button only. OK!
You can do this many different ways. Just because the data is on one form, doesn't mean it has to go into one table. Basically you need to learn how to write some server side code that parses the incoming data and puts it where it needs to be.
So the simplest way is to just submit your form, and then on the server save the data to where it needs to go.
Having 2 buttons could be clunky, unless thats how it was designed...
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("MYDB") or die(mysql_error());
// Insert a row of information into the table "example"
$sql="INSERT INTO example
(name, age) VALUES('Timmy Mellowman', '23' ) ")
or die(mysql_error());
// Insert a row of information into the table "example"
$sql=mysql_query("INSERT INTO example1
(name, age) VALUES('Timmy Mellowman', '23' ) ")
or die(mysql_error());
?>
You can insert into different tables like this:
EDIT (new code):
<?php
// Make a MySQL Connection
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("double") or die(mysql_error());
// Insert a row of information into the table "example"
mysql_query("INSERT INTO example
(name, age) VALUES('Timmy Mellowman', '23' ) ")
or die(mysql_error());
// Insert a row of information into the table "example"
mysql_query("INSERT INTO example1
(name, age) VALUES('Timmy Mellowman', '23' ) ")
or die(mysql_error());
?>
Hope this answers you question because toy cant have double destination (i think) but this inserts into two different MySQL tables...
Good luck
To summarize what others have said above,
You could submit to two different locations, using javascript to change the action attribute of the form. You might wanna use it if the two destinations are not on the same server.
Or you could submit it to one destination only, massage your data, and then insert into two tables using php. It'll be particularly advantageous as you wouldn't need to sanitize or validate the data twice on server-side.
Very Very Simple...
You can insert in two tables by only one submit button..
Example:
<?php
if(isset($_POST['submit']))
{
$value1 = (!empty($_POST['form_name_value1']))?$_POST['form_name_value1']:null;
$value2 = (!empty($_POST['form_name_value2']))?$_POST['form_name_value2']:null;
$str = "INSERT INTO table_name1(db_value1, db_value2)VALUES('$value1','$value2')
$sql = mysql_query($str) or die(mysql_error());
$str1 = "INSERT INTO table_name2(db_value1, db_value2)VALUES('$value1','$value2')
$sql1 = mysql_query($str1) or die(mysql_error());
if($str)
{
echo "Successful";
}else{
echo "Unsuccessful";
}
if($str1)
{
echo "Successful";
}else{
echo "Unsuccessful";
}
}
This question was asked 4 years ago. Not the time to answer now I know. But
still answering to help others searching for the same problem.
Vote Up if you find this helpful. :D
Related
I am trying to bulk insert some data in PHP from a textarea form, and then prevent duplications from already existing data. I tried to code something but right now it just inserts everything that I insert in the textarea in same "value" in the column. But I want each line from the textarea separated in each and own column.
Here is what I have so far, and this works but it inserts the whole row:
<?php
include '../includes/config.php';
if (isset($_POST["data"])) {
$_POST["ban"] = $value;
$line_data = explode("\n", $_POST["data"]);
foreach ($line_data as $key => $value) {
$checkQuery = "SELECT ip FROM blacklist WHERE ip='" . $_POST["ip"] . "'";
$checkResult = mysqli_query($con, $checkQuery);
if (mysqli_num_rows($checkResult) != 0){
// do nothing
} else {
$sql = "INSERT IGNORE INTO blacklist (ip) VALUES ('{$value}')";
$result = mysqli_query($con, $sql);
}
}
}
?>
<form action="bulk.php" method="post">
<textarea type="text" name="data" placeholder="IP address"></textarea><br/>
<button type="submit" name="ban">Ban</button>
</form>
So my question is, what am I doing wrong and is there good way to handle this? If so, how?
Edit: It inserts into it's own column now, but it still duplicates. Like it's still possible insert same thing many times even if data exists in database.
You can function explode for splitting values in field ip into lines. Save each line with ip address as separate record in your db table blacklist
I built an html page with some options to insert details for a friends club.
I used an INSERT query and it worked. I want to add other queries like an UPDATE, DELETE, SELECT etc.
this is the php file:
<?php
//Input posted data.
$Fname = $_POST["Fname"];
$Lname = $_POST["Lname"];
$Date = $_POST["Date"];
$Mail = $_POST["Mail"];
$Pass = $_POST["Pass"];
// Create connection
$conn = mysqli_connect('localhost','root',"");
//Check if the connection was opened, if not prompt the error to the page.
if (!$conn)
{
die('Could not connect: ' . mysqli_error());
}
//Select the data base.
mysqli_select_db($conn, "club");
//Set the character set to utf-8 to allow hebrew.
mysqli_query($conn, "SET NAMES 'utf8'");
//SQL query - user Details
$sql = "INSERT INTO customers (Fname, Lname, Mail, Date, Pass)
VALUES('$Fname','$Lname','$Mail','$Date','$Pass')";
//Run SQL query
$results = mysqli_query($conn, $sql) or die (mysqli_connect_errno());
//Close the SQL connection.
mysqli_close($conn);
?>
I want to use those queries in the same file.
how can I do that?
Should I add a new form on the same page?
For example <form name="input" action="Update.php" method="POST"> to direct it to the Update.php file?
can I use more than one form at the same html file?
I've created this form for the Update button on the page to Update.php file but it doesn't work. It just adds the details and does not update them, although I used the UPDATE query.
You take all your PHP code and put it in the head of the form's page, then wrap it all inside
if(isset($_POST['submit-button-name'])){
//YOUR PHP CODE
}
Now you for each submit-button-name you make an if statement with it, for example
if(isset($_POST['insert'])){
//YOUR INSERT QUERY
}
if(isset($_POST['update'])){
//YOUR UPDATE QUERY
}
if(isset($_POST['delete'])){
//YOUR DELETE QUERY
}
That if you for example have 3 buttons like the following
<button type='submit' name='insert'>INSERT</button>
<button type='submit' name='update'>UPDATE</button>
<button type='submit' name='delete'>DELETE</button>
Inside the form, of course the UPDATE & DELETE queries require an identifier to find the row
WHERE id = $id
So it depends how you will implement the buttons in one form.
I've put certain values like a user id into the url e.g /index.php?id=1 in previous PHP files.
I have a HTML form that has an action like this:
<form name="staffResponse" method="post" action="respond_ticket.php?id=<?php echo $_GET['id']; ?>">
Which when you go to respond_ticket.php and simply echo the value for the id and look at the URL it does it successfully. Whats more the data that I am posting to that file is also done without problem. However I want to then write that information to a table but it does not seem to work.
Here is the respond_ticket.php file
<?php
include 'database/db.php';
$id = $_GET['id'];
$staffResponse = $_POST['staffResponse'];
$sql = "INSERT INTO tickets (staffResponse) VALUES ('$staffResponse') WHERE id='$id'";
$result = mysqli_query($connection, $sql);
if ($result === TRUE) {
echo '<p>Response ' . $staffResponse . ', has been added</p>';
}
else {
echo '<p class="warning">Unable to respond</p>';
}
?>
The db.php file has all the necessary information for connection to the database i.e name password etc. It also opens the question there too.
I keep just getting the warning message that I wrote.
you cant do an insert with a where modifier like this. change it to update ;)
UPDATE tickets SET staffResponse = '$staffResponse' WHERE id = '$id'
You are not supposed to use a WHERE clause with INSERT
$sql = "INSERT INTO tickets (staffResponse) VALUES ('$staffResponse')";
You may wish to set your tickets table up with auto increment so you dont need to insert an id if you haven't done that already.
use ON DUPLICATE UPDATE if it helps
INSERT INTO tickets (id,staffResponse) VALUES ('$id','$staffResponse')
ON DUPLICATE KEY UPDATE id=VALUES(id), staffResponse=VALUES(staffResponse)
Below is a form I am submitting once this form is submitted it will display a questionnaire. The hidden input type in the echo statement holds an array of question id's. the question text is printed out. Then a text box is created for the answer to be filled in and this will be passed through as an array of different answers - questionanswer[].
<form action="addanswers.php" method="post">
<fieldset>
<?php
$sql = "SELECT * FROM QUESTIONS WHERE QUESTIONNAIRE_FK = '$questionnaireid';";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$questionid = $row["QUESTION_ID"];
if($row["QUESTION_TYPE"] == "ff"){
echo "<input type='hidden' name = 'questionid[]' value = '".$questionid."'>".$row["QUESTION_TEXT"]." <input type='text' name='questionanswer[]''></br>";
}
}
?>
<input type="Submit" value="Submit">
</fieldset>
</form>
I am then trying to submitting the data entered into the text box to the database but I also want to be able to link the question id from the form to the question answer and submit both of them to the answers table of the database along with a questionnaire id. The answers table looks like this:
Answers(Answer_ID(PK), Answer_Text, Question_FK, Questionnaire_FK)
Below shows addanswers.php. At the minute I am able to add the answer to the database which is posted from the text box in the questionnaire. I am having difficulty linking the question id to the answer text to submit it to the answer table.
$questionanswers = $_POST['questionanswer'];
$questionids = $_POST['questionid'];
foreach($questionanswers as $qa){
$sql = "INSERT INTO ANSWERS (ANSWER_TEXT, QUESTIONNAIRE_FK) values ('$qa', '$questionnaireid')";
mysql_query($sql) or die(mysql_error());
}
Any help and advice on this issue would be greatly appreciated.Thanks in advance for your help.
Alright, I just wanted to make sure of your array structure, try this way:
$questionanswers = array_map('mysql_real_escape_string', $_POST['questionanswer']);
$questionids = array_map('mysql_real_escape_string', $_POST['questionid']);
foreach($questionanswers as $ind=>$ans){
$sql = "INSERT INTO ANSWERS (ANSWER_TEXT, QUESTIONNAIRE_FK) values ('$ans', '$questionids[$ind]')";
//$ind above contains index of the $questionanswers array-> 0, 1, 2
//since your $questionids index is also numeric and have the
//same number of array values, we can use this index to refer
//the corresponding $questionids
mysql_query($sql) or die(mysql_error());
}
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
When submitted, a new row gets added to the 'servers' table, but every data says '0' instead of the data I inputted.. I'm using VARCHAR64 for the rows..
Form.html
<html>
<head>
</head>
<body>
<form action="db.php" method="post">
server id: <input type="text" name="post_serverid">
server ip: <input type="text" name="post_serverip">
<input type="submit>
</body>
</html>
db.php
<?php
$con=mysqli_connect("localhost","root","","toplist");
//Checking the connection
if(mysqli_connect_errno($con))
{
echo "Cold not connect to SQL Database: " + mysqli_connect_error();
}
mysqli_query($con, "INSERT INTO servers (serverid, serverip) VALUES ('$_POST['post_serverid']', '$_POST['post_serverip']')");
?>
First: NEVER just throw user data straight into your database without validating / cleansing it first.
Next, you've got some odd punctuation going on in your mysqli_query(). Try this:
$serverid = $mysqli->real_escape_string($_POST['serverid']);
$serverip = $mysqli->real_escape_string($_POST['serverip']);
$sql = "INSERT INTO servers (serverid, serverip) VALUES('$serverid', '$serverip');";
mysqli_query($con, $sql);
From OP's comment:
"Strangely enough, mysqli_query($con,"INSERT INTO form (name, dob) VALUES ('$_POST[post_name]', '$_POST[post_dob]')"); works."
"But when I replace NAME with SERVERID, and replace DOB with SERVERIP, the inputted data doesn't insert."
The problem is, you need to change your POST variables and column names accordingly.
Rename your NAME column to SERVERID and DOB column to SERVERIP.
and post_name to serverid and post_dob to serverip
The new query can now be done this way:
$serverid = mysqli_real_escape_string($con,$_POST['serverid']);
$serverip = mysqli_real_escape_string($con,$_POST['serverip']);
$sql = "INSERT INTO `servers` (`serverid`, `serverip`) VALUES ('$serverid', '$serverip');";
mysqli_query($con, $sql);
Using this method will help prevent against SQL injection.
You might want to use $_POST['key'] instead of $_POST[key]
$_POST is an associative array, you need to access the keys with single or double quotes.
Example:
change your query to
$query = "INSERT INTO servers (serverid, serverip) VALUES ('".$_POST['post_serverid']."','".$_POST['post_serverip']."')";
mysqli_query($con, $query);
Also, you are currently volunerable to SQL injection. I'd suggest to use a prepared statement or at least escape the $_POST variables before inserting it to the DB.
Hope this helps!
$serverip=$_POST['post_serverid'];
$serverid=$_POST['post_serverip'];
$query = mysqli_query($con,"INSERT INTO servers (serverid, serverip) VALUES ('$serverid','$serverid')");
Try this, it should work