Inserting into two table simultaneously sharing same id - php

Please i have a little problem here. the below code i wrote was meant to insert into two tables simultaneously but it those not work. but if i remove the second INSERT the first INSERT will work dont know whats wrong. ITs meant insert in the first table and also collect the last Insert Id of the First table to the Second table. What did i do wrong
<?php
$english_name = $_POST['EnglishName'];
$tel_number = $_POST['TelNumber'];
$email_address = $_POST['EmailAddress'];
$gender = $_POST['Gender'];
$age = $_POST['Age'];
$region = $_POST['Region'];
mysql_connect("localhost", "root", "") or die ('Error: ' . mysql_error());
mysql_select_db("fruitmarket");
$query="INSERT INTO data (english_name, tel_number, email_address, gender, age, region) VALUES (";
$query.="'".$english_name."', ";
$query.="'".$tel_number."', ";
$query.="'".$email_address."', ";
$query.="'".$gender."', ";
$query.="'".$age."', ";
$query.="'".$region."')";
$query .= "INSERT INTO data_category (id, english_name)
VALUES (LAST_INSERT_ID(), '$english_name');";
mysql_query($query) or die ('Error updating database');
echo "Record is inserted.";
?>

its almost 2018, so please stop using depreciated and removed mysql_* functions use PDO/mysqli with prepared statements.
I have re-written your code with prepared statements, please follow these links :
Why shouldn't I use mysql_* functions in PHP?
How can I prevent SQL injection in PHP?
Prepared statements
<?php
$servername = "localhost";
$username = "username";
$password = "";
$dbname = "fruitmarket";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = "INSERT INTO data (english_name,tel_number,email_address,gender,age,region) VALUES(?,?,?,?,?,?)";
$sql = $conn->prepare($stmt);
$sql->bind_param("ssssis", $english_name, $tel_number, $email_address, $gender, $age, $region);
if ($sql->execute()) {
$id = $sql->insert_id;
$insert = $conn->prepare("INSERT INTO data_category (id, english_name) VALUES(?,?)");
$insert->bind_param("is", $id, $english_name);
if ($insert->execute()) {
echo "data inserted successfully";
} else {
printf("Errormessage: %s\n", $mysqli->error);
}
} else {
printf("Errormessage: %s\n", $mysqli->error);
}
A prepared statement is a feature used to execute the same (or similar) SQL statements repeatedly with high efficiency.
Prepared statements basically work like this:
Prepare: An SQL statement template is created and sent to the
database. Certain values are left unspecified, called parameters
(labeled "?"). Example: INSERT INTO myTabvle VALUES(?, ?, ?)
The database parses, compiles, and performs query optimization on
the SQL statement template, and stores the result without executing
it
Execute: At a later time, the application binds the values to the
parameters, and the database executes the statement. The application
may execute the statement as many times as it wants with different
values Compared to executing SQL statements directly, prepared
statements have three main advantages:
Prepared statements reduces parsing time as the preparation on the
query is done only once (although the statement is executed multiple
times)
Bound parameters minimize bandwidth to the server as you need send
only the parameters each time, and not the whole query
Prepared statements are very useful against SQL injections, because
parameter values, which are transmitted later using a different
protocol, need not be correctly escaped. If the original statement
template is not derived from external input, SQL injection cannot
occur.

I tested the above code and noticed you just need just to add and change some code see my below example
<?php
$english_name = $_POST['EnglishName'];
$tel_number = $_POST['TelNumber'];
$email_address = $_POST['EmailAddress'];
$gender = $_POST['Gender'];
$age = $_POST['Age'];
$region = $_POST['Region'];
mysql_connect("localhost", "root", "") or die ('Error: ' . mysql_error());
mysql_select_db("fruitmarket");
$query="INSERT INTO data (english_name, tel_number, email_address, gender, age, region) VALUES (";
$query.="'".$english_name."', ";
$query.="'".$tel_number."', ";
$query.="'".$email_address."', ";
$query.="'".$gender."', ";
$query.="'".$age."', ";
$query.="'".$region."')";
mysql_query($query) or die ('Error updating database');
echo "Record is inserted.";
$query= "INSERT INTO data_category (id, english_name)
VALUES (LAST_INSERT_ID(), '$english_name');";
mysql_query($query) or die ('Error updating database');
echo "Record is inserted.";
?>
test it to check if it will work

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']}')";

Data not stored using prepared statements

I am just learning to use prepared statements and stuck here. there is no problem with normal method. there is nothing error shown but the data is not stored in database although it displays "data entered".
$db = new mysqli("localhost", "root","","learndb");
if ($db->connect_error) {
die("Connection failed this is the error: " . $db->connect_error);
}
$stmt = $db->prepare("INSERT INTO studentrecords (Name, email, Phone, school,dob,father,feereceived,due,image) VALUES (?,?,?,?,?,?,?,?,?)");
$stmt->bind_param("ssisssiib",$first,$email,$phone,$school,$dob,$father,$feereceived,$due,$image);
$stmt->execute();
if($stmt)
{
echo"data entered";
}
Update
Data is stored but not the type required. should i specify all types in user input? Also the pattern in html form not working.
I'd suggest that you wrap the entire bind_param & execute with an if condition as the statement will fail to be prepared if there is even a minor issue. In this case I would guess it could be that the types for each variable/field is wrong at some point - probably the image / b part.
You can echo the type of each using gettype which might help track it down:
echo gettype($first), gettype($email), gettype($phone),
gettype($school), gettype($dob), gettype($father),
gettype($feereceived), gettype($due), gettype($image);
$db = new mysqli("localhost", "root","","learndb");
if ($db->connect_error) {
die("Connection failed this is the error: " . $db->connect_error);
}
$stmt = $db->prepare("INSERT INTO studentrecords (`Name`, `email`, `Phone`, `school`,`dob`,`father`,`feereceived`,`due`,`image`) VALUES (?,?,?,?,?,?,?,?,?)");
if($stmt) {
$stmt->bind_param("ssisssiib",$first,$email,$phone,$school,$dob,$father,$feereceived,$due,$image);
$stmt->execute();
} else {
echo 'Failed to prepare the sql statement';
}

MySQL - PHP form to insert values into table?

I would like to add comments to a database using a simple form. For whatever reason, I can't seem to get the table to update when I use said form. I'm not getting any errors, it's just that nothing happens when I refresh the table afterwards. In other words, even after submitting the form, the table still has 0 entries. Here is my code:
<?php
session_start();
$connection = mysql_connect("server", "username", "password");
if ($connection->connect_error) {
die('Connect Error: ' . $connection->connect_error);
}
// Selecting Database
mysql_select_db("database", $connection) or die(mysql_error());
$name = $_POST['name'];
$title = $_POST['title'];
$comments = $_POST['comments'];
$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";
mysql_close($connection); // Closing Connection
?>
Thank you for your help!
You don't ever actually execute your query:
$sql = "INSERT INTO comments (Name, Title, Comments)
VALUES ('$name', '$title', '$comments')";
$result = mysql_query($sql);
Other things:
if ($connection->connect_error) { is not valid. You can't use the old mysql API in an OOP fashion. You need to use mysqli for that.
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.
You are also wide open to SQL injections
You do no error checking. How do you expect to know if there are problems if you don't look for them?
(note: please change server, username, and password for your server information)
<?php
session_start();
$connection = mysql_connect("server","username","password");
if (!$connection) {
die('Connect Error: ' . mysql_error());
}
// Selecting Database
mysql_select_db("database",$connection) or die(mysql_error());
$name = $_POST['name'];
$title = $_POST['title'];
$comments = $_POST['comments'];
$sql = "INSERT INTO comments (Name,Title,Comments)
VALUES ('$name', '$title', '$comments')";
mysql_query($sql);
mysql_close($connection); // Closing Connection
?>
For security (defense against SQL injection) you can using mysql_real_escape_string function for limit input fields. For example:
$name = mysql_real_escape_string($_POST['name']);
$title = mysql_real_escape_string($_POST['title']);
$comments = mysql_real_escape_string($_POST['comments']);

MySQLi insert, successful database connection but not successfully inserted [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I'm attempting to insert some data into a table using mysqli functions.
My connection works fine using the following:
function connectDB(){
// configuration
$dbuser = "root";
$dbpass = "";
// Create connection
$con=mysqli_connect("localhost",$dbuser,$dbpass,"my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return false;
}else{
echo '<br />successfully connected<br />';
return $con;
}
}
But when I attempt to run my insert function I get nothing in the database.
function newUserInsertDB($name,$email,$password){
$con = connectDB();
// Prepare password
$password = hashEncrypt($password);
echo $password . "<br />";
// Perform queries
mysqli_query($con,"SELECT * FROM users");
mysqli_query($con,"INSERT INTO users (name,email,password,isActivated) VALUES ($name,$email,$password,0)");
// insert
mysqli_close($con);
}
I have been looking through the list of mysqli functions for the correct way to give errors but they all seem to be regarding the connection to the DB, not regarding success of an insert (and I can clearly see in my DB that it is not inserting.)
What would be the best way to debug? Which error handling shall I use for my insert?
I've tried using mysqli_sqlstate which gives a response of 42000 but I cannot see any syntax errors in my statement.
As mentioned in my comment, you would be better off using a prepared statement. For example...
$stmt = $con->prepare(
'INSERT INTO users (name, email, password, isActivated) VALUES (?, ?, ?, 0)');
$stmt->bind_param('sss', $name, $email, $password);
$stmt->execute();
Using this, you don't have to worry about escaping values or providing quotes for string types.
All in all, prepared statements are much easier and much safer than attempting to interpolate values into an SQL string.
I'd also advise you to pass the $con variable into your function instead of creating it within. For example...
function newUserInsertDB(mysqli $con, $name, $email, $password) {
// Prepare password
$password = hashEncrypt($password);
// functions that "echo" can cause unwanted side effects
//echo $password . "<br />";
// Perform queries
$stmt = $con->prepare(
'INSERT INTO users (name, email, password, isActivated) VALUES (?, ?, ?, 0)');
$stmt->bind_param('sss', $name, $email, $password);
return $stmt->execute(); // returns TRUE or FALSE based on the success of the query
}
The quotes are missing from the mysql statement from around the values. Also, you should escape the values before inserting them into the query. Do this way:
mysqli_query($con,"INSERT INTO users (name,email,password,isActivated) VALUES ('".
mysqli_real_escape_string($con,$name)."','".
mysqli_real_escape_string($con,$email)."','".
mysqli_real_escape_string($con,$password)."',0)");
Regards

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

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();
?>

Categories