📅  最后修改于: 2023-12-03 15:15:30.906000             🧑  作者: Mango
Heroku is a platform that allows developers to build, run, and scale applications in a cloud environment. One of the most common use cases for Heroku is running MySQL databases with PHP applications.
To set up a MySQL database on Heroku, you can use the ClearDB add-on, which provides a variety of MySQL plans. Here is how to create a MySQL database with ClearDB using the Heroku CLI:
$ heroku login
$ heroku create <app-name>
$ heroku addons:create cleardb
$ heroku config:get CLEARDB_DATABASE_URL
This will output a URL such as mysql://<username>:<password>@<host>/<database>
.Once you have created a MySQL database on Heroku, you can connect to it from your PHP application using the mysqli
extension. Here is an example of how to do this:
<?php
$db_url = getenv('CLEARDB_DATABASE_URL');
$db_parts = parse_url($db_url);
$db_host = $db_parts['host'];
$db_user = $db_parts['user'];
$db_pass = $db_parts['pass'];
$db_name = substr($db_parts['path'], 1);
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($mysqli->connect_errno) {
die('Failed to connect to MySQL: ' . $mysqli->connect_error);
}
// Use the $mysqli object to perform database operations.
// ...
$mysqli->close();
?>
Heroku makes it easy to set up and run MySQL databases with PHP applications. By using the ClearDB add-on and the mysqli
extension, you can quickly get up and running with a robust, scalable database solution.