How to connect to the mysql database in php?

This question is often asked by the new PHP Developer who is trying to learn PHP themselves.

Here’s the syntax:

<?php

//connect to the db
$mysqli = new mysqli("hostname","db_username","db_password","db_name");

// Check connection
if ($mysqli->connect_errno) {
  echo "Failed to connect: " . $mysqli->connect_error;
  exit();
}

// query a table
if ($result = $mysqli->query("SELECT * FROM table")) {
  while ($row = $result->fetch_row() ){
    print_r($row);
  }
  //free up the memory
  $result -> free_result();
}

//close the connection
$mysqli->close();

?>

Where the “hostname” will be mostly “localhost” if you’re working on a local computer. Hosting provider of MySQL servers also may have “localhost” but some time they have unique server name like “sql.hosting.etc” or IP address “104.20.65.6”

And the “username” and “password” is mostly be “root”  and  ” ” (blank)  if you are on the local computer. But it will differ for online Hosting!

Here’s the example code (localhost):

<?php

$mysqli = new mysqli("localhost","root","","mydb");

// Check connection
if ($mysqli->connect_errno) {
  echo "Failed to connect: " . $mysqli->connect_error;
  exit();
}

// query a table
if ($result = $mysqli->query("SELECT * FROM users")) {
  while ($row = $result->fetch_row() ){
    print_r($row);
  }
  $result -> free_result();
}

$mysqli->close();

?>

Keep this connection in a separate file so wherever you need you can include this file in your PHP file using below code:

include("connection.php");

I hope this helped a little bit for a beginner PHP Developer, Best of LUCK!

One thought on “How to connect to the mysql database in php?

Leave a Reply

Theme: Overlay by Kaira
Agurchand