Mandya University, Mandya
DEPARTMENT OF COMPUTER SCIENCE
PHP: HYPERTEXT-PREPROCESSOR
Topic: Connecting to MySQL and Selecting the Database.
NAME: JAYANTH KUMAR D
CLASS: 6th sem BCA ‘C’ sec
REG_No.: U21AT22S0243
SUBMITTED TO:
Mrs. NAYANA.
ASSISTANT PROFESSOR
MANDYA UNIVERSITY, MANDYA.
Connecting to MySQL in PHP
Is a way to connect and interact with a MySQL database using procedural
(function-based) style in PHP. It uses the mysqli_connect() function to establish
a connection and other mysqli_ functions to perform database operations.
● It is simpler and more straightforward than object-oriented or PDO for
small scripts, but less flexible for complex applications.
Example:
<?php
$host = "localhost";;
$user = "root";
$pass = "arya";
$conn = mysqli_connect($host, $user, $pass);
if(! $conn )
{
die('Could not connect: ' . mysqli_connect_error());
}
echo 'Connected successfully<br/>';
$sql = 'CREATE Database MUMCollege';
if(mysqli_query( $conn,$sql)){
echo "Database MUMCollege created successfully.";
}else{
echo "Sorry, database creation failed ".mysqli_error($conn);
}
mysqli_close($conn);
?>
Output:
Connected successfully.
Database MUMCollege created successfully.
Key points:
● $conn: conn usually represents the connection object or resource used to
interact with the database.
● mysqli_connect_error: mysqli_connect_error() is a PHP function that
tells you what went wrong if the connection to the MySQL database fails.
It helps you debug connection errors by showing the reason.
● die:means "stop here and show this message." It’s often used for error
handling.
● mysqli_connect():is how PHP talks to your MySQL database. If the
connection is successful, you can run queries. If not, you use
mysqli_connect_error() to check what went wrong.
● mysqli_query(): lets PHP run SQL commands in your MySQL database.
● mysqli_close():means "disconnect from the database.”
Selecting the Database:
Uses the mysqli_connect() function to connect to the MySQL server and select
the database at the same time. It is the most common and convenient way when
you already know the database you want to use.
Syntax:mysqli_connect(host,username, password, database_name);
Example:
<?php
$conn = mysqli_connect("localhost", "username", "password",
"database_name");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected and database selected successfully";
?>