I’m trying to run a query on my table to create a row and get it’s auto incremented ‘id’ number to then be attached to associated records. I am sending the query using php and have tested it on my local WAMP host and my remote host. This is my code:
$myemail = someEmailAddress
$q = mysqli_query($cxn,"INSERT INTO `purchases`(`id`, `email`)
VALUES (NULL , '$myemail');
SELECT LAST_INSERT_ID();") or die(mysql_error());
If I take out this bit:
SELECT LAST_INSERT_ID();
The query runs fine and I get a shiny new record with a correctly auto incremented ‘id’ but put it back in and nothing happens at all. Incidentally, running the same query in the SQL window of phpMyAdmin for my WAMP server I get the result I was looking for.
I think the problem is in running multiple queries in the same string. As far as I can see the syntax is correct so is it a problem with the server I am running?
Let me explain what I want to achieve. I am going into business for myself and I want customers to be able to make bookings online. I want to group individual events that a customer might want to book at the same time, into a single invoice. I have an array ($_SESSION[basket]) collecting the data in the session and at the point of booking I want to create a new record in my ‘purchases’ table which has an auto increment primary key ‘id’, when that is created i need to know the ‘id’ value for that new record so I can link the event they are booking to the purchase through a third table with a many-to-many relationship.
Thanks for your help.
to get the auto generated id off the last sql use this:
just call
$mysqli->insert_idafter the query when you need it.sorry as you are using procedural style you will call it like this
mysqli_insert_id($cxn)