INSERT ... SELECT(insert many rows) - mysql

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';

Related

PDO insert max id+1 not auto_increment

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.

INSERT value using SELECT in mysql

I have 2 tables: users with columns (id,username, password), and user_failed with columns (user_id, failed, time). is there any possible way i can insert into table user_failed by only using username? i try this code but it failed:
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`)
VALUES (SELECT user_id FROM users WHERE username = 'pokemon','',3)
Your SQL query is incorrect for several reasons.
The following should work if I have interpreted your query correctly.
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`)
SELECT id, '', 3 FROM users WHERE username = 'pokemon'
INSERTing into a table from a SELECT does not require VALUES ( ... ). Here is an example of how you would use VALUES ( ... ):
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`)
VALUES (1, '', 3)
Also, your sub query SELECT user_id FROM users WHERE username = 'pokemon','',3 the WHERE clause is invalid. Specifically the '',3 part which I assume is the values you wanted to insert for time and failed.
This will work....you have to add plain parentheses before and after statements.
INSERT INTO `login_attempts`(`user_id`, `time`, `failed`) VALUES ((SELECT user_id FROM users WHERE username = 'pokemon'),'',3)

mysql insert record without using 'values'

INSERT INTO class
(name, description, personid)
Select name, description, 12 from Class where PersonID = 3;
Select * from Class
Select * from Person
Why is the values words is missing from above statement? I thought it should be like this insert into tableA('name') values('select name from tableB') ?
INSERT INTO my_table VALUES ()
Insert data one Table to another table
OR
Not Using Value keyword
Insert into Table2 (Name , Address , Mobile) Select Column 1, Column 2 , Column 3 From Table1
There are different techniques of INSERT, the code above is inserting values from the table itself and change only the personid to 12, he use select so that he can copy the data aside from hardcoded personid . that's why you didn't see the VALUES keyword , but that's true.. the basic insert statement we learn from school is INSERT INTO TableName (Col1, Col2... etc) VALUES (Value1, Value2... etc) , INSERTION of data depends on the requirements that you are working on.

Adding only one value to the table in sql

I have a table named student which consists of (rollno, name, sem, branch)
If I want to INSERT only one value (i.e only name has to be entered) what is the query?
To insert values into specific columns, you first have to specify which columns you want to populate. The query would look like this:
INSERT INTO your_table_name (your_column_name)
VALUES (the_value);
To insert values into more than one column, separate the column names with a comma and insert the values in the same order you added the column names:
INSERT INTO your_table_name (your_column_name_01, your_column_name_02)
VALUES (the_value_01, the_value_02);
If you are unsure, have a look at W3Schools.com. They usually have explanations with examples.
insert into student(name) values("The name you wan to insert");
Be careful not to forget to insert the primary key.
First, if the table is all empty, just wanna make the column 'name' with values, it is easy to use INSERT INTO. https://www.w3schools.com/sql/sql_insert.asp.
`INSERT INTO TABLE_NAME (COLUMN_NAME) VALUES ("the values")`
Second, if the table is already with some values inside, and only wanna insert some values for one column, use UPDATE. https://www.w3schools.com/sql/sql_update.asp
UPDATE table_name SET column1 = value1 WHERE condition;
insert into student (name)
select 'some name'
or
insert into student (name)
values ('some name')
Following works if other columns accept null or do have default value:
INSERT INTO Student (name) VALUES('Jack');
Further details can be found from the Reference Manual:: 13.2.5 INSERT Syntax.
Execute this query, if you want the rest of columns as "#", do insert # inside the single quote which is left blank in query.
Also, there is no need of defining column name in the query.
insert into student values('','your name','','');
Thanks...

INSERT INTO with SubQuery MySQL

I have this Statement:
INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
VALUES (1, 2, (SELECT item_costprice FROM qa_items WHERE item_code = 1));
I'm trying to insert a value copy the same data of item_costprice, but show me the error:
Error Code: 1136. Column count doesn't match value count at row 1
How i can solve this?
Use numeric literals with aliases inside a SELECT statement. No () are necessary around the SELECT component.
INSERT INTO qa_costpriceslog (item_code, invoice_code, item_costprice)
SELECT
/* Literal number values with column aliases */
1 AS item_code,
2 AS invoice_code,
item_costprice
FROM qa_items
WHERE item_code = 1;
Note that in context of an INSERT INTO...SELECT, the aliases are not actually necessary and you can just SELECT 1, 2, item_costprice, but in a normal SELECT you'll need the aliases to access the columns returned.
You can just simply e.g.
INSERT INTO modulesToSections (fk_moduleId, fk_sectionId, `order`) VALUES
((SELECT id FROM modules WHERE title="Top bar"),0,-100);
I was disappointed at the "all or nothing" answers. I needed (again) to INSERT some data and SELECT an id from an existing table.
INSERT INTO table1 (id_table2, name) VALUES ((SELECT id FROM table2 LIMIT 1), 'Example');
The sub-select on an INSERT query should use parenthesis in addition to the comma as deliminators.
For those having trouble with using a SELECT within an INSERT I recommend testing your SELECT independently first and ensuring that the correct number of columns match for both queries.
Your insert statement contains too many columns on the left-hand side or not enough columns on the right hand side. The part before the VALUES has 7 columns listed, but the second part after VALUES only has 3 columns returned: 1, 2, then the sub-query only returns 1 column.
EDIT: Well, it did before someone modified the query....
As a sidenote to the good answer of Michael Berkowski:
You can also dynamically add fields (or have them prepared if you're working with php skripts) like so:
INSERT INTO table_a(col1, col2, col3)
SELECT
col1,
col2,
CURRENT_TIMESTAMP()
FROM table_B
WHERE b.col1 = a.col1;
If you need to transfer without adding new data, you can use NULL as a placeholder.
If you have multiple string values you want to add, you can put them into a temporary table and then cross join it with the value you want.
-- Create temp table
CREATE TEMPORARY TABLE NewStrings (
NewString VARCHAR(50)
);
-- Populate temp table
INSERT INTO NewStrings (NewString) VALUES ('Hello'), ('World'), ('Hi');
-- Insert desired rows into permanent table
INSERT INTO PermanentTable (OtherID, NewString)
WITH OtherSelect AS (
SELECT OtherID AS OtherID FROM OtherTable WHERE OtherName = 'Other Name'
)
SELECT os.OtherID, ns.NewString
FROM OtherSelect os, NewStrings ns;
This way, you only have to define the strings in one place, and you only have to do the query in one place. If you used subqueries like I initially did and like Elendurwen and John suggest, you have to type the subquery into every row. But using temporary tables and a CTE in this way, you can write the query only once.