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 !
}
Related
This question already has answers here:
How to UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) in PostgreSQL?
(7 answers)
Postgres on conflict do update on composite primary keys
(2 answers)
Closed 6 months ago.
I have a problem with my SQL statement written in PHP.
I am using store() function to both INSERT or UPDATE object in the database following it's rule that it can be done:
The INSERT OR UPDATE command is an extension of the INSERT command, with these differences:
If the row being inserted does not exist, INSERT OR UPDATE performs an
INSERT operation. If the row being inserted already exists, INSERT OR
UPDATE performs an UPDATE operation, updating the row with the
specified column values.
I wrote type declaration for the Content ID like : public ?$contentId = null; so I can use the same methods for both actions.
public function store(Content $content, int $teamId)
{
$rsm = new ResultSetMapping($this->entityServiceRepository);
$stmt = $this->entityServiceRepository->getConnection()->prepare(
'UPDATE content
SET
name = :name,
url = :url,
WHERE id = :contentId
AND team_id = :teamId
',
$rsm
);
$stmt->bindValue("contentId", $content->getId(), PDO::PARAM_INT);
$stmt->bindValue("teamId", $content, PDO::PARAM_INT);
$stmt->bindValue("name", $content->getName(), PDO::PARAM_STR);
$stmt->bindValue("url", $content->getUrl(), PDO::PARAM_STR);
$stmt->executeQuery();
However from some reason data does not exist in the database. All bindValue() return true ant other sql queries seems to work well. How can I debug this query? Or can someone tell is there a problem with sql query I wrote.
Thanks.
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)";
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
This question already has answers here:
Inserting NOW() into Database with CodeIgniter's Active Record
(11 answers)
Closed 7 years ago.
I'm trying to do an update in MySQL from PHP with CodeIgniter, but, how can I insert a now() method?
I mean, I'm using an array to insert my information, but, how can I insert the date?
This is an example of my array:
$data = array(
'name' => $inputName,
'lastname' => $inputLast,
'DOBirth' => now()
);
NOW() is part of MySQL, not PHP, so you need to put into the query.
Try this way, which is how you handle it using PDO. This should work:
$stmt = $pdoDb->prepare('INSERT INTO tablename (name, lastname, dobirth) VALUES (:name, :lastname, NOW())');
// either bind each parameter explicitly
$stmt->bindParam(':name', $name);
$stmt->bindParam(':lastname', $lastname);
$stmt->execute();
source: Datetime NOW PHP mysql (+ PDO variant)
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`