Home > Database > Mysql Tutorial > How Can I Insert Date and Time Values into MySQL Using mysqli\'s bind_param?

How Can I Insert Date and Time Values into MySQL Using mysqli\'s bind_param?

Mary-Kate Olsen
Release: 2024-12-01 22:59:11
Original
586 people have browsed it

How Can I Insert Date and Time Values into MySQL Using mysqli's bind_param?

Binding Date and Time Columns with MySQLi bind_param

Inserting date or time values into a MySQL table can be tricky when using PHP's mysqli extension and the bind_param method. However, the process is relatively straightforward once you understand how it works.

Using bind_param with Date and Time Columns

To insert data into a date or time column using bind_param, simply treat the value as any other string. Here are the steps:

  1. Prepare the MySQL statement with a placeholder for the date or time value:

    $stmt = $mysqli->prepare('insert into foo (dt) values (?)');
    Copy after login
  2. Assign the date or time value to a PHP variable, using the appropriate format:

    $dt = '2009-04-30 10:09:00'; // Format: 'YYYY-MM-DD hh:mm:ss'
    Copy after login
  3. Bind the variable to the placeholder using the correct type specifier ('s' for string in this case):

    $stmt->bind_param('s', $dt);
    Copy after login
  4. Execute the statement to insert the data into the database:

    $stmt->execute();
    Copy after login

Example:

The following code demonstrates how to insert a date and time value ('2009-04-30 10:09:00') into a field named 'dt' in a table named 'foo':

$mysqli = new mysqli('localhost', 'username', 'password', 'database');

$stmt = $mysqli->prepare('insert into foo (dt) values (?)');
$dt = '2009-04-30 10:09:00';
$stmt->bind_param('s', $dt);
$stmt->execute();

$stmt->close();
$mysqli->close();
Copy after login

The above is the detailed content of How Can I Insert Date and Time Values into MySQL Using mysqli\'s bind_param?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template