Sql select max id from table - php

I want to get the Max userID from tblLogin and add 1
This value i want to put into a string to insert into the table
$sql2="INSERT INTO tblLogin (Gebruikersnaam, Wachtwoord, UserID)
VALUES ('$_POST[gebruikersnaam]','$_POST[wachtwoord]', 'SELECT MAX(tblLogin.UserID) FROM tblLogin')";
I want to insert another row with the UserID then being the max one (5) + 1 so 6
However if i try this with the code i have now
it just adds 1 instead of 6
It looks like it takes the value as 0 and i don't know why.
The 'Gebruikersnaam' (it's dutch :p) and 'Wachtwoord' are being inserted fine.
Only the UserID gives an issue.
Help.

You can set UserID field to AUTO_INCREMENT.
Thereafter you don't need to pass USerID value in your insert query.

if you want to to increase it everytime then you should set it to auto increment.
otherwise you can try like this:
$sql2="INSERT INTO tblLogin
(Gebruikersnaam, Wachtwoord, UserID)
VALUES ('$_POST[gebruikersnaam]','$_POST[wachtwoord]',
(SELECT 1+MAX(tblLogin.UserID) FROM tblLogin)";

$sql2="INSERT INTO tblLogin (Gebruikersnaam, Wachtwoord, UserID)
SELECT '$_POST[gebruikersnaam]','$_POST[wachtwoord]', MAX(tblLogin.UserID)
FROM tblLogin";

Related

Get sql Id and insert it into another query instantly

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()

only want to insert one row into other table

How do I get this to only insert one row of data, with selected fields inserted into another table by using the reference ?
so far I can only get all of the fields transferred when using the statement in phpmyadmin
$Reference=$_GET['Reference'];
$sql="INSERT INTO Triage (Reference, Forename)
SELECT Reference, Forename from `Instruction` WHERE Reference='$Reference'"
INSERT INTO Table2(LongIntColumn2, CurrencyColumn2)
SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1;
INSERT INTO prod_detail(prod_name,prod_code) select Name,Zip as data from info_tb where Name="mittal";
Try something like this:
$Reference=mysql_real_escape_string($_GET['Reference']);
$sql="INSERT INTO Triage (Reference, Forename)
SELECT Reference, Forename FROM `Instruction`
WHERE Reference='$Reference' LIMIT 1";

Insert multiple rows with same unique ID

I am inserting multiple rows using one query and, obviously, the ID column auto increments each row. I want to create another ID column and have the ID remain the same for all rows inserted during the query. So if I insert 10 rows during one query, I want all 10 rows to have the id "1". How can this be done? Thanks for any help
If I understood your question correctly, you want to supply an ID for the specific group of INSERT statements.
Assumming you have this schema
CREATE TABLE TableName
(
RecordID INT AUTO_INCREMENT PRIMARY KEY,
OtherColumn VARCHAR(25) NOT NULL,
GroupID INT NOT NULL
)
You can have two statements for this:
1.) Getting the last GroupID and increment it by 1.
SELECT COALESCE(MAX(GroupID), 0) + 1 AS newGroupID FROM TableName
2.) once you have executed it, store the value in a variable. Use this variable for all the insert statement,
$groupID = row['newGroupID'];
$insert1 = "INSERT INTO TableName(OtherColumn, GroupID) VALUES ('a', $groupID)";
$insert2 = "INSERT INTO TableName(OtherColumn, GroupID) VALUES ('b', $groupID)";
$insert3 = "INSERT INTO TableName(OtherColumn, GroupID) VALUES ('c', $groupID)";
UPDATE 1
SQLFiddle Demo

PHP Mysql increment a column during insert

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.

PHP : inserting row id to another table

how can I get the row id of tbl_questions and send it to tbl_link_qa
and then tbl_answers get to send it's row number to tbl_link_qa (same with tbl_questions) but this time it must correspond to the first row number from tbl_questions that was inserted first at tbl_link_qa
i need to link the row number of a question from tbl_questions and the row number of an answer from tbl_answers.
need help really bad
rec_id---qRec_id---aRec_id
96------------0-----------0
95------------0-----------0
I need to make it like this >>
rec_id---qRec_id----aRec_id
96----------123----------456
95----------124----------
123 and 124 is the row number from tbl_questions inserted into tbl_link_qa and 456 is from tbl_answers
Use mysql_insert_id to get the auto_increment ID of the last row you inserted.
Ex:
mysql_query("INSERT INTO tbl_questions VALUES (something)");
$question_id = mysql_insert_id();
mysql_query("INSERT INTO tbl_answer VALUES (something)");
$answer_id = mysql_insert_id();
mysql_query("INSERT INTO tbl_link_qa (qRec_id, aRec_id) VALUES ($question_id, $answer_id)");

Categories