require "config.php";// Database connection
Now use the $connection as connection object in your script. Here is the code for config.php file.
<?Php
$host = "localhost";
$database = "sql_tutorial";// Change your database name
$username = "userid"; // Your database user id
$password = ""; // Your password
//error_reporting(0);// With this no error reporting will be there
///// Do not Edit below //////
$connection=mysqli_connect($host,$username,$password,$database);
if (!$connection) {
echo "Error: Unable to connect to MySQL.<br>";
echo "<br>Debugging errno: " . mysqli_connect_errno();
echo "<br>Debugging error: " . mysqli_connect_error();
exit;
}
?>
Here the variables $host is name of the MySQL server host or ip address ( 'localhost' or '127.0.0.1')<?php
$host = 'localhost'; // MySQL host address
$username = 'root'; // User id to login
$password = 'test'; // Password for user id
$database = 'my_tutorial'; // Database name
try {
// Establish MySQLi connection
$connection = new mysqli($host, $username, $password, $database);
// Check for connection error
if ($connection->connect_error) {
// Throw exception if connection fails
throw new Exception('Connection failed: ' . $connection->connect_error);
}
} catch (Exception $e) {
// Handle connection error
echo 'Error: ' . $e->getMessage();
echo "<br>Debugging errno: " . mysqli_connect_errno();
echo "<br>Debugging error: " . mysqli_connect_error();
} finally {
echo "Connection successful!";
}
?>
NULL if no error occurred.throw new Exception('Connection failed: ' . $connection->connect_error); is used to throw a custom exception in the event that a connection to the MySQL database fails. Here’s how it works:
<?Php
$host = "34.68.103.244";
$database = "my_tutorial"; // Change your database name
$username = "root-plus2net"; // Your database user id
$password = "*********"; // Your password
//error_reporting(0);// With this no error reporting will be there
///// Do not Edit below //////
$connection=mysqli_connect($host,$username,$password,$database);
if (!$connection) {
echo "Error: Unable to connect to MySQL.<br>";
echo "<br>Debugging errno: " . mysqli_connect_errno();
echo "<br>Debugging error: " . mysqli_connect_error();
exit;
}
//////Sample script to display record ///
$q="SELECT * FROM student WHERE id=3";
// Generate resultset
$result_set = $connection->query($q);
$row=$result_set->fetch_array(MYSQLI_NUM);
echo $row[0],$row[1],$row[2],$row[3];
$result->free;
?>
Details of MySQL database setupAuthor & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.