Connecting MYSQL Database and PHP Scripting

Subramanya Krishna
2 min readJul 14, 2020
Photo by KOBU Agency on Unsplash

Finally, you started learning web development and after leaning PHP and MySQL you may encounter some questions Like How one can connect the database and website? How to add data to the database? In the article, we will see how we can take with the database server.

Pre-requirements :

Install XAMPP or any other server software and create a user, and basic knowledge of PHP and Mysql

Let’s Begin

First, to connect your website with the database we have a small set of codes at the starting of the .php file.

<?php 
//connecting to database
$conn = mysqli_connect('localhost','subbu','test1234');
//conn = mysqli_connect('hostname','username',password';
?>

So above we will use a predefined PHP function which helps us to connect with the server. localhost is a hostname. mysqli_connect will open a connection to the stated MySQL server.

The return value of the mysqli_connect function is boolean. If there is a connection then it will output True Otherwise False. So, how do we know errors if the connection is not achieved?

Checking errors in MySQL server connection:

if(!$conn){
echo"connection error: ".mysqli_connect_error();
}

We check whether the value of conn is True or False. If false it will output the inclusive statements. mysqli_connect_error( ) is a function which stores and returns error in connection between server. we will append using “ .” operator to our string connection error.

Creating and writing to the Database:

<?php $sql = "CREATE DATABASE DoggApp"; ?>

The above equation will create a Database and It store the string of query in sql variable. For obtaining results of the query we use mysqli_query( ).

<?php $result = mysqli_query($conn,$sql); ?>

mysqli_query(connection, query) this function will use the connection conn and execute the query and it will store the result in the result variable. The result means all data returned by the query. Let’s find a way to fetch the result from result variable.

<?php
if (mysqli_query($conn, $sql)) {
echo "Database creation successful";
} else {
echo "Error : " . mysqli_error($conn);
} ?>

we will add a table!!!

<?php $sql = "CREATE TABLE DogDetails(
id INT(6) AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
age INT(2),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)"; ?>
if (mysqli_query($conn, $sql)) {
echo "Table DogDetails created successfully";
} else {
echo "Error : " . mysqli_error($conn);
}

I’m new to medium please help me to improve.

--

--