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))";
Related
I have two tables first called messages and the other called messages_reply.
I used this code to insert into messages table:
$query = "INSERT INTO `messages` VALUES('', '$id', '$otherId', '')";
$query_run = mysqli_query($connect, $query);
I have the first column auto_increment thats why I left it empty by writing ''
Now i want this auto_increment value that i have inserted to be inserted in the other table called messages_reply
Do I have to create another query to return it or there is an instant way to insert it here and there?
you have to select the last id on table messages first, then you can insert that last id + 1 into messages reply
$query_sel_last_id = "SELECT id FROM messages ORDER BY id desc LIMIT 1"; // select the last id
after that, you only need to insert to messages_reply, remember to plus the value
$query_sel_last_id + 1
EDIT: gordon's solution is better and simpler, LAST_INSERT_ID()
I have a database of Users and another table for Teachers. Teachers have all the properties as a user but also an e-mail address. When inserting into the DB how can I insert the info, ensuring that the ID is the same for both?
the ID currently is on automatic incrament.
this is what I have at the moment:
$sqlQuery="INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID)
VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$result=mysql_query($sqlQuery);
$sqlQuery = "INSERT INTO teacher(email) VALUES ('$myEmail')";
$result=mysql_query($sqlQuery);
thank you!
use MYSQL function LAST_INSERT_ID()
OR php mysql http://ro1.php.net/manual/en/function.mysql-insert-id.php
why to use separate table for teachers. instead, you can have email field with in user table and additional field with flag (T ( for teacher) and U (for user). Default can be a U. This have following Pros.
Will Not increase table size as email would be varchar
Remove extra overhead of maintaining two tables.
Same Id can be used
If you want to have that as separate table then answer you selected is good one but make sure last insert id is called in same connection call.
After the first insert, fetch the last inserted id:
$last_id = mysqli_insert_id(); // or mysql_insert_id() if you're using old code
Or you could expand your second query and use mysql's integrated LAST_INSERT_ID() function:
$sqlQuery = "INSERT INTO teacher(id, email) VALUES ((SELECT LAST_INSERT_ID()), '$myEmail')";
Try this:
$sqlQuery="INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID)
VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$result=mysql_query($sqlQuery);
$id = mysql_insert_id();
$sqlQuery = "INSERT INTO teacher(id, email) VALUES (' $id ','$myEmail')";
$result=mysql_query($sqlQuery);
Insert data into two tables & using the same ID
First method
$sqlQuery1 = "INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID) VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$result1 = mysqli_query($conn, $sqlQuery1);
$lastID = mysqli_insert_id($conn);
$sqlQuery2 = "INSERT INTO teacher(email, lastID) VALUES ('$myEmail', 'lastID')";
$result2 = mysqli_query($conn, $sqlQuery2);
If the first method not work then this is the second method for you
$sqlQuery1 = "INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID) VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$result1 = mysqli_query($sqlQuery1);
$sqlQuery2 = "INSERT INTO teacher(email) VALUES ('$myEmail')";
$result2 = mysqli_query($sqlQuery2);
You can set the Foreign Key in your database table (phpMyAdmin/ MySQL Workbench) to let the Foreign Key follow the Primary Key (ID). Then the data after insert will auto-follow the Primary Key ID.
Example here,
Teachers table set ID - Primary Key
Users table set UserID - Foreign Key (will follow the Teachers table ID)
if you're using MySQL WorkBench, you can refer to this link to set a foreign key.
https://dev.mysql.com/doc/workbench/en/wb-table-editor-foreign-keys-tab.html
Hope I can help any of you.
Though you can use the LAST_INSERT_ID() function in order to get the last insert id, the best approach in this case is to create a column reference to user id table.
teacher
id | user_id | email
So the teacher.id could be anyting, but the user_id column is the real reference to user table.
If you use InnoDB table, you can make the database consistent using Foreign keys
You Should Use A Transaction In MySQL. First insert In One Table And GET LAST_INSERT_ID().
Insert LAST_INSERT_ID() In Second Table.
$sqlQuery="INSERT INTO user(firstName,lastName,DOB,title,password,classRoomID)
VALUES('$myFirstName','$myLastName','$myDOB','$myTitle','$newPassword','$myClassRoom')";
$sqlQuery = "INSERT INTO teacher(LAST_INSERT_ID(), email) VALUES (' $id ','$myEmail')";
$result=mysql_query($sqlQuery);
I have a PostGreSQL database with the following data model:
CREATE TABLE staff (s_id serial UNIQUE, name, username, password, email)
CREATE TABLE institution (i_id serial UNIQUE, name);
CREATE TABLE isStaffOf (i_id, s_id); //foreign key references
When a user submits the form I have a PHP script which writes the information to first two data tables and that automatically generates the s_id and i_id values. Great!
I've tried out a few PHP modifications to get the system writing both the s_id and i_id into the isStaffOf relation so it can enforce the explicit 1..1 relationship required for my project but on submit it says I have an insufficient data type. See below for the PHP code.
$name = $_POST["name"];
$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
$institution = $_POST["institution"];
$conn = pg_connect("host=***** port=**** dbname=****** user=**** password=******");
$staffWrite = pg_query("INSERT INTO staff(name, username, password, email) VALUES ('$name', '$username', '$password', '$email')");
$instiWrite = pg_query("INSERT INTO institution(name) VALUES ('$institution')");
$instiFK=pg_query("SELECT i_id FROM institution WHERE name='$institution'");
$staffFK=pg_query("SELECT s_id FROM staff WHERE name='$username'");
$sql=("INSERT INTO isstaffof(i_id, s_id) VALUES ('$instiFK', '$staffFK')");
$result = pg_query($sql);
That is the script I have at the moment but its not working. Any ideas on how to fix this so that when a user submits all the data tables will be filled and the referential integrity enforced? I'm almost there and still trying things out but to no avail.
The error message:
ERROR: invalid input syntax for integer: "Resource id #4" LINE 1: INSERT INTO isstaffof(i_id, s_id) VALUES ('Resource id #4', ...
Please let me know if you need more explanation but I'm sure its clear what I want to achieve and I'm convinced I can do it without so many pg_query calls.
As of PostgreSQL version 9.1, you can use a single query to INSERT in all 3 tables, a writable common table expression:
WITH
step_1 AS(
INSERT INTO staff (name) VALUES('Frank') RETURNING s_id
),
step_2 AS (
INSERT INTO institution (name) VALUES('PostgreSQL') RETURNING i_id
)
INSERT INTO isStaffOf (i_id, s_id) SELECT i_id,s_id FROM step_1, step_2;
Simple, fast and reliable.
You could do some other tricks as well, when some records already exists and just want to select the primary key value.
WHEN creating the isstaffof table, you at least have to specify the datatypes, and you can specify they are foreign keys.
CREATE TABLE isstaffof
(i_id BIGINT REFERENCES institution(i_id)
, s_id BIGINT REFERENCES staff(s_id)
);
NOTE: avoid using MixedCase for identifiers. It might cause terrible problems, if you ever have to port to a different DBMS platform.
UPDATE: Just put it in a plain INSERT INTO ... SELECT ... FROM ... statement.
CREATE TABLE staff (s_id serial UNIQUE, sname varchar);
CREATE TABLE institution (i_id serial UNIQUE, iname varchar);
CREATE TABLE isstaffof
(i_id BIGINT REFERENCES institution(i_id)
, s_id BIGINT REFERENCES staff(s_id)
);
INSERT INTO isstaffof(i_id,s_id)
SELECT i.i_id,s.s_id
FROM staff s, institution i
WHERE i.iname='$institution'
AND s.sname = '$staff'
;
Now, you can wrap that into your front-end code.
You'll have to fetch the result with pg_fetch_assoc or something similar. The way you're using it now you're passing the whole pg_query resource as an integer - obviously php can't convert that to a valid integer.
$name = $_POST["name"];
$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
$institution = $_POST["institution"];
$conn = pg_connect("host=***** port=**** dbname=****** user=**** password=******");
$staffWrite = pg_query("INSERT INTO staff(name, username, password, email) VALUES ('$name', '$username', '$password', '$email')");
$instiWrite = pg_query("INSERT INTO institution(name) VALUES ('$institution')");
$instiFK=pg_query("SELECT i_id FROM institution WHERE name='$institution'");
$rowInsti = pg_fetch_assoc($instiFK);
$staffFK = pg_query("SELECT s_id FROM staff WHERE name='$username'");
$rowStaff = pg_fetch_assoc($staffFK);
$result = pg_query("INSERT INTO isstaffof(i_id, s_id) VALUES (".$rowInsti['i_id'].", ".$rowStaff['s_id'].")");
As an alternative you could probably use pg_last_oid directly after every insert to get the id. (Even more beautiful would the RETURNING-solution be. Just read the comments on the php.net page)
I recently asked a question about writing to multiple tables: PHP/MySQL insert into multiple data tables on submit
I have now tried out this code and there are no errors produced in the actual code but the results I am getting are strange. When a user clicks register this 'insert.php' page is called and the code can be found below.
<?php
$username = $_POST["username"];
$password = $_POST["password"];
$institution = $_POST["institution"];
$conn = pg_connect("database connection information"); //in reality this has been filled
$result = pg_query($conn, "INSERT INTO institutions (i_id, name) VALUES (null, '$institution') RETURNING i_id");
$insert_row = pg_fetch_row($result);
$insti_id = $insert_row[0];
// INSTITUTION SAVED AND HAS ITS OWN ID BUT NO MEMBER OF STAFF ID
$resultTwo = pg_query($conn, "INSERT INTO staff VALUES (NULL, '$username', '$password', '$insti_id'");
$insert_rowTwo = pg_fetch_row($resultTwo);
$user_id = $insert_rowTwo[0];
// USER SAVED WITH OWN ID AND COMPANY ID
// ASSIGN AN INSTITUTION TO A STAFF MEMBER IF THE STAFF'S $company_id MATCHES THAT OF THE
// INSTITUION IN QUESTION
$update = pg_query($conn, "UPDATE institutions SET u_id = '$user_id' WHERE i_id = '$insti_id'");
pg_close($conn);
?>
What the result of this is just the browser waiting for a server response but there it just constantly waits. Almost like an infinite loop I'm assuming. There are no current errors produced so I think it may be down to a logic error. Any ideas?
The errors:
RETURNING clause is missing in the second INSERT statement.
Provide an explicit list of columns for your second INSERT statement, too.
Don't supply NULL in the INSERT statements if you want the column default (serial columns?) to kick in. Use the keyword DEFAULT or just don't mention the column at all.
The better solution:
Use data-moidifying CTE, available since PostgreSQL 9.1 to do it all in one statement and save a overhead and round trips to the server. (MySQL knows nothing of the sort, not even plain CTEs).
Also, skip the UPDATE by re-modelling the logic. Retrieve one id with nextval(), and make do with just two INSERT statements.
Assuming this data model (you should have supplied that in your question):
CREATE TABLE institutions(i_id serial, name text, u_id int);
CREATE TABLE staff(user_id serial, username text, password text, i_id int);
This one query does it all:
WITH x AS (
INSERT INTO staff(username, password, i_id) -- provide column list
VALUES ('$username', '$password', nextval('institutions_i_id_seq'))
RETURNING user_id, i_id
)
INSERT INTO institutions (i_id, u_id, name)
SELECT x.i_id, x.user_id, '$institution'
FROM x
RETURNING u_id, i_id; -- if you need the values back, else you are done
Data model
You might think about changing your data model to a classical n:m relationship.
Would include these tables and primary keys:
staff (u_id serial PRIMARY KEY, ...)
institution (i_id serial PRIMARY KEY, ...)
institution_staff (i_id, u_id, ..., PRIMARY KEY(i_id, u_id)) -- implements n:m
You can always define institution_staff.i_id UNIQUE, if a user can only belong to one institution.
I'm pulling data from a calendar feed and each event in the calendar has a unique $EventID string. I'm using PHP.
I have a SQL database with an Event_ID column. These IDs are strings. I need to be able to compare my $EventID against the Event_ID column and put in in the database if it's not there.
I have a primary key set up to auto increment in the database, and I was thinking I can set up a loop to increment through those and compare each to the $EventID, but I'm wondering if there is a better way-maybe a PHP function I don't know about?
I've got a whole lot of code, but basically I've got:
<?php
$EventID = $event->id; //This is the event ID
mysql_query("INSERT INTO myTable
(Event_ID, Date_added, Date_edited)
VALUES
('$EventID', '$dateAdded', '$lastEdited')");
?>
So how do I set up a conditional to check all the Event_IDs that are already in the database against the $EventID?
$query = "SELECT * FROM `myTable` WHERE `Event_ID`='$EventID' ";
$result = mysql_query($query);
if (!mysql_num_rows($result))
// INSERT QUERY
Check if the Event ID is present, If not insert it
You could just skip the "Select" query and do an "INSERT IGNORE" instead:
mysql_query("INSERT IGNORE INTO myTable
(Event_ID, Date_added, Date_edited)
VALUES
('$EventID', '$dateAdded', '$lastEdited')");
this will leave existing Event_id's, and just add new records if required.