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)
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 answers here:
PDO prepared statements for INSERT and ON DUPLICATE KEY UPDATE with named placeholders
(2 answers)
Closed 7 years ago.
How can I use ON DUPLICATE KEY UPDATE in PDO
My problem is that I get (SQLSTATE[42000]: Syntax error or access violation?) when I try the following synthaxe, the insert function and update works fine, but when I use both with on duplicate, I get error :
$query = "INSERT INTO my_table (name,tophtml,bothtml,lang,background_mode,redirhtml,bg_color)
VALUES (:name, :top_html, :bottom_html, :hs_language, :bg_style, :redirect_to, :bg_color )
ON DUPLICATE KEY UPDATE
tophtml= :top_html, bothtml= :bottom_html, lang= :hs_language, bg_color= :bg_color, redirhtml= :redirect_to, background_mode= :bg_style WHERE name=:name
";
$request = $databaseStatus->connection->prepare($query);
$request->bindParam(":name", $name, PDO::PARAM_STR);
$request->bindParam(":top_html", $top_html, PDO::PARAM_STR);
$request->bindParam(":bottom_html", $bottom_html, PDO::PARAM_STR);
$request->bindParam(":bg_color", $bg_color, PDO::PARAM_STR);
$request->bindParam(":redirect_to", $redirect_to, PDO::PARAM_STR);
$request->bindParam(":hs_language", $hs_language, PDO::PARAM_STR);
$request->bindParam(":bg_style", $bg_style, PDO::PARAM_STR);
$request->execute();
I found the solution here.
My problem was in the where clause, you don't need to put the table name or SET in the ON DUPLICATE KEY clause, and you don't need a WHERE clause (it always updates the record with the duplicate key).
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:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(2 answers)
Closed 1 year ago.
I have a function that generates a prepared INSERT statement based on an associative array of column names and values to be inserted into that column and a table name (a simple string):
function insert ($param, $table) {
$sqlString = "INSERT INTO $table (".implode(', ',array_keys($param)).') VALUES ('.str_repeat('?, ', (count($param) - 1)).'?)';
if ($statement = $this->conn->prepare($sqlString)):
$parameters = array_merge(array($this->bindParams($param), $param));
call_user_func_array(array($statement, 'bind_param', $parameters));
if (!$statement->execute()):
die('Error! '.$statement->error());
endif;
$statement->close();
return true;
else:
die("Could Not Run Statement");
endif;
}
My problem is that $this->conn->prepare (it's part of a class, conn is a NEW mysqli object, which works with no issues) returns false, but does not give me a reason why!
Here is a sample $sqlString that gets built for the prepare statement:
INSERT INTO students (PhoneNumber, FirstName, MiddleInit, LastName, Email, Password, SignupType, Active, SignupDate) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
Can anyone see a problem with this parameterized statement? Any reason the prepare function would return false?
I'm copying the solution into this answer so this can be given an upvote, otherwise the question will appear in the "unanswered questions" forever. I'm marking this answer CW so I won't get any points.
#Andrew E. says:
I just turned on
mysqli_report(MYSQLI_REPORT_ALL) to
get a better understanding of what was
going on - turns out that one of my
field names was incorrect - you'd
think that prepare() would throw an
exception, but it fails silently.
These are the main reasons I got this issue.
Error in the query
Trying to run two simultaneous queries (commands out of sync)
First you need to know the exact cause. for that, add following code.
if ($stmt === FALSE) {
die ("Error: " . $mysqli->error);
}
If you are running two simultaneous queries, store values from your first statement will resolve the issue.
$first_stmt->store_result()