I don't want to use auto increment of mysql ,But I want to get max id+1 to insert as ID for next data.
I tried to do as How to get auto increment id by PDO before execute
But no luck.
$sql = "INSERT INTO checklist ((SELECT MAX(checklist_id)+1), checklist_name ) VALUES (NULL, :checklist_name)";
$pdo_statement = $pdo_conn->prepare( $sql );
$result = $pdo_statement->execute ((array(':maxid'=>NULL,':checklist_name'=>$_POST['checklist_name']));
Could you please help me what code it should be?
Edit: as one of the commentors have pointed out above; it is not recommended to not have PRIMARY Key in your MySQL Database
Your SQL query is wrong. You need to have columns and values separately.
$sql = "INSERT INTO checklist ((SELECT MAX(checklist_id)+1), checklist_name ) VALUES (NULL, :checklist_name)";
To make your INSERT statement correct look at the documentation
INSERT INTO table (column, column, etc.) VALUES (value, value, etc.)
So to make your statement correct you will have to switch some of the variables
INSERT INTO checklist (checklist_id, checklist_name) VALUES ((SELECT MAX(checklist_id)+1 FROM checklist), :checklist_name)
And your array with your bind values will look like this
array(':checklist_name' => $_POST['checklist_name'])
If you have problems with any SQL syntax you can look at the documentation or w3schools tutorials.
Related
i want to insert the scholar's id to the tblinbox. Here is my query:
$sql = "INSERT INTO tblinbox VALUES ('','$sender','$type','$subject','$LRN','$content','$date', '$newyearLevel','','$userType','THIS_IS_FOR_THE_ID_OF_THE_SCHOLAR')
SELECT id FROM tblscholar WHERE schoYear = '$newyearLevel'";
my problem is,it is not inserting. what will i change in my query?
INSERT ... SELECT syntax does not allow for VALUES declaration. The values ARE the results returned from the SELECT.
See the documentation here: http://dev.mysql.com/doc/refman/5.6/en/insert-select.html
I honestly am not fully sure what you are trying to do with your insert. If you are trying to insert the same values held in your variables for each id value from the tblscholar table then perhaps you need to do something like this:
INSERT INTO tblinbox
/*
maybe add column definitions here to make it clearer
column definitions could look like this:
(
someField,
type,
subject,
LRN,
content,
`date`,
newyearLevel,
someOtherField,
userType,
id
)
*/
SELECT
'',
'$sender',
'$type',
'$subject',
'$LRN',
'$content',
'$date',
'$newyearLevel',
'',
'$userType',
id
FROM tblscholar
WHERE schoYear = '$newyearLevel'
An INSERT statement supports either a VALUES clause followed by a row of values, or else a SELECT query with columns to match the columns of the table you want to insert into.
But not both!
But you can add constant values into your SELECT query:
$sql = "INSERT INTO tblinbox
SELECT '','$sender','$type','$subject','$LRN','$content','$date',
'$newyearLevel','','$userType', id
FROM tblscholar WHERE schoYear = '$newyearLevel'";
considering id is the first column in your insert statement, try this
$sql = "INSERT INTO tblinbox VALUES ((SELECT id FROM tblscholar WHERE schoYear = '$newyearLevel'),'$sender','$type','$subject','$LRN','$content','$date', '$newyearLevel','','$userType')";
You can insert values either fetching values form another table or providing values as follows:
Way 1:
INSERT INTO tblinbox(coloumn_name1,coloumn_name2) VALUES (value1,value2);
Way 2:
INSERT INTO tblinbox(coloumn_name1,coloumn_name2) SELECT value1,value2 from tblscholer where schoYear= '$newyearLevel';
$stmt2 = $db->prepare("INSERT INTO
usertabbrige(`tabId`,`uId`)
VALUES
((LAST_INSERT_ID()),$userId)");
anything wrong with this query? It's wrap within my first stmt, which will insert a value into uId (PK) in other table. usertabbrige table contain a field uId which is a FK.
Do not use LAST_INSERT_ID() in your query. You dont know which insert statement was last in current session. You can insert to one table, and if you use LAST_INSERT_ID() in another query, you dont actually know where LAST_INSERT_ID() came from.
As I can see you are using PDO. After you executed an insert query, save id:
$db->query("INSERT INTO ...");
$lastInsertedTabId = $db->lastInsertId;
Use it in your next prepared statement
$stmt2 = $db->prepare("INSERT INTO
usertabbrige(`tabId`,`uId`)
VALUES
($lastInsertedTabId ,$userId)");
I'm using a third party mysql table (ie I can't change any of its properties) and I have a row that has id (key), name and value.
I want to store unique cache keys into a row with the name cacheKeys.. and this is my sql statement
$query = "INSERT INTO ".$tableName." (name, value) VALUES ('CacheKeys', '".$key."') ON
DUPLICATE KEY UPDATE value = CONCAT_WS (',', $tableName.value, '$key')";
I've already implemented my caching algorithm, so that every time someone adds a cache key, I check to see if it already exists (from the CacheKeys row above), if it does I fetch it from cache.. otherwise I store it.
Problem is it seems that the sql write operation takes time, and it often stores duplicate cacheKeys
ie: currencies,defaultCurrencyId,user19,currency1,currency1,currency1,currency1,currency1
So I need to check to see that I'm not adding a duplicate key into the cacheKeys field.. and I need to do that using SQL (using php, ie regex etc would just be waaaay to expensive).
Try this::
INSERT INTO tb (firstname, lastname) VALUES ('Jack', 'Doe') IF NOT
EXISTS ( SELECT * FROM tb WHERE firstname='Jack' AND lastname='Doe' );
I'm dealing with a relational table and I've been wondering if there's a way to lower the number of queries I need to make when inserting data to the tables..
Here are the queries I currently use:
I insert the "main" values.
INSERT INTO products
(title, description, status, url)
VALUES
('some title', 'description of doom', 1, 'some-title');
We make it insert the value only if it doesn't exist already.
INSERT IGNORE INTO values
(value)
VALUES
('example value');
Since I'm not sure if the query was actually inserted, I get the id..
SELECT id
FROM
values
WHERE
value = 'example value';
Where "?" is the ID I got from the last query.
INSERT INTO link
( id_product, id_catalog, id_value )
VALUES
( 33, 1, ? );
This means that each extra value I need to add will cost 3 queries. So my question is: Is there a more efficient way to do this?
You can do this to at least drop one of the queries:
INSERT INTO link
( id_product, id_catalog, id_value )
VALUES
( 33, 1, (SELECT id
FROM values
WHERE value = 'example value') );
I basically am replacing the '?' with a sub select of the second query to get the id.
"Is there a more efficient way to do this?"
No. Not really. Creating three things takes three inserts.
You should be able to tell whether the insert succeeded with the ROW___COUNT() function from inside MySQL. If calling from another language (e.g. PHP), the mysql_query or equivalent function will return the row count.
You could use an INSERT INTO ... ON DUPLICATE KEY UPDATE statement.
This does, however, require that the primary key be one of the values for the insert, so it doesn't work on tables with an auto-increment.
I want to copy all of the columns of a row, but not have to specify every column. I am aware of the syntax at http://dev.mysql.com/doc/refman/5.1/en/insert-select.html but I see no way to ignore a column.
For my example, I am trying to copy all the columns of a row to a new row, except for the primary key.
Is there a way to do that without having to write the query with every field in it?
If your id or primary key column is an auto_increment you can use a temp table:
CREATE TEMPORARY TABLE temp_table
AS
SELECT * FROM source_table WHERE id='7';
UPDATE temp_table SET id='100' WHERE id='7';
INSERT INTO source_table SELECT * FROM temp_table;
DROP TEMPORARY TABLE temp_table;
so in this way you can copy all data in row id='7' and then assign
new value '100' (or whatever value falls above the range of your current auto_increment value in source_table).
Edit: Mind the ; after the statments :)
You'll need to list out the columns that you want to select if you aren't selecting them all. Copy/Paste is your friend.
This is a PHP script that I wrote to do this, it will assume that your first col is your auto increment.
$sql = "SELECT * FROM table_name LIMIT 1";
$res = mysql_query($sql) or die(mysql_error());
for ($i = 1; $i < mysql_num_fields($res); $i++) {
$col_names .= mysql_field_name($res, $i).", ";
}
$col_names = substr($col_names, 0, -2);
$sql = "INSERT INTO table_name (".$col_names.") SELECT ".$col_names." FROM table_name WHERE condition ";
$res = mysql_query($sql) or die(mysql_error());
If you don't specify the columns you have to keep the entries in order. For example:
INSERT INTO `users` (`ID`, `Email`, `UserName`) VALUES
(1, 'so#so.com', 'StackOverflow')
Would work but
INSERT INTO `users` VALUES
('so#so.com', 'StackOverflow')
would place the Email at the ID column so it's no good.
Try writing the columns once like:
INSERT INTO `users` (`Email`, `UserName`) VALUES
('so#so.com', 'StackOverflow'),
('so2#so.com', 'StackOverflow2'),
('so3#so.com', 'StackOverflow3'),
etc...
I think there's a limit to how many rows you can insert with that method though.
No, this isn't possible.
But it's easy to get the column list and just delete which one you don't want copied this process can also be done through code etc.
Copy the table to a new one, then delete the column you don't want. Simple.
I'm assuming that since you want to omit the primary key that it is an auto_increment column and you want MySQL to autogenerate the next value in the sequence.
Given that, assuming that you do not need to do bulk inserts via the insert into ... select from method, the following will work for single/multi record inserts:
insert into mytable (null, 'a', 'b', 'c');
Where the first column is your auto_incremented primary key and the others are your other columns on the table. When MySQL sees a null (or 0) for an auto_incremented column it will automatically replace the null with the next valid value (see this link for more information). This functionality can be disabled by disabling the NO_AUTO_VALUE_ON_ZERO sql mode described in that link.
Let me know if you have any questions.
-Dipin