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:
Prepare the MySQL statement with a placeholder for the date or time value:
$stmt = $mysqli->prepare('insert into foo (dt) values (?)');
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'
Bind the variable to the placeholder using the correct type specifier ('s' for string in this case):
$stmt->bind_param('s', $dt);
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!