PHP Getting Previous MySQL Query's ID For Next Queries, How? - php

I have a simple question about MySQL and PHP here. Let's say I have this PHP syntax :
mysql_query("INSERT INTO Persons (FirstName, LastName, Age)
VALUES ('Peter', 'Griffin',35)");
on that Person table, there's a column named ID (Auto Increment). how to get Peter Griffin's ID after INSERT process is done without making another SELECT query?
or is it possible to do INSERT for 2 tables using single query? for example I want to INSERT Peter's address as well on Address table :
mysql_query("INSERT INTO Address (City, State, Zip)
VALUES ('Cupertino', 'California', 35212)");
that's all..

$new_id = mysql_insert_id();
Put that right after your INSERT query and it will give you the id.
I would't recommend trying to do two INSERTs in one, and the mysql_insert_id() method will make it simplest for you and your code.

Related

Multiple Insert in different tables with insert new AI

I have a PHP-script in which I can register news users.
Of course I want to insert things like username, password etc. (these values come from the user) but on the other side I want to insert his user_id (new user!) into another table.
My SQL
$sql = "
BEGIN;
INSERT INTO users (username, password, auth_lvl, realname, usercolor) VALUES ('$username', '$password', '$auth_lvl', '$realname', '$usercolor');
INSERT INTO users_startmodules (user_id, startmodule, enabled) VALUES ('(SELECT MAX(user_id)+1 FROM users)', 'newsmodule', '1');
COMMIT;
";
How can I solve this problem and is BEGIN; ... COMIT; the right choice when I want to get the query canceled if just one thing didn't work, because I don't want to have just a few entries in the worst case.
I suggest to change the type of user_id in users table to auto_increment with something like this:
alter table users alter column user_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
Now, Assuming that you have escaped the user input data:
$query="INSERT INTO users (username, password, auth_lvl, realname, usercolor) VALUES ('$username', '$password', '$auth_lvl', '$realname', '$usercolor');"
and run that:
$mysqli->query($query);
then get the userid with mysql_insert_id() function of MySQL or alternatively in PHP:
$userid=$mysqli->insert_id;
and:
$query="INSERT INTO users_startmodules (user_id, startmodule, enabled) VALUES ('$userid', 'newsmodule', '1');";
$mysqli->query($query);
This is too long for a comment.
To get the id that was just inserted, use last_insert_id(). This function is documented here.
Next, the answer to your question is to start a transaction. I would give you the syntax, but it is better for you to read the documentation on transactions before you start using them.
The key idea is that a transaction groups data modifications together. Either all take place or none do. Along the way, you can use commit or rollback, depending on whether or not you want to keep the changes or keep none of the changes.

INSERT and set a field to copy the newly inserted id

Is it possible to INSERT a row, and simultaneously set one of the fields to contain the inserted row's ID? (the "self" id)
I'm trying to avoid using multiple queries if possible (it would be 3 queries in total otherwhise)
Something like this (but probably not):
INSERT INTO thetable (email, phone, activationkey) VALUES ($email, $phone, CONCAT(THIS_NEW_ID, md5($activation) )
Why would you want to store duplicated data?
You could change your table structure and just run:
INSERT INTO thetable (email, phone, activation_suffix)
VALUES ($email, $phone, md5($activation))
And then you have all the data you need.
You can always concat when you query the table:
SELECT CONCAT(id, activation_suffix) activationkey
FROM thetable
WHERE ...
UPDATE
On second thoughts, do you really need the id as part of the activationkey?
I wouldn't want to give any user the id for their record in my table unless it is hashed/encrypted.

PHP MySql Insert columns form one table to another

I want to insert my table data from copying another table with some new given data.
I use this query
$sql = "INSERT INTO table2(name, city, email,money)
hasib,SELECT table1.city, table1.email,
newsletter_subscribers.email
FROM table1 WHERE name='jesy',100";
But its not Work
You must give all columns inside the select statement columns, even constant values, e.g.
insert into table2(name, city, email, money)
select 'hasib', city, email, 100
from table1
where name = 'jesy'
If you want to take values from multiple tables, as your select statement suggests, you must look into joins.

Insert two table rows, then join in relational table by ID

I have a form that takes two names and two email addresses, then a single password.
I am looking to write multiple queries so that the names and emails get inserted in to one table, then the auto-incrementing IDs generated by the database for both of those get inserted into the second table along with the password.
I run one insert query, grab last_insert_id, then run the other and do the same.
As I'm using last_insert_id to grab the auto-incrementing values, is there any way to store both of these as a variable, so that I can easily insert both their relevant IDs into the second table at the same time? Once I use last_insert_id a second time, it seems to lose the first value.
Pointers on methods to use, or a general direction in which to head, would be much appreciated. I like figuring out the exact code to use on my own.
EDIT:
These are my queries, which work fine except the UIDs created are 1 and 2, but inserted in to the second table are IDs 0 and 1. Any idea why?
$your_query = "INSERT INTO MEMBERS (NAME, EMAIL) VALUES ('$your_name', '$your_email')";
$your_id = (mysql_insert_id());
mysql_query($your_query);
$partner_query = "INSERT INTO MEMBERS (NAME, EMAIL) VALUES ('$partner_name', '$partner_email')";
$partner_id = (mysql_insert_id());
mysql_query($partner_query);
$couples_query = "INSERT INTO COUPLES (UID_1, UID_2, PASSWORD, SALT) VALUES ('$your_id', '$partner_id', '$password', '$salt')";
mysql_query($couples_query);
Turns out I had some extra brackets around each mysql_insert_id, and it should have been run after the mysql_query.
$your_query = "INSERT INTO MEMBERS (NAME, EMAIL) VALUES ('$your_name', '$your_email')";
mysql_query($your_query);
$your_id = mysql_insert_id();
$partner_query = "INSERT INTO MEMBERS (NAME, EMAIL) VALUES ('$partner_name', '$partner_email')";
mysql_query($partner_query);
$partner_id = mysql_insert_id();
$couples_query = "INSERT INTO COUPLES (UID_1, UID_2, PASSWORD, SALT) VALUES ('$your_id', '$partner_id', '$password', '$salt')";
mysql_query($couples_query);

PHP ~ Column count doesn't match value count at row 1

I'm creating a registration and I'm using just straight PHP not JavaScript to send my form to the MySQL database, so everything is working fine, no syntax error or anything but I fill out all my information and click 'Register' and it returns a message saying 'Column count doesn't match value count at row 1'.
I'm only 14 so this is pretty confusing for me does anyone have a solution?
This is my INSERT INTO code:
$sql = mysql_query("INSERT INTO users(firstname, lastname, email, password, day, month, year, gender)
VALUES('$firstname','$lastname','$email','$db_password','$day','$month','$year')")
or die (mysql_error());
You are trying to insert 7 values into 8 columns - you are missing the insertion of gender.
The correct code would be:
$sql = mysql_query("INSERT INTO users(firstname, lastname, email, password, day, month, year, gender)
VALUES('$firstname','$lastname','$email','$db_password','$day','$month','$year', '$gender')")
or die (mysql_error());
By the way, if you are not already doing it, I highly recommend escaping the strings first, before passing them to the query like so:
$firstname=mysql_real_escape_string($firstname)
You should do this with all variables above. Here you can find more about the escape function.
With your code there, I see you forget to insert $gender.
When inserting data into a MySQL table, you will have to specify which data goes into which column. You do this by specifying the column names before the VALUES part:
INSERT INTO tblA (col1, col2) VALUES ('value1','value2');
If you omit that information, MySQL will expect all columns:
If your table is like this:
CREATE TABLE tblA (
col1 INT,
col2 INT
);
You can insert information like this:
INSERT INTO tblA VALUES ('value1', 'value2');
If you omit column names and do no specify values for all columns, MySQL will give the "Column count doesn't match value count at row" error will occur, as MySQL doesn't know what to put in the missing columns. With the table structure as above,
INSERT INTO tblA VALUES ('value1');
will result in that error.
In non-strict mode, MySQL will insert default values for omitted column names.
You have missed a value for gender column (the last one)
You are completely missing the gender value:
$sql = mysql_query("INSERT INTO users(firstname, lastname, email, password, day, month, year, gender)
VALUES('$firstname','$lastname','$email','$db_password','$day','$month','$year', 'gender goes here')")
or die (mysql_error());

Categories