Get ID from last insert into table - php

Im inserting into multiple tables , and need to get the ID from the last insert into table1 and use that as a variable in the insert for table 2.
The IDs is auto incremented.
The query's will be run once a submit button has been clicked in a form.
Query's:
$sql = "INSERT INTO table1 (Text) VALUES ($T1text);";
$sql = "INSERT INTO table2 (table1ID,Text) VALUES ($table1id, $T2text);";
table1 {id,Text}
table2 {id,table1.id,Text}

There is a PHP function for that (Decprecated, Removed in 7.0 !)
Or the according mysql/mysqli/pdo functions.
Solutions
PHP (Deprecated)
Example
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');
mysql_query("INSERT INTO mytable (product) values ('kossu')");
printf("Last inserted record has id %d\n", mysql_insert_id());
Source: http://php.net/manual/en/function.mysql-insert-id.php
Mysql/Mysqli/PDO
Mysqli
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
PDO
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
// use exec() because no results are returned
$conn->exec($sql);
$last_id = $conn->lastInsertId();
Source: http://www.w3schools.com/php/php_mysql_insert_lastid.asp

Related

Insert in MySQL Not Working

I am trying to put data in MySQL with PHP but is not showing any error but values are not entered in database too.
$query = "INSERT INTO orders (username, servicename, link, quantity, cost, date)
VALUES('$username', '$service_name', '$link', '$quanitiy', '$cost', '$date')";
$insert=mysqli_query($db, $query);
I think your query should look something like that:
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// create the query
$query = "INSERT INTO orders (username, servicename, link, quantity, cost, date)
VALUES('$username', '$service_name', '$link', '$quanitiy','$cost', '$date')";
// preform the query
$insert=mysqli_query($conn, $query);
// you need to check if the insert succeeded before closing the connection
// close connection to DB
mysqli_close($conn);

Passing auto increment id to second query

Currently I've got two queries, where the first one has an auto increment id. I would like to pass this id to my second query. But can't figure out how to do this. I've used 'mysqli_insert_id', but it returned in to the database.
This is my code:
$query = "INSERT INTO klanten (bedrijfsnaam) VALUES ('Some name')";
$last_id = mysqli_insert_id($con);
second_query = "INSERT INTO klantnotitie (login_id) VALUES ('" . $last_id . "')";
To avoid confusion: I want to insert to id of the first query into another table where it will just be an integer.
Hope someone can help me out!
Change your code like that
$query = "INSERT INTO klanten (bedrijfsnaam) VALUES ('Some name')";
mysqli_query($con, $query);
$last_id = mysqli_insert_id($con);
$second_query = "INSERT INTO klantnotitie (login_id) VALUES ('" . $last_id . "')";
mysqli_query($con, $second_query);
It will work in this way
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_query($link, "CREATE TABLE myCity LIKE City");
$query = "INSERT INTO klanten (bedrijfsnaam) VALUES ('Some name')";
mysqli_query($link, $query);
printf ("New Record has id %d.\n", mysqli_insert_id($link));
$last_id = mysqli_insert_id($link);
second_query = "INSERT INTO klantnotitie (login_id) VALUES ('" . $last_id . "')";
mysqli_query($link, $second_query);
/* close connection */
mysqli_close($link);
?>
Refer this
Assuming You are executing your queries,
1. You can use Mysql's function: LAST_INSERT_ID()
Example:
SELECT LAST_INSERT_ID();
2. You can use PHP's function mysqli_insert_id
Example:
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
//.. some code
$query = "INSERT INTO klanten (bedrijfsnaam) VALUES ('Some name')";
mysqli_query($link, $query);
printf ("New Record has id %d.\n", mysqli_insert_id($link));

php insert to sql not working

I'm on ubuntu running on apache2.
<?php
$con = mysqli_connect("localhost", "root", "password", "loops");
if (!mysqli_connect_errno()) {
echo "Error to connect: ".mysqli_connect_error();
}
$firstName = $_POST['firstname'];
$lastName = $_POST['lastname'];
$age = $_POST['age'];
echo "First: ".$firstName."<br />Age: ".$age;
$sql = "INSERT INTO persons (FirstName, LastName, Age)
values (".$firstName.",".$lastName.",".$age.")";
if (!mysqli_query($con)) {
die("Error :".mysqli_error($con);
}
echo "1 added";
mysqli_close($con);
?>
I don't know what to do now, but the error seems to be on the '$sql', 'cause when I put that
under a comment, the rest works...
You forgot the infamous mistake of wrapping the varchar variables with single quote '
"INSERT INTO persons (FirstName, LastName, Age)
values ('".$firstName."','".$lastName."','".$age."')";
Additionally, It's highly risky for you, not be using protections against SQL Injections
Try this, mysqli_query($con, $sql) You need to execute the query so that it will store into the database
$sql = "INSERT INTO persons (FirstName, LastName, Age)
values ('".$firstName."','".$lastName."','".$age."')";
if (!mysqli_query($con, $sql)) {
...................^
die("Error :".mysqli_error($con);
}
Try this:
$sql = "INSERT INTO persons (`FirstName`, `LastName`, `Age`) values (".$firstName.",".$lastName.",".$age.")";
If this doesn't work, what error do you get.

writing from a form to database

I have the following piece of code to make a input form being written in table named "client" database 'smsmart' which has fields name , address and phone
<?php
define ('DB_USER', 'root');
define ('DB_PASSWORD', '');
define ('DB_HOST', 'localhost');
define ('DB_NAME', 'smsmart');
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db("smsmart");
if (!$db_selected) {
die('Can\'t use ' . smsmart . ': ' . mysql_error());
}
$value1 = $_POST['username'];
$value2 = $_POST['address'];
$value3 = $_POST['mobileno'];
$sql = "INSERT INTO client (name,address,phone) VALUES ('$value1', '$value2', '$value3')";
mysql_close();
?>
The fields 'username' 'address' and 'mobileno' from form is not being written into database. What am i doing wrong?
It looks like you're generating the $sql query but not executing it. Given the lack of sanitation on your $_POST inputs, you should probably use a parametric or PDO method to protect yourself against potential SQL attacks.
Here is an example of a parameter-based mySQLi insert.
// connect to the database
$dbConnection = mysqli_connect("localhost", "root", "", "smsmart");
// prepare statement
$stmt = mysqli_prepare($dbConnection, "INSERT INTO client (name,address,phone) VALUES (?,?,?)");
// bind parameters
mysqli_stmt_bind_param($stmt, "sss", $value1, $value2, $value3);
// execute statement
mysqli_stmt_execute($stmt);
// close statement
mysqli_stmt_close($stmt);
// close database connection
mysqli_close($link);
You are saving your query in a variable but that variable isn't doing anything itself
mysql_query($sql);
mysql_query will help you to insert all the data in your Database.
you are missing mysql_query().
$sql = "INSERT INTO client (name,address,phone) VALUES ('$value1', '$value2', '$value3')";
mysql_query($sql);
mysql_close();
$sql = "INSERT INTO client (name,address,phone) VALUES ('$value1', '$value2', '$value3')";
mysql_close();
hence add mysql_query
should be
$sql = "INSERT INTO client (name,address,phone) VALUES ('$value1', '$value2', '$value3')";
mysql_query($sql);
mysql_close();
Everything looks great except one:
Just Use mysql_query() function, Like
$sql = "INSERT INTO client (name,address,phone) VALUES ('$value1', '$value2',
'$value3')";
mysql_query($sql);
mysql_close();

Php Post to two tables in Mysql

I'm trying to POST to two tables at the same time. I'm trying to get the DonorID to display in to another table under $description. I'm able to just write any text in the $description, but I need it to be dynamic not static, which is what the text is. I have two tables; the first is accounting and the second is donations. I'm trying to alter the $description='Donation from Donor'; and have the donor that made the transaction be listed where the Donor is. Any suggestions would be greatly appreciated.
Here is my code:
<?php
$dbserver = "localhost";
$dblogin = "root";
$dbpassword = "";
$dbname = "";
$date=$_POST['date'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$middleinitial=$_POST['middleinitial'];
$organization=$_POST['organization'];
$donorid=$_POST['donorid'];
$paymenttype=$_POST['paymenttype'];
$nonmon=$_POST['nonmon'];
$event=$_POST['event'];
$Income=$_POST['Income'];
$account='Revenue';
$description='Donation from Donor';
$transactiontype='Income';
$Expense='0.00';
$con = mysql_connect("$dbserver","$dblogin","$dbpassword");
if (!$con)
{
die('Could not connect to the mySQL server please contact technical support
with the following information: ' . mysql_error());
}
mysql_select_db("$dbname", $con);
$sql = "INSERT INTO donations (date, firstname, middleinitial, lastname,
organization, donorid, paymenttype, nonmon, Income, event)
Values
('$date','$firstname','$middleinitial','$lastname','$organization',
'$donorid','$paymenttype','$nonmon','$Income','$event')";
$sql2 = "INSERT INTO accounting (date, transactiontype, account,
description, Income, Expense)
VALUES ('$date','$transactiontype','$account','$description','$Income','$Expense')";
mysql_query($sql2);
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con);
header( 'Location: http://localhost/donations.php' ) ;
?>
As i said i would personaly use mysqli for new project, here a sample of you code with mysqli:
$dbserver = "localhost";
$dblogin = "root";
$dbpassword = "";
$dbname = "";
$date=$_POST['date'];
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$middleinitial=$_POST['middleinitial'];
$organization=$_POST['organization'];
$donorid=$_POST['donorid'];
$paymenttype=$_POST['paymenttype'];
$nonmon=$_POST['nonmon'];
$event=$_POST['event'];
$Income=$_POST['Income'];
$account='Revenue';
$description='Donation from Donor';
$transactiontype='Income';
$Expense='0.00';
//opening connection
$mysqli = new mysqli($dbserver, $dblogin, $dbpassword, $dbname);
if (mysqli_connect_errno())
{
printf("Connection failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "INSERT INTO `donations` (`date`, `firstname`, `middleinitial`, `lastname`, `organization`, `donorid`, `paymenttype`, `nonmon`, `Income`, `event`) Values ('$date','$firstname','$middleinitial','$lastname','$organization', '$donorid','$paymenttype','$nonmon','$Income','$event')";
$sql2 = "INSERT INTO `accounting` (`date`, `transactiontype`, `account`, `description`, `Income`, `Expense`) VALUES ('$date','$transactiontype','$account','$description','$Income','$Expense')";
$query1 = $mysqli->query($sql) or die($mysqli->error.__LINE__);
$query2 = $mysqli->query($sql2) or die($mysqli->error.__LINE__);
//closing connection
mysqli_close($mysqli);
header( 'Location: http://localhost/donations.php' ) ;
UPDATE
you can add donorid simply placing both vars in the query like:
$sql2 = "INSERT INTO `accounting` (`date`, `transactiontype`, `account`, `description`, `Income`, `Expense`) VALUES ('".$date."','".$transactiontype."','".$account."','".$donorid . " " . $description."','".$Income."','".$Expense."')";
this way i just separate donorid and description with a space but you can add anything you want to in plain text:
'".$donorid . " - " . $description."'
After this
$sql = "INSERT INTO donations (date, firstname, middleinitial, lastname,
organization, donorid, paymenttype, nonmon, Income, event)
Values
('$date','$firstname','$middleinitial','$lastname','$organization',
'$donorid','$paymenttype','$nonmon','$Income','$event')";
put
mysql_query($sql);
Please execute the query.
Things I see is ..
First your just executing your $sql2 but not the other $sql statement
Another is while inserting you declared some columns name that is a mysql reserved word (date column)
you should have `` backticks for them..
Refer to this link MYSQL RESEERVED WORDS
additional note: Your query is also vulnerable to sql injection
SQL INJECTION
How to prevent SQL injection in PHP?
Just write after insert on trigger on first table to insert data into another table.
You will have to split $sql2 to 2
1st :-
$sql2 = "INSERT INTO accounting (description) SELECT * FROM donations WHERE donorid='$donorid'"
then another one
"UPDATE accounting SET date='', transactiontype='', account ='', Income='', Expense ='' WHERE description=(SELECT * FROM donations WHERE donorid='$donorid')"
that will take all the information from donoation for the given donorid and list it under description in accounting

Categories