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
Mary-Kate OlsenOriginal
2024-12-01 22:59:11587browse

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 (?)');
  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'
  3. Bind the variable to the placeholder using the correct type specifier ('s' for string in this case):

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

    $stmt->execute();

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();

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!

Statement:
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