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.
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)";
This question already has answers here:
PHP: Calling MySQL Stored Procedure with Both INPUT AND OUTPUT Parameters (NOT "INOUT")
(2 answers)
Closed 3 years ago.
To call a Stored procedure with an IN parameter is easy like
CREATE PROCEDURE `catalog_delete_product`(IN `inProductId` INT) BEGIN DELETE FROM product_attribute WHERE product_id = inProductId; DELETE FROM product_category WHERE product_id = inProductId; DELETE FROM shopping_cart WHERE product_id = inProductId; DELETE FROM product WHERE product_id = inProductId; END
You can see that it is as easy as that. But how do we call an OUT parameter in MySQL Stored parameter and use it in PHP?
As an example to illustrate it, I will a real world practical example(inserting data into an order table and returning the lastInsertId).
CREATE PROCEDURE `shopping_cart_create_order`(IN `inCartId` INT(11), OUT `newOrderId` INT(11)) BEGIN
DECLARE newOrder int;
-- Insert a new record into orders and obtain the new order ID
INSERT INTO orders (created_on) VALUES (NOW());
-- Obtain the new Order ID
SELECT LAST_INSERT_ID() INTO newOrder;
SET newOrder = newOrderId;
END
At PHP level// Probably at the Model/Entity level First, we need to execute the
shopping_cart_create_order()
stored procedure. Which might probably be in a function.
Second, to get the last order id, we need to query it from the variable
#oid
. It is important that we must call the method
closeCursor()
of the PDOStatement object in order to execute the next SQL statement.
function query($pdo, $sql, $parameters = []){
$query = $pdo->prepare($sql);
$query->execute($parameters);
return $query;
}
function create_order($pdo, $cart_id){
// Binding the parameters
$parameters = [':cart_id' => $cart_id];
// calling stored procedure command
$sql = 'CALL shopping_cart_create_order(:cart_id)';
// prepare for execution of the stored procedure, pass value to the command
and execute the Stored Procedure
$query = query($pdo, $sql, $parameters);
// Then close Cursor. It is important for you to close it.
$query->closeCursor();
// execute the second query to get last insert id
$row = $pdo->query("SELECT #oid AS oid")->fetch();
return $row;
}
This question already has answers here:
Find out if REPLACE statement has replaced or just inserted in MySQL
(3 answers)
Closed 4 years ago.
if I have a query with field 1 being a primary key:
$rep = "Replace into table (field1,field2) values ('value1','value2')";
$stmt = $db->query($rep);
Is there a way to tell if mysql inserted the row, or found and replaced the row?
For Posterity:
$rowCount = $stmt->rowCount();
if $rowCount == 1 it was an insert, if $rowCount == 2, it was a replace.
INSERT INTO AggregatedData (datenum,Timestamp)
VALUES ("734152.979166667","2010-01-14 23:30:00.000")
ON DUPLICATE KEY UPDATE
Timestamp=VALUES(Timestamp)
To achieve this type of task mysql provide us DUPLICATE KEY UPDATE.
Below is the example how you will create new record if record is not exists in database otherwise it will update record
$rep = "INSERT into table (primaryField,field2) values ('value1','value2') ON DUPLICATE KEY UPDATE primaryField=VALUES(primaryField)";
$stmt = $db->query($rep);
For more detail you can read this
https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html
I think this will help you.
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:
"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
(12 answers)
Closed 8 years ago.
I have a query that will update a row in the database, which works fine providing there is a row there to begin with.
How could I say; update if exists insert if doesn't?
require_once('../scripts/includePDO.php');
$who = $_SESSION['who'];
$formText = $_POST['protext'];
$sql = "UPDATE tbl_profiles SET proText = :formText WHERE user_id = :who";
$q = $conn->prepare($sql);
$q->bindValue(':who',$who,PDO::PARAM_INT);
$q->bindValue(':formText',$formText,PDO::PARAM_STR);
$q->execute();
header("Location: ../settings/?status=Done");
Assuming user_id is a unique key in the db:
$sql = "INSERT INTO tbl_profiles (user_id, proText) VALUES (:who, :formText) ON DUPLICATE KEY UPDATE proText = :formText";
Your SQL query should be:
INSERT INTO tbl_profiles (user_id,proText) VALUES (:who,:formText)
ON DUPLICATE KEY UPDATE proText=:formText
This is assuming that user_ID is a unique id
1- simple way is use ORM such as Dotrine
2- How ORM handle this :
usually tables has primary key(id) that should not be null .if you have update then you had select that load this data . in you select load id field in you data structure (array or object or something else) . in save method only check current row you want save that it has id (if this record has id then it exist and need to update else you should save).