Pilih Laman

sumber: https://www.hostinger.co.id/tutorial/koneksi-database-php

Using MySQLi to Create a PHP Connection to MySQL

Four steps using MySQLi to establish a PHP database connection to MySQL:

  1. Go to File Manager -> public_html.
  2. Create a New File by clicking the add file icon in the menu at the top of the screen.
  3. Save it as databaseconnect.php, or any other name you want, but keep the extension .php.
  4. Copy and paste the line of code below into the file. Double click to open it. Make sure you’ve replaced the first four values ​​under <?php with the information (credentials) noted earlier.
<?php
$servername = “localhost”;
$database = “databasename”;
$username = “username”;
$password = “password”;
// Create connection
$conn = mysqli_connect($servername, $username, $password, $database);
// Check connection
if (!$conn) {
die(“Connection failed: “ . mysqli_connect_error());
}
echo “Connected successfully”;
mysqli_close($conn);
?>
Using PDO to Create a PHP Connection to MySQL
The second way to establish a PHP database connection to MySQL is with PDO. The steps are almost the same as for MySQLi although there are slight differences:
1. In the public_html folder, create a file that will be named pdoconfig.php. Enter the code below into the file. Replace the placeholder values ​​with the database information you created and noted down earlier. Click Save and Close when finished.
<?php
$host = ‘localhost’;
$dbname = ‘databasename’;
$username = ‘username’;
$password = ‘password’;
2. In the same directory, create another file and name it databaseconnect.php. Add the code below. If the previous file was given a different name (not pdoconfig.php), replace the value in require_once.
<?php
require_once ‘pdoconfig.php’;
try {
$conn = new PDO(“mysql:host=$host;dbname=$dbname”, $username, $password);
echo “Connected to $dbname at $host successfully.”;
} catch (PDOException $pe) {
die(“Could not connect to the database $dbname :” . $pe->getMessage());
}