Home > Software design >  PHP-MySQL DateTime to string conversion not working
PHP-MySQL DateTime to string conversion not working

Time:01-04

I need to insert data into one of MySql cell that contains the current datetime, but i'm not getting it. The unique thing i get is a "Fatal error: Uncaught Error: Object of class DateTime could not be converted to string" at mysqli_query line.

I saw a solution that contains a fixed date like "DateTime('2000-01-01')", but i need the "now" datetime.

$saleend = new DateTime();

date_add($saleend,date_interval_create_from_date_string("$saledays days, $salehours hours, 00 minutes, 00 seconds"));

$saleend->format('Y-m-d H:i:s');

mysqli_query($conn, "UPDATE tableName SET SALEEND = '$saleend' WHERE ID = '$id'");

CodePudding user response:

I strongly recommend not using string concatenation in your application, instead use the much safer prepared statements. I've crafted a prepared statement and test it's operation:

<?php

mysqli_report(MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("127.0.0.1", "test", "password", "testdb");

$saleend = new DateTime();
$saledays = 1;
$salehours = 10;
date_add($saleend,date_interval_create_from_date_string("$saledays days, $salehours hours, 00 minutes, 00 seconds"));

/* Use a prepared statement */
$stmt = $mysqli->prepare("UPDATE tableName SET SALEEND = ? WHERE ID = ?");

$id = 1;
$timechange = $saleend->format('Y-m-d H:i:s');

// The "si" stands for $saleend is a string ("s") and $id is an integer ("i").
$stmt->bind_param('si', $timechange, $id);

$stmt->execute();
print $stmt->error; //to check errors

You can remove the mysqli_report() and print $stmt->error; line once you have debugged the application.

The prepare() line sets up your substitutions. Then the bind_param() does the swaps server side where it is safer. The execute() sends the query to the server.

Here is the table before I ran this code:

ID SALEEND
1 2022-01-03 01:14:47

Then after:

ID SALEEND
1 2023-01-04 16:40:51
  • Related