I'm importing a .sql file via php. My .sql file contains multiple tables and I want the last inserted id of a particular table.
So, how to get last inserted id of any table by table name?
Any idea how to get the id?
Please don't suggest, get id by select query to get MAX id.
As long as auto_increment is defined, that last inserted auto increment id can be retrieved from information_schema.tables:
select IF(auto_increment = 1,
'No row has been inserted',
auto_increment - ##auto_increment_increment) As LastInsertedId
from information_schema.tables
where table_schema = 'DBName' and table_name = 'TableName';
This can be done in both mysql and mysqli.
$conn = mysqli_connect($servername, $username, $password, $dbname);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('abc', 'xyz', 'abc#example.com')";
if (mysqli_query($conn, $sql)) {
$last_id = mysqli_insert_id($conn);}
in mysql
mysql_connect($servername, $username, $password);
mysql_select_db($dbname);
$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('abc', 'xyz', 'abc#example.com')";
if (mysql_query($sql)) {
$last_id = mysql_insert_id();}
We had.
id | value
1 | 10
3 | 20
Then we inserted 2 | 15, so it had become
id | value
1 | 10
2 | 15
3 | 20
(Remind, we have a .sql file, not a live connection)
And now you want to know, that the last one was 2? If so — it's impossible. .sql file doesn't keep that kind of information, only bare data and some meta.
Try these functions
If you're using PDO, use PDO::lastInsertId
If you're using Mysqli, use mysqli::$insert_id
But if you have to, use mysql_insert_id.
Related
I have a database with following table test_users:
| id | Username | Password |
| 1 | pat | ***** |
| 2 | roger | ***** |
| 3 | luke93 | ***** |
And to insert a new row I use following code, and it works fine:
$sql = $conn->prepare("INSERT INTO `test_users` (`Username`, `Password`) VALUES (?,?)");
$sql->bind_param('ss',$name, $email);
But now i am trying to make a "update profile"-page and I wanted to use ON DUPLICATE KEY. That means I need to check if idexists and if so update the row. Neither Username or Password is Unique, but id is. I have a $_SESSION["id"] which is available if the user is logged in. Can I use that in some way?
So how do I write a SQL-sentence that finds out if id exist, and if so, overwrite it with ON DUPLICATE KEY (or a better way)?
first write selct query and count num rows if its 0 then insert query fire else update query
UPDATE works the same as an insert. You just need to pass the WHERE condition.
You can do this with the following code, Try it
$id = $_SESSION['id'];
$sql = "UPDATE test_users SET Username=?, Password=? WHERE id=?";
$stmt = $conn->prepare($sql);
$stmt->bind_param($Username, $Password, $id);
$stmt->execute();
Assign unique key of your unique field and try below query
Insert into a MySQL table or update if exists
INSERT INTO test_user(id, username, password) VALUES(1, "test", "test") ON DUPLICATE KEY UPDATE
username="test", password="test"
Use INSERT ... ON DUPLICATE KEY UPDATE
QUERY:
INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE
name="A", age=19
credits to Donnie
By according to this question I have 2 table Source and details .
The Source table is as follows:
+----+----------+---------------+-----------+
| id | item_name|items_download | category |
+----+----------+---------------+-----------+
| |
+----+----------+---------------+-----------+
The details table is as follows:
+------+----------+-----+------+
| name | download | time| ip |
+------+----------+-----+------+
| |
+------+----------+-----+------+
At first step I want to get data from Source table (in real time) and put into details table by this code:
$get= "INSERT INTO `details` (`name`, `download`) SELECT `Source`.`item_name`,`Source`.`items_download` FROM `Source`"
At next step I want to get visitor IP address for each file.
for example if someone downloaded testfile I want to have this output:
+----------+---------+--------------+-----------+
| name | download | time | ip |
+----------+----------+-------------+-----------+
| testfile | 32 |download time|192.168.0.0|
+----------+----------+-------------+-----------+
| file2 | 0 | | |
+----------+----------+-------------+-----------+
To do this i use this code:
$ip = $_SERVER['REMOTE_ADDR'];
$update = "UPDATE details SET ip = '$ip', dldate = NOW()"
But its happened for all files, all of the file get same IP and time. I know its need a condition WHERE but I don't know what should I type as a condition to get IP address for each file that download.
Imho you don't need any UPDATE query. You just do an INSERT everytime a user requests a file:
<?php
$fileid = $_GET['fileid'];
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$sql = "SELECT * FROM Source WHERE id=" . (int)$fileid;
foreach ($pdo->query($sql) as $row) {
$statement = $pdo->prepare("INSERT INTO details (name, download, time, ip) VALUES (?, ?, NOW(), ?)");
$statement->execute(array(
$row['item_name'],
$row['items_download'],
$_SERVER['REMOTE_ADDR'],
));
}
?>
Some hints on the code above:
Use prepared statements - never inject any value directly into an SQL string.
It might be useless to insert file_name and items_download into the details table everytime. You have this information in your table "Source" anyway. So usually you would just put Source.id into your details table.
You should use your id column, which you have in your first table view, but it stragely disappears in the later ones.
Your id column should also be your PRIMARY_KEY AUTO INCREMENT column. Then each row has its own unique and indexed id.
But aside from that, what do you use to identify which file the user downloads? If it's the filename then simply use that:
EDIT: Add an id column to your details table!
$update = "UPDATE details SET ip = '$ip', dldate = NOW()
WHERE name = '$fileNameValue' LIMIT 1"
On a related note, you can not update multiple columns with the same shorthand reference of device = ip = '$ip' you have to specify each column in isolation and with an absolute target data to insert (here, the variable) .
If this is a typo you should edit and update your question.
Please also see Gerfried's answer regarding using prepared statements, they are the way you should be doing these things.
I think you need to get the session of user when he downloads the file and add it to the WHERE condition.
I have a query that returns the next auto-increment value (id), and I use that value when I'm inserting data in table t_name.
SELECT AUTO_INCREMENT id
FROM information_schema.TABLES
WHERE TABLE_SCHEMA = 'db_name'
AND TABLE_NAME = 't_name'
But I want that this query gives a different value each time. E.g. Me and my pal are inserting data in db at same time, so I will get one id, he will get another. When I run this query, I want it to give me a different and incremented value each time.
Is it possible? Or do I have to create tables with sequences?
You can insert and than get the last inserted id:
$connection = mysqli_connect($rv, $username, $pass, $mydatabase);
$result = $connection->query('INSERT INTO mytable (id, name) VALUES("", "myName")');
if($result)
{ $lastId = connection->insert_id;
// so something with $lastId...
}
I've two tables in my joomla 2.5 site component that trying to inset two tables and first table ID should be second table foreign-key.
Table: MYTABLE
-------------------------------------------------------------
| mytab_id | mytab_name | mytab_country | mytab_city |
-------------------------------------------------------------
Table: YOURTABLE
-------------------------------
| yourtab_id | group_name |
-------------------------------
mytab_id is auto increment value and that should insert to second table yourtab_id as foreign-key.
How should I insert data to both tables as first table id value to second table id.
I've tried below code but it doesn't work.
$insert_query = "INSERT INTO #__mytable (mytab_name, mytab_country, mytab_city) VALUES ('". $mytab_name."',".$mytab_country.",'".$mytab_city."'); ";
$db->setQuery( $insert_query );
$db->query();
$insert_query2 = "INSERT INTO #__yourtable (yourtab_id, group_name) VALUES (".LAST_INSERT_ID().", 2);";
$db->setQuery( $insert_query2 );
$db->query();
Thanks,
Try This,
In Joomla you can get the last insert id using
$db->insertid();
For details about Joomla DB Queries, Also try to use more standards in your query.
$db = JFactory::getDbo();
$query = $db->getQuery(true);
// Insert columns.
$columns = array('mytab_name', 'mytab_country', 'mytab_city');
// Insert values.
$values = array($db->quote($mytab_name), $db->quote($mytab_country), $db->quote($mytab_city));
// Prepare the insert query.
$query
->insert($db->quoteName('#__mytable'))
->columns($db->quoteName($columns))
->values(implode(',', $values));
// Set the query using our newly populated query object and execute it.
$db->setQuery($query);
$db->query();
You can make your query standards like here
Hope it helps..
You can use the available php function to achieve this
mysql_insert_id()
you can refer Here For Documentation in php
i had following table and columns
Table Name = users
column = user_id, name, email, password, status, identity
i'm using following query for insert data to table users
$name = mysql_real_escape_string($_POST['name']);
$email = mysql_real_escape_string($_POST['name']);
$password = mysql_real_escape_string($_POST['txtPassword']);
$password = md5($password); //===Encrypt Password
if(isset($_POST['btnRegister'])) //===When I will Set the Button to 1 or Press Button to register
{
$query = "insert into users(name,email,pasword,status,identity)values('$name','$email','$password','1','0')";
$res = mysql_query($query);
header('location:success_register.php');//Redirect To Success Page
}
what i am asking is, i want store last id to column identity also
for example: if last user_id= 10, identity also will be = 10. i mean get last id then store that id to identity column
Result will be look like this
user_id name email password status identity
5 aa aaa#ab.com **** 1 5
6 bbb bbb#ac.com **** 1 6
how to do it,?
In MYSQL, you have alternative possibility to find it, when you think last_insert_id() is not working. You may require to have SELECT privilege on INFORMATION_SCHEMA and its tables.
If you have that privileges, try the following query.
$query = "insert into users( name, email, pasword, status, identity )"
. " values( '$name', '$email', '$password', '1',"
. " ( SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES"
. " WHERE TABLE_NAME='users' and TABLE_SCHEMA=DATABASE() )"
. " )";
And, lastly, suggesting to stop using deprecated API.
Save last insert id like this:
$id = mysql_insert_id();
and use it in next insert
You are looking for:
mysql_insert_id()
mysqli_insert_id(mysqli $link)//for mysqli
PDO::lastInsertId()//for PDO
Other Approach:
if your id column is auto increment and not random then you can select the max id(everytime just after your insert query) from the users table and insert it into whatever column you want.
$id=mysql_result(mysql_query(select max(user_id)
from users),0);
Dont use mysql_ as they are depracated.*
here is what you are looking for. Select max(user_id)+1 and store it in a variable.
Now you need to pass this variable in user_id and identity parameter.
Note that even though user_id is auto increment, it will allow you to insert the new row with specified user_id
i think you can also put it like this
$lastID = MySQLI_insert_id($DBcon); //where Dbcon is your connection to your database
and then
$query = "insert into users(name,email,pasword,status,identity)values('$name','$email','$password','1','$lastID')";
$res = mysql_query($query);
I think you need to insert number of rows in the table after the insert:
It may useful to you
$query = "insert into users(name,email,pasword,status,identity)values('$name','$email','$password','1','0',(select COUNT(*)+1 FROM users))";