Blog

Using PHP How to Connect, Fetch, Display, and Insert Values from/into a MySQL Database
Posted on June 19, 2015 in MySQL, PHP by Matt Jennings

How to Connect to a MySQL Database with PHP and MySQL

In the new-connection.php file provided by Coding Dojo which allows me to connect to a MySQL database, make sure the top of code in the file looks something like below:

define('DB_HOST', 'localhost');
define('DB_USER', 'root');

/*
- Set DB_PASS as 'root' if you're using Mac and MAMP

- On a Mac if using AMPPS set to 'mysql'
*/
define('DB_PASS', 'root'); 

// 'mydb' refers to the name of your database
define('DB_DATABASE', 'mydb'); 

In PHP Code Exampe of How to Fetch, Display, and Insert Values from/into a MySQL Database

<?php session_start(); ?>
<?php require_once('new-connection.php'); ?>
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

<?php

echo '<h2>Output Below from PHP &amp; MySQL Commands to Show Multiple Records</h2>';

// To query the database
$query = "SELECT * FROM film";

// To get multiple records
$films = fetch($query);

// Foreach to get multiple records
foreach($films as $film)
{
    echo $film['title'] . '<br />';
}

echo '<h2>Output Below from PHP &amp; MySQL Commands to Show a Single Record</h2>';

// To get a single record
$films = mysqli_fetch_assoc(mysqli_query($connection, $query));
// To echo a single record
echo $films['title'] . ': ' . $films['description'];


echo '<h2>Insert New Values into a Database</h2>';

// To insert new data into a database
$query = "INSERT INTO film(title, description, release_year, rental_duration, rental_rate, length, replacement_cost, rating, special_features, last_update)
          VALUES('AAA', 'AAA', 2015, 6, 0.99, 99, 1.99, G, AAA, NOW())";

$insertFilm = run_mysql_query($query);

var_dump($insertFilm);
?>

</body>
</html>

Leave a Reply

To Top ↑