This question already has an answer here:
MYSQL INSERT SELECT problem
(1 answer)
Closed 6 years ago.
$new_id = mysqli_insert_id($dbc)
foreach ($_POST['d_specialty'] as $key => $value) {
$q = "INSERT INTO d_specialty (d_id, s_id) VALUES ($new_id, (SELECT specialty.id FROM specialty WHERE specialty.name = $value))";
$r = mysqli_query($dbc,$q);
i want to insert two values, the first one is a variable and the second is a select statement but the code above does not work...
First, use insert . . . select:
INSERT INTO d_specialty (d_id, s_id)
SELECT $new_id, specialty.id
FROM specialty
WHERE specialty.name = $value;
Second, parameterize the query so $new_id and $value are passed in as parameters rather than put directly into the query string. One reason is to prevent SQL injection attacks. Another very important reason is to guard against potential syntax errors.
When using insert into select you don't need to use values. Remove that and then move the $new_id variable into the select statement:
INSERT INTO d_specialty (d_id, s_id)
SELECT $new_id, specialty.id
FROM specialty
WHERE specialty.name = $value
Related
This question already has answers here:
PDO Parameterized Query - Reuse named placeholders?
(5 answers)
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 3 years ago.
I'm trying to write a query to insert/update a table and it's my first time using prepared statements, I'm receiving the error SQLSTATE[HY093]: Invalid parameter number but from what I can see I'm passing all the columns/values required.
(I'm trying to do this without using bindParam as in example #2 here)
This is just a test for now, I plan on making it dynamic once I've actually got a query working.
$data_test = [
':event_id' => 3354,
':event' => 'TESTESTEST',
':staff_booking_id' => 27255,
':is_read' => 'yes',
':priority' => 'medium'
];
$q = "INSERT INTO events(event_id, event, staff_booking_id, is_read, priority)
VALUES(:event_id, :event, :staff_booking_id, :is_read, :priority)
ON DUPLICATE KEY UPDATE event_id = LAST_INSERT_ID(:event_id), event = :event, staff_booking_id = :staff_booking_id, is_read = :is_read, priority = :priority;";
$result = $this->db->prepare($q);
$result = $result->execute($data_test);
As commentented by FunkFortyNiner and tadman, it is possible that the issue comes from the fact that you are reusing the same placeholder.
Actually the MySQL syntax does not require you to reuse the named parameter: you can use the VALUES() to refer to the values initially passed for INSERT.
Also, your attempt to update event_id using LAST_INSERT_ID() does not seem right; I am unsure that this is valid syntax - and anyway, if this is the primary key of table, then you don't want to update it.
Finally, as pinpointed by FunkFortyNiner, event is a reserved word in MySQL, so it needs to be quoted.
$q =
"INSERT INTO events(
event_id,
`event`,
staff_booking_id,
is_read,
priority
)
VALUES(
:event_id,
:event,
:staff_booking_id,
:is_read,
:priority
)
ON DUPLICATE KEY UPDATE
`event` = VALUES(`event`),
staff_booking_id = VALUES(staff_booking_id),
is_read = VALUES(is_read),
priority = VALUES(priority)";
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
After searching on Google, i came to know that,
I can not use a WHERE clause in my INSERT query..
But i want to insert a value on column "Book_4" where "Student_ID = 1"
How can i do that ??
Is there any alternate to do that ?
Will be Thankful to You !
$Query = "INSERT INTO issued_books (Book_4) VALUES ('$IssuedBookNumber')" ;
EDITED:
More Details
Using insert query, when i insert a value in column "Student_ID" in my table. All columns in the row of Student_ID (except Student_ID) shows 0 in my DB.
I dun know what this 0 means according to DB.
It might be Null or numeric 0.
If it is a numeric 0, then it should be updated using the UPDATE statement.
But whenever i'm trying to update it, it never updates using UPDATE statement. That's why i'm asking !
P.S: All columns have Datatype INT.
Hope you understand what i want to say :)
Here is the complete code.
Suppose: Student_ID is already created having the value 2.
IssuedBookNumber = 51
Using the above values:
Result = A new row is created having all columns 0 except the column "IssuedBookNumber" that is having value = 51.
While i want, the result should be:
On row Student_ID = 2, Book_4 should be 51.
The point is, When i inserted a value on Student_ID, all other columns becomes 0 on the same row. But when any of the column on the same row having any number except the 0 (that was automatically came on all columns when i inserted a value in Student_ID). Update Query will work.. !
$IssuedBookNumber = $_POST['IssuedBookNumber'];
$Student_ID = $_POST['StudentId'];
$FetchingQuery = "SELECT * FROM issued_books WHERE Student_ID='" . $Student_ID . "'";
$RunFetchingQuery = mysql_query($FetchingQuery);
while ( $row = mysql_fetch_array( $RunFetchingQuery ) ) {
$Book_1 = $row[ 'Book_1' ];
$Book_2 = $row[ 'Book_2' ];
$Book_3 = $row[ 'Book_3' ];
$Book_4 = $row[ 'Book_4' ];
$Book_5 = $row[ 'Book_5' ];
}
if(!empty($Book_4))
{
$Update = "UPDATE issued_books SET Book_4='$IssuedBookNumber' WHERE Student_ID= '$Student_ID'";
mysql_query ($Update);
}
else
{
$AddQuery = "INSERT INTO issued_books (Book_4) VALUES ('$IssuedBookNumber')";
mysql_query ($AddQuery);
}
That not an INSERT. That's an UPDATE. INSERT statements insert a new row. UPDATE statements update an existing row.
UPDATE issued_books
SET Book_4 = '$IssuedBookNumber'
WHERE Student_ID = '$Student_ID'
(I'm assuming you've properly escaped $IssuedBookNumber and $Student_ID)
If you can add a unique index on the 2 columns combined (book_4, student_id)
This would be a good query andshould replace most of your code above
INSERT INTO issued_books (book_4, student_id) VALUES('$IssuedBookNumber','$Student_ID')
ON DUPLICATE KEY UPDATE
SET Book_4 = '$IssuedBookNumber';
Note: you while loop above is not needed since $Book_4 will always return the value of the last row.
your code will then look like this :)
$IssuedBookNumber = $_POST['IssuedBookNumber'];
$Student_ID = $_POST['StudentId'];
$Update = "UPDATE issued_books SET Book_4='$IssuedBookNumber' WHERE Student_ID= '$Student_ID'";
mysql_query ($Update);
Things you should consider,
Switch to using PDO or mysqli
Escape your variables are your code is vulnerable to a SQL injection. Perhaps after you switch to PDO or mysqli you can use prepare statement.
Why not something like this:
$Query = "INSERT INTO issued_books (Book_4, Student_ID)
VALUES ('$IssuedBookNumber', '$Student_ID')"
Use update statement.
update issued_books set Book_4 = $IssuedBookNumber
where Student_ID = '$Student_ID'
I want to have each array value inside a paranthesis
$id = $_POST['id'];
$test2 = array($id);
$id_list = implode(',', $test2);
$sql .= "INSERT INTO tmp (id) VALUES ({$id_list});";
for example: I'm performing an insert so the output of the list should be (5),(10),(15) not '5','10','15'
Any suggestions on how I can insert using an array?
MySQL's extended insert syntax is
INSERT INTO sometable (...fields...) VALUES (value set #1), (value set #2), (value set #3), etc...
Note how each value set is in its own (). You're not doing that. you're just passing a bunch of values in a SINGLE () set, which means you're providing values for fields that are NOT present in the field list.
You need to do
$id_list = '(' . implode('),(', $_POST['id']) . ')';
producing
(5),(10),(15)
instead of
(5, 10, 15)
You also need to realize that you're vulnerable to sql injection attacks.
This question already has answers here:
Can PHP PDO Statements accept the table or column name as parameter?
(8 answers)
Closed 8 years ago.
Why this line doesn't work:
$db_Table = "myTable";
$pdo->prepare("INSERT INTO :db_Table VALUES (...
$query->execute(array(
':db_Table' => $db_Table,
Whereas this one works:
$pdo->prepare("INSERT INTO myTable VALUES (...
How can I solve it ?
Tablenames can not be replaced in a PDO Query.
Further information you can find in the following thread
Can PHP PDO Statements accept the table or column name as parameter?
unfortunately there are no builtin function for binding table names, you have to do it yourself:
$db_Table = "myTable";
$query = $pdo->prepare("INSERT INTO `$db_Table` VALUES (...)");
$query->execute();
But that is still not being escaped, one workaround is to have an array of table, then check if it exist:
$list_of_tables = array('myTable1', 'myTable2', 'myTable3');
if(!in_array($db_Table, $list_of_tables){
//table does not exist !
}
This question already has answers here:
MySQL query to get column names?
(22 answers)
Closed 9 years ago.
Here is the situation. I just know total number of columns the table test_table has but don't know their names(sounds strange but its true). Is there any way I can write UPDATE Query for all column values on basis of some ID(auto-increment primary key)?
To add row in this table, I did following which is working but don't have idea how to do it for UPDATE:
$newCols = $_POST['newRowCols'];
$query = "INSERT INTO test_table VALUES "."("."NULL";
foreach($newCols as $col)
{
$query .= ",'$col'";
}
$query.=")";
mysqli_query($con,$query);
Thanks.
No this is not possible. But you can get the column names using the information_schema database:
SELECT
`ORDINAL_POSITION`,
`COLUMN_NAME`
FROM `information_schema`.COLUMNS
WHERE
`TABLE_SCHEMA` = $dbname
AND
`TABLE_NAME` = $tablename
ORDER BY `ORDINAL_POSITION`