Sorry, let me try to explain .... recordID auto increments and is my primary key ..... LISTINGID refers to the ID in a different table. In this table 1 need to increment recordListingID for each record that has the same LISTINGID. My insert statement inserts upto 10 records that have the same LISTINGID I need the the recordListingID to start at 1 and so on.
Hi guys
I am inserting records into mysql from php it can be 1 or more records I need one of the cols to increment with the first entry being 1 here is my insert code
mysql_query("INSERT INTO car_listing_images (recordID, recordText, recordListingID, LISTINGID) VALUES ('', '$fileName', '??', '$listingid')");
where I have put ?? is the col that needs to increment. How can i achieve this?
Thanks in advance!
You can use the built in Auto_Increment function of MySql
AUTO_INCREMENT
http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html
MySql would increment the specified field by 1 (Or what ever interval you set)
You may use user-defined variables
A preface: If you need to have 2 fields that increment, but are not tied to each other, you are probably doing it wrong. It might be better to not have recordListingID and instead just use the recordID as they will probably be the same number.
If your tables are running InnoDB you can create transactions. Then you can try something like this:
<?php
mysql_query('START TRANSACTION');
$recordListingId = mysql_result(mysql_query("SELECT count(*)+1 as num FROM car_listing_images WHERE LISTINGID=$listingid"), 'num', 0);
mysql_query("INSERT INTO car_listing_images (recordID, recordText, recordListingID, LISTINGID) VALUES ('', '$fileName', '$recordListingId', '$listingid')");
mysql_query('COMMIT');
?>
If you don't have innodb, try using a stored procedure.
Alter your table structure to include the AUTO_INCREMENT attribute for your recordListingID column, then omit the column from your insert to have it auto-populate with an incremental number.
I.e: mysql_query("INSERT INTO car_listing_images (recordID, recordText, LISTINGID) VALUES ('', '$fileName', '$listingid')");
You can initialise the variable as 1 and use the post-increment operator:
$value = 1;
for(...){
$sql = 'INSERT ...';
$value++;
}
I don't know if I really understand your question.
If you're wanting to increment a column with every record, it should be defined as an AUTO_INCREMENT column. This way, in your INSERT statement if you insert NULL into that column, it will go up every time.
Alternatively you could do fieldname+1, but AUTO_INCREMENT is always preferred.
As per my comment, you could do something like this:
$row = mysql_fetch_assoc(mysql_query("SELECT MAX(recordListingID) AS `max` FROM car_listing_images"));
$next_id = $row['max'] + 1;
mysql_query("INSERT INTO car_listing_images (recordID, recordText, recordListingID, LISTINGID) VALUES ('', '$fileName', '$next_id', '$listingid')");
I would still seriously recommend against this, it's a much much better implementation to use an AUTO_INCREMENT field.
After your last comment I would suggest the following. You will not be able to do this in MySQL directly (unless you use a variable, but this may go wrong if you're inserting multiple RecordIDs too).
$next_id = 0;
foreach ($insert as $insert_stmt) {
$next_id++;
mysql_query("INSERT INTO car_listing_images (recordID, recordText, recordListingID, LISTINGID) VALUES ('', '$fileName', '$next_id', '$listingid')");
}
i think i know what you were/are trying to accomplish. there may be a better way to it, but what i did was to "select max(id)+1 as nextId from table" and store that in a variable that i used in the secondary id field that you called "recordListingID."
that way the first row you insert will have the same id and recordListingID, but each other row will auto_inc the id, but the recordListingID will be the same as the first.
in my situation, there is only one user doing this at a time, so there is no chance of errors, but in a multi-user situation, you may want to modify this to watch out for people doing inserts at the same time. like maybe marking the last row so your query knows it's finished so you could so something like "select max(id)+1 as nextId from table where lastRow =1" or something like that.
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 been working on my first webapp and I hit a bit of a wall. I have a table in my db set up as follows:
student_id(student_id, first_name, last_name, bdate, etc...)
I also have several tables for classes set up similarly to this
class_table(id, student_id, quiz_1, quiz_2, etc....)
student_id is how I would like to track everything, from my understanding, this would be a primary key that would become a foreign key on the class tables.
What I would like to do is create an entry for the student on each class table when the php script I am writing creates a new student. This is what my query looks like:
$query = "INSERT INTO student_id(0, '$first_name', '$last_name'.... etc);".
"INSERT INTO class_table(0, LAST_INSERT_ID(), '$quiz_1', $quiz_2'...etc)";
Is this the right way to do this? I keep getting an error from my mysqli_query... so I am guessing this is where the problem is. How would I achieve this?
mysqli_query() (and mysql_query()) will only execute a single query. You would need to perform two calls to mysqli_query() or use mysqli_multi_query(), which will execute multiple queries in one call.
You're missing the VALUES clause:
$query = "INSERT INTO student_id VALUES (0, '$first_name', '$last_name'.... etc);".
"INSERT INTO class_table VALUES (0, LAST_INSERT_ID(), '$quiz_1', '$quiz_2'...etc)";
and you will need to use the mysqli_multi_query() function. See the example at http://www.php.net/manual/en/mysqli.multi-query.php#106126:
if ($mysqli->multi_query($query)) {
$i = 0;
do {
$i++;
} while ($mysqli->next_result());
}
if ($mysqli->errno) {
echo "Batch execution prematurely ended on statement $i.\n";
var_dump($statements[$i], $mysqli->error);
}
You could also create a stored procedure, and call it with all the needed parameters:
CALL insert_student('$first_name', '$last_name', '$quiz_1', $quiz_2', ... etc);
Here's an example:
CREATE PROCEDURE add_student(
IN v_first_name VARCHAR(50),
IN v_last_name VARCHAR(50),
IN v_quiz_1 VARCHAR(255),
IN v_quiz_2 VARCHAR(255)
)
DETERMINISTIC
MODIFIES SQL DATA
proc: BEGIN
START TRANSACTION;
INSERT INTO student_id VALUES (0, v_first_name, v_last_name);
IF ROW_COUNT() <= 0 THEN
ROLLBACK;
SELECT 0 AS result;
LEAVE proc;
END IF;
INSERT INTO class_table VALUES (0, LAST_INSERT_ID(), v_quiz_1, v_quiz_2);
COMMIT;
SELECT 1 AS result;
END;
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.
I have a simple sql query adding a new row to a database and need it to return the a field back to Javascript. The field does Auto_increment but stupildy I called it 'itemId' so mysql_insert_id doesnt work and I don't think I have time to go and amend all the php files that use 'itemId'
Here's my code if it helps:
$addMainItem = "INSERT INTO newsItems (itemId, title, date, tags, location, latitude, longitude, visibleFrontpage, introText, fullDome, liveEvent, customServing, visitorAttraction, retail, digitalCinema, visiblePublic, thumbPath, links, smallDesc) VALUES ('','$title','$date','$tags','$loco','$lat','$long','$visiFront','$intro','$dome ','$live','$custom','$attrac','$retail','$cinema','$public','$thumbPath','$links','$smallDesc')";
$result = mysql_query($addMainItem) or die('error '.mysql_error());
if($result) echo (mysql_insert_id());
I've never heard that naming a column itemId breaking mysql_isert_id().
But you can just select the last inserted record if auto_increment is working.
SELECT * FROM newsItems ORDER BY itemId DESC LIMIT 1
You can put the select statement into a transaction with the insert statement if you're using innoDB and you're worried about a race condition.
mysql_query("SELECT LAST_INSERT_ID()");
Isn't it what are you looking for?
I'm new to php. So, please forgive me if this seems like a dumb question.
Say i have a MySQL insert statement insert into table (a,b) values (1,2),(3,4),(5,6). table 'table' has a auto increment field called 'id'.
how can I retrieve all the ids created by the insert statement above?
It will be great if i get an example that uses mysqli.
You can't. I would suggest that you maintain your own ids (using guid or your own auto-increment table) and use it when you insert into the table.
But it's possible to get the auto-increment value for the last inserted using LAST_INSERT_ID():
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
AngeDeLaMort's answer is almost right. Certainly, the most appropriate way to deal with the problem is to insert one row at a time and poll the insert_id or generate the sequence elsewhere (which has additional benefits in terms of scalability).
I'd advise strongly against trying to determine the last insert_id and comparing this the most recent insert_id after the insert - there's just too may ways this will fail.
But...an alternative approach would be:
....
"INSERT INTO destn (id, data, other, trans_ref)
SELECT id, data, other, connection_id() FROM source";
....
"SELECT id FROM destn WHERE trans_ref=connection_id()";
....
"UPDATE destn SET trans_ref=NULL where trans_ref=connection_id()";
The second query will return the ids generated (note that this assumes that you use the same connection for all 3 queries). The third query is necessary because connection ids to go back into the pool when you disconnect (i.e. are reused).
C.
In some cases, if you have another identifier of sort such as a UserID, you could filter your query by UniqueID's greater than or equal to mysql_insert_id(), limit by the number of affected rows and only display those by the user. This would really only work inside of a transaction.
$SQL = "INSERT INTO Table
(UserID, Data)
VALUES
(1,'Foo'),
(1,'Bar'),
(1,'FooBar')";
$Result = mysql_query($SQL);
$LastID = mysql_insert_id();
$RowsAffected = mysql_affected_rows();
$IDSQL = "SELECT RecordID
FROM Table
WHERE UserID = 1
AND RecordID >= '$LastID'
LIMIT '$RowsAffected'";
$IDResult = mysql_query($IDSQL);
as a follow up to AngeDeLaMort:
You could seperate your inserts and do it something like this:
$data = array (
array(1,2),
array(3,4),
array(5,6)
);
$ids = array();
foreach ($data as $item) {
$sql = 'insert into table (a,b) values ('.$item[0].','.$item[1].')';
mysql_query ($sql);
$id[] = mysql_insert_id();
}
Now all your new id's are in the $id array.
Maybe I can do this
$insert = "insert into table (a,b) values (1,2),(3,4),(5,6)";
$mysqli->query($insert);
$rows_to_be_inserted=3;
$inserted_id = $mysqli->insert_id // gives me the id of the first row in my list
$last_row_id = ($inserted_id+$rows_to_be_inserted)-1;
$mysql->query("select * from table where id between $inserted_id and $last_row_id");
what to you guys say?