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);
Related
I have written my sql below and it works. As I've set my particulars_id to autoincrement, i have to use Last_Insert_ID() in order for the database to use the next id using auto increment. However, i would like to store that value into a php variable. Is that possible?
$addquery = "INSERT INTO Particulars (Particulars_ID, Name, Identification_Number, Number, Nationality, Status, Remarks)
VALUES(LAST_INSERT_ID(),'$_POST[newname]', '$_POST[newic]','$_POST[newnumber]','$_POST[newnationality]','$_POST[newstatus]','$_POST[newremarks]')";
When you insert a row into a table that has an AUTO_INCREMENT field that field will be incremented automatically as the name implies. You don't need to tell MySQL to increment it, you don't have to provide a value for the auto-increment field at all.
So to begin with, remove the call to LAST_INSERT_ID() from your query:
$addquery = "INSERT INTO Particulars (Name, Identification_Number, Number, Nationality, Status, Remarks)
'$_POST[newname]', '$_POST[newic]','$_POST[newnumber]','$_POST[newnationality]','$_POST[newstatus]','$_POST[newremarks]')";
Notice how I completely removed the Particulars_ID from the query.
Second, this is not directly related to your question but your query is vulnerable to SQL Injection. When accepting user input you should avoid concatenating it to your query, instead use Prepared Statements and modify your query like this:
$addquery = "INSERT INTO Particulars (Name, Identification_Number, Number, Nationality, Status, Remarks)
VALUES(?,?,?,?,?,?)";
You can then prepare a statement and bind the values from $_POST. This essentially sanitizes user input. Read more about prepared statements here
START OF EDIT
An example of binding the real values to the ? placeholders using PDO:
//First prepare the statemt
$db->prepare("INSERT INTO Particulars (Name, Identification_Number, Number,Nationality, Status, Remarks)
VALUES(?,?,?,?,?,?)";
//Start binding values to placeholders
$db->bindValue(1, $_POST['name']);
$db->bindValue(2, $_POST['Identification_Number'];
$db->bindValue(3, $_POST['Number'];
//Bind the rest of the values in the same way
END OF EDIT
About the id of the last inserted row you will need to run a separate query to get it. So after you run the above query and if insertion is successful you can
run a query like this:
SELECT LAST_INSERT_ID() AS id FROM Pariculars
I am looking for a way to write 2 MySQL queries into 1 PHP variable since I am looking to insert into 2 different tables.
I am building a simple registry page where the name is in table "users" and email and password is in table "auth".
Tables as follows:
table users
table auth
so I thought something like this:
$sql = "INSERT INTO users VALUES('', '$name','','') INSERT INTO auth VALUES('', '', '$email', $password', '')";
since I am using
$result = mysql_query($sql);
I would need to have the query in one variable ($sql) as far as I understand.
Thanks.
If the two tables are related, a straightforward insert will put the data in no problem. Then just get your data into a $result variable.
SELECT username, auth
FROM users
INNER JOIN auth
ON users.id=auth.id;
Just add ; to sql query to execute double query
$sql = "INSERT INTO users VALUES('', 'name');INSERT INTO auth
VALUES('', '', '$email', $password', '')";
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.
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());
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.