Best Blogger tutorials and Tech Tricks website.

Monday 5 November 2018

How to connect to your database using php

1 comment

<?php
$host = "localhost";
$username = "root";
$password = " ";
$database = "database name";


$conn = mysqli_connect("$hostmysql","$username","$password");

if (!$conn) die ("Connecttion Failed");

mysqli_select_db($database,$conn) or die ("Database Not selected); 


?>

Code Explained

STEP 1: 

$host = "localhost";
$username = "root";
$password = " ";
$database = "database name";

This is the basic details you provide when you are using a localserver like XAMP, WAMP OR MAMP on your computer. The details may changed you have customize your server or when you are using an online server you will be given your server details

NOTE!: If you are using Xamp or Wamp or maybe Mamp the $host name is always localhost and $username is always root leave the $password empty!

STEP 2: 


$conn = mysqli_connect("$hostmysql","$username","$password");


Once you have completed the first step, You now have to create a variable and a fuction that connects to the mysql database using the details above. 

$conn is just a variable i used to connect, (You can name yours anything eg: connect etc). mysqli_connect is the function use to connect to a database.
you the put the name of your variable in the first step in a parentheses or round brackets ( ) if i may say. with this step if there is no errors, The you are connected.

STEP 3: 


if (!$conn) die ("Connecttion Failed");


When coding in php, you must always check for error first. what the above means is that we are telling php that when the $conn variable which is assigned to the mysqli_connect fails, then we use a function called die() which alerts us that "The connection failed"; and also stops the process.


STEP 4:

mysqli_select_db($database,$conn) or die ("Database Not selected); 

What the aboves means that mysqli_select_db( ) function selects the database that you named in STEP 1, but when it fails the die() function alerts that Database is not selected but connection is made. this could be that you type a wrong database name or the database does not exit .


If you got no error message then that means you have sucessfully connect to your mysql database and you can include that connect in your projects.

Conclusion


the ! sign means not, it is used to check for errors and always mostly used in php statements.




If you have any problem in connecting your database or any php issue don't forget to send me a message or leave your question in the comment section. Share this post guys.

1 comment :