📜  heroku mysql - PHP (1)

📅  最后修改于: 2023-12-03 15:15:30.906000             🧑  作者: Mango

Heroku MySQL - PHP

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.

Setting Up a MySQL Database on Heroku

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:

  1. Install the Heroku CLI if you haven't already done so.
  2. Log in to your Heroku account using the CLI.
    $ heroku login
    
  3. Create a new Heroku app. This will also create a new Git repository for your app.
    $ heroku create <app-name>
    
  4. Add the ClearDB add-on to the app.
    $ heroku addons:create cleardb
    
  5. Retrieve the database URL from the Heroku environment variables.
    $ heroku config:get CLEARDB_DATABASE_URL
    
    This will output a URL such as mysql://<username>:<password>@<host>/<database>.
  6. Use the URL to connect to the database from your PHP application.
Connecting to a MySQL Database from PHP

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

?>
Conclusion

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.