Inserting data in 2 table on the same form [duplicate] - php

Assuming that I have two tables, names and phones,
and I want to insert data from some input to the tables, in one query. How can it be done?

You can't. However, you CAN use a transaction and have both of them be contained within one transaction.
START TRANSACTION;
INSERT INTO table1 VALUES ('1','2','3');
INSERT INTO table2 VALUES ('bob','smith');
COMMIT;
http://dev.mysql.com/doc/refman/5.1/en/commit.html

MySQL doesn't support multi-table insertion in a single INSERT statement. Oracle is the only one I'm aware of that does, oddly...
INSERT INTO NAMES VALUES(...)
INSERT INTO PHONES VALUES(...)

Old question, but in case someone finds it useful... In Posgresql, MariaDB and probably MySQL 8+ you might achieve the same thing without transactions using WITH statement.
WITH names_inserted AS (
INSERT INTO names ('John Doe') RETURNING *
), phones_inserted AS (
INSERT INTO phones (id_name, phone) (
SELECT names_inserted.id, '123-123-123' as phone
) RETURNING *
) SELECT * FROM names_inserted
LEFT JOIN phones_inserted
ON
phones_inserted.id_name=names_inserted.id
This technique doesn't have much advantages in comparison with transactions in this case, but as an option... or if your system doesn't support transactions for some reason...
P.S. I know this is a Postgresql example, but it looks like MariaDB have complete support of this kind of queries. And in MySQL I suppose you may just use LAST_INSERT_ID() instead of RETURNING * and some minor adjustments.

I had the same problem. I solve it with a for loop.
Example:
If I want to write in 2 identical tables, using a loop
for x = 0 to 1
if x = 0 then TableToWrite = "Table1"
if x = 1 then TableToWrite = "Table2"
Sql = "INSERT INTO " & TableToWrite & " VALUES ('1','2','3')"
NEXT
either
ArrTable = ("Table1", "Table2")
for xArrTable = 0 to Ubound(ArrTable)
Sql = "INSERT INTO " & ArrTable(xArrTable) & " VALUES ('1','2','3')"
NEXT
If you have a small query I don't know if this is the best solution, but if you your query is very big and it is inside a dynamical script with if/else/case conditions this is a good solution.

my way is simple...handle one query at time,
procedural programming
works just perfect
//insert data
$insertQuery = "INSERT INTO drivers (fname, sname) VALUES ('$fname','$sname')";
//save using msqli_query
$save = mysqli_query($conn, $insertQuery);
//check if saved successfully
if (isset($save)){
//save second mysqli_query
$insertQuery2 = "INSERT INTO users (username, email, password) VALUES ('$username', '$email','$password')";
$save2 = mysqli_query($conn, $insertQuery2);
//check if second save is successfully
if (isset($save2)){
//save third mysqli_query
$insertQuery3 = "INSERT INTO vehicles (v_reg, v_make, v_capacity) VALUES('$v_reg','$v_make','$v_capacity')";
$save3 = mysqli_query($conn, $insertQuery3);
//redirect if all insert queries are successful.
header("location:login.php");
}
}else{
echo "Oopsy! An Error Occured.";
}

Multiple SQL statements must be executed with the mysqli_multi_query() function.
Example (MySQLi Object-oriented):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO names (firstname, lastname)
VALUES ('inpute value here', 'inpute value here');";
$sql .= "INSERT INTO phones (landphone, mobile)
VALUES ('inpute value here', 'inpute value here');";
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

Related

How can I pass my user entered information to my database using php?

The users enter their name and number in the textfields. The this information is passed then sent to the data.php file where I am trying to get it to write to my database. The data base name is called hello.
<!-- connect to database -->
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "hello";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}
//<!-- post added information to database -->
if ($_POST['name']) {
if ($_POST['number']) {
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number'')";
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
} ?>
From looking at my code I believe the issue is with this line.
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', '$_POST['name']', '$_POST['number']')";
There is a blank left at the star for the auto incremented id that I have set in phpmyadmin.
I can hard code an entry such as:
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', 'john', '12345)";
These hard coded entries are put into the database but i can't get the user entered data to go in.
Create variables for the $_POST values and add the vars for ease of code understanding:
$name = $_POST['name'];
$number = $_POST['number'];
$sql = "INSERT INTO hello (id, name, number) VALUES ('', $name, $number)";
One reason your code may not be working because you have the single quotes around the $_POST values, then you can also do what Jasbeer Rawal recommended.
UPDATE
Based on the kind comments... I would personally take a different approach to adding the data to your database, instead use prepared statements. I use MySQLi, but you can also use PDO.
Start by creating your connection:
<?php
define("HOST", "localhost");
define("USER", "");
define("PASSWORD", "");
define("DATABASE", "");
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($mysqli->connect_error) {
echo "There was a slight problem, please contact your webmaster before continuing.";
exit();
}
Then when the user submits the form handle it:
if(isset($_POST['submit']
{
$name = $_POST['name'];
$number = $_POST['number'];
if ($stmt = $mysqli->prepare("INSERT hello (name, number) VALUES (?, ?)"))
{
$stmt->bind_param("ss", $name, $number);
$stmt->execute();
$stmt->close();
}
else
{
echo "ERROR: Could not prepare SQL statement.";
}
}
This will add $name and $number and your ID role has to be a primary role and set to auto_increment. IDs will be automatically generated.
You're about to go down a slippery slope using mysqli. I'd recommend trying to learn to use PDO for making queries. Right now, someone could easily put SQL into the name POST data and actually do damage to your database.
Anyways, your problem at hand, you have a missing bracket and one issue:
VALUES ('', '$_POST['name']', '$_POST['number'')";
It won't work as intended with nested single quotes.
VALUES ('', '$_POST[name]', '$_POST[number]')";
Remove single quotes from $_POST['name'] and $_POST['number'] as below
$sql = "INSERT INTO hello (id, name, number)
VALUES ('', $_POST['name'], $_POST['number'])";
Your insert code be like this
$sql = "INSERT INTO hello (id, name, number)
VALUES ('','{$_POST['name']}', '{$_POST['number']}')";
Then your value will be in database
If field id is primary key and auto increment then your insert statement should be like
Try this:
$sql = "INSERT INTO hello ( name, number)
VALUES ('{$_POST['name']}', '{$_POST['number']}')";

Php wont input data into database

So im trying to get my data from my form submission to be put into a mysql database but whenever i submit a form it gives me this error: Error: INSERT INTO form_submissions(ID, first, last, phone, class) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5])
Now here is my PHP code:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "form_database";
$value = $_POST['first'];
$value1 = $_POST['last'];
$value2 = $_POST['phone'];
$value3 = $_POST['class'];
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error){
die("connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO `form_submissions`(`ID`, `first`, `last`, `phone`,
`class`) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5])";
if ($conn->query($sql) === TRUE) {
echo "Submitted Successfully";
} else {``
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
assuming that ID is auto-incrementing, and that the others are text,
$sql = "INSERT INTO `form_submissions`(`first`, `last`, `phone`,
`class`) VALUES ('$value','$value1','$value2','$value3')";
Your query should be like:
INSERT INTO `form_submissions`(`first`, `last`, `phone`, `class`)
VALUES ('John','doe', '98564', 'SOMECLASS');
To check: echo the $sql query and debug it in phpmyadmin.
Note: If you enabled AUTO_INCREMENT, you can ignore the data feed of that column. It will do its job automatic.
Security tip - >
To prevent SQLi Injection check out this post.
There are two things wrong.
The first thing is you give 5 fields (ID, First, last, phone, class)
And you only have 4 variables in your post. I think you don’t need to send the ID on an insert if the column is set to auto increment in the database, So don’t send an value for the ID field.
Your variables are not correctly inserted in the query.
The [value-1] douse not mean the $value1 variable will automatically be injected in there.
This can be done in a lot of way’s
I wil give you a simple solution, (but it wil be a bad one for real websites). The simple solution is:
$sql = "INSERT INTO `form_submissions`(`first`, `last`, `phone`,`class`) VALUES (`$value`,`$value1`,`$value2`, `$value3`)";
The reason this is bad is: You are directly entering post data inside your query and are now vounerable to SQL-Injections. You need to escape your post data befoure inserting it in a query. Or better yet don’t use ‘mysqli’ but an PDO.
An good PDO example can be found here
https://www.w3schools.com/php/php_mysql_insert.asp
I hope this helps.
Your SQL is apparently wrong. It should look's like with something like that:
$sql = "INSERT INTO `form_submissions`(`ID`, `first`, `last`, `phone`,
`class`) VALUES ($value1,$value2,$value3,$value4,$value5)";
The field ID should be auto_increment. If it is, you don't need to pass value to it.

PHP MySQL Inserting data in a database table using PHP script

Using the given below php script, I connect to database and insert data in it. But the data is not getting inserted in my database table. It is also not throwing any error. Where is my code wrong?
<?php
$host = '127.0.0.1';
$uname='root';
$pswd='';
$myDB='portal';
if($myConn = new mysqli($host,$uname,$pswd))
echo 'Connected to MySQL server successfully.</br>';
else
echo 'Unable to connect to server</br>';
$database = mysqli_select_db($myConn,$myDB);
if($database)
echo 'Connected to database...</br>';
else
echo 'Database not found!</br>';
$var1='string1';
$var2='string2';
$query= "INSERT INTO users VALUES ($var1,$var2)";
$result = mysqli_query($myConn,$query) or die(mysqli_error($myConn));
?>
You have to add single quotes around the values:
$query= "INSERT INTO users VALUES ('$var1','$var2')
Or better use prepared statements. See this for an example.
In your statement, you must define the names of the target tables in your database, that the values should be inserted into, like this:
$query= "INSERT INTO users (Name,Age) VALUES ('$name','$age')";
if users table have only two columns, or two plus an auto-incrementing id the query is:
INSERT INTO users VALUES ('$var1','$var2')
if there are more columns or a non primary id the query is:
INSERT INTO users (col1,col2) VALUES ('$var1','$var2')
You also miss a parameter in the connection instantiation:
$mysqli = new mysqli($host, $uname,$pswd, $myDB);

How to grab an auto incremented variable and insert it into an insert query

I am trying to do a couple of php insert queries into a relational database, but I am running into a bit of an issue. In order for this relation to work I need to grab the autoincremented value from the first query and then insert it into the second query so the relation between the two exists.
I have this:
$query2 = "INSERT into words values ('' ,'$name') ";
-- The first value listed as '' is the auto-incremented primary key --
$query3 = "INSERT into synonyms values ('' , '', $alias') ";
-- The first value listed is the auto incremented pk, the second value needs to be the fk or the pk from the first query, but I don't know how to place it there. --
Is there a way to do this? Any help would be appreciated.
Here an SQL Fiddle to help y'all out:
http://sqlfiddle.com/#!2/47d42
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO words(word) values ('word1')");
$last_id = mysql_insert_id();
mysql_query("INSERT INTO words(synonym_id,synonym) values ($last_id, "synonym1)");
?>
Reference: http://php.net/manual/en/function.mysql-insert-id.php
. . You should consider using PDO in most recent PHP versions for its modern features, such as prepared statements, so that you don't need to worry about SQL Injection or broken escaping functions.
. . Using transactions is also advisable if the follow up queries are mandatory for the record to be useful. Using transactions keeps your database clear of the garbage of any failed second or third queries.
. . Also, you can omit the Auto-Increment field when running the Insert Query if you list the other fields after the table name. I think it's a much more common pattern, like INSERT INTO table (field1, field2) VALUES ("value1", "value2"). I used it in the example below:
$pdo = new PDO('mysql:host=localhost;dbname=database', 'user', 'pass');
$pdo->beginTransaction();
try {
$prepared = $dbh->prepare('INSERT INTO words (fieldName) values (?)');
$prepared->execute(array($name));
$fID = $pdo->lastInsertId();
$prepared = $dbo->prepare('INSERT INTO synonyms (fieldName) Values (?, ?)';
$prepared->execute(array($fID, $alias));
$dbo->commit();
} catch(PDOExecption $e) {
$dbo->rollback();
print 'Error: '. $e->getMessage();
}
. . Note that this will not work with MSSQL as it doesn't support "lastInsertId".
. . Amplexos.
not sure if you're using MySQL native functions or not. If so the answer is to use mysql_last_id(). These functions are deprecated and are not adivsable to use.
EXAMPLE:
//escape your indata
$brand= mysql_real_escape_string($_POST['brand']);
$sql = "INSERT INTO cars(brand) VALUES('{$brand}')";
mysql_query($sql);
//find last id from query above
$id = mysql_last_id();
Try PDO instead:
PDO::lastInsertId
EXAMPLE:
$brand= $_POST['brand'];
$sql = "INSERT INTO cars(brand) VALUES (:brand)";
$query = $conn->prepare($sql);
$query ->execute(array(':brand'=>$brand));
$id = $conn->lastInsertId();
http://www.php.net/manual/en/book.pdo.php

add values to mysql database using php on ubuntu

n00b learning php from a book.
I'm trying to add data to a database called adv_php. I'm using the following snippet of code in the page that's receiving the data from the post:
<?php
$dbc = mysqli_connect('host', 'name', 'password', 'adv_php');
if (mysqli_connect_errno())
{
echo "Failed to connec to MySQL" . mysqli_connect_error();
}
$parent_id = $_POST['parent_id'];
$task = $_POST['task'];
// Add the task to the database.
$q = "INSERT INTO (parent_id, task) tasks VALUES ($parent_id,'$task')";
mysqli_query($dbc, $q);
?>
I know this code connects to the database elsewhere as I can retrieve info from the database. With this page, I don't get an error, I just get a blank page, and nothing is added to the database Where am I going wrong?
Your query is wrong...Change it ...
$q = "INSERT INTO tasks(parent_id, task) VALUES ($parent_id,'$task')";
you misplaced table_name, use below query
$q = "INSERT INTO tasks (parent_id, task) VALUES ($parent_id,'$task')";
Your insert statement is wrong
Try this
$q = "INSERT INTO tasks (parent_id, task) VALUES ($parent_id,'$task')";

Categories