How to Connect Database in PHP? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to Connect Database in PHP?

5th Dec 2016, 2:02 PM
Sameer Masood
Sameer Masood - avatar
4 Answers
+ 1
It's very simple <?php $host="localhost"; // name of your host $user="root"; //database user $password=""; // password of database $dbName="DB Name"; // Database name $connect = mysqli_connect($localhost, $user, $password, $dbName) ; //Now, to check connection if(!$connect) { echo("database not connected ") ; } ?>
5th Dec 2016, 8:48 PM
Shan Asif
Shan Asif - avatar
0
$conn = new PDO("mysql: host=localhost; dbname=name", "root", "root_password"); host - ip address of host you wanna connect to (or localhost). dbname - name of database root - user name root_password - password of user then you can do something like: $conn->query("SELECT * FROM table"); If you want to read some more about it type PDO in google ^^
5th Dec 2016, 2:19 PM
Jakub Stasiak
Jakub Stasiak - avatar
0
^I do not recommend Shan's way to connect. PDO is safer and newer way :)
6th Dec 2016, 9:28 AM
Jakub Stasiak
Jakub Stasiak - avatar
0
there are many ways to connect database in php, two are already mention in comment and I'll prefer PDO method which is new and more secure but if you are starter then go to other one that is posted by Shan.
12th Dec 2016, 7:58 PM
Zubair Mehboob
Zubair Mehboob - avatar