Skip to main content

How to Connect To Your Database Using PHP and MySQLi

Connecting your project to SQL Database comes with these 3 requirements.
1. Create 2 Pages (Optional tho' but safe) with these names:
  • config.php
  • connect.php
Reasons, If A hacker, hacks to your connect page, he'll get all there is to know about your script and your database and that might be really harmful but if, there's a configuration with secret details and a connection with configured details separately created there's actually a sense of safety.

In the first 
config.php
Type these codes

<?php 
define("DATABASE_HOST","localhost");
define("DATABASE_USER","root");

define("DATABASE_NAME","test_name");
define("DATABASE_CODE",""); 
?> 


DATABASE_HOST
This Database_host is by default a "localhost" since it is a test work done locally, using *AMP (APACHE,  MYSQL, & PHP).

DATABASE_USER
 The database user is by default "root" but can be alternated, So Just be sure what, before configurations
  
DATABASE_NAME
This a Name You Created In Your Database, therefore names vary, but let's assume it's "test_name"

DATABASE_CODE
The Code by default is Null (i.e Empty). If you have a Password use it.
on your config.php type...

<?php 
include_once 'config.php';
$conn = mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_CODE);
mysqli_select_db($conn, DATABASE_NAME);
?> 


Taaadaaah, You're Connected. To Test Connection write:

<?php 
include_once 'config.php';
$conn = mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_CODE);
$connection_status = ($conn) ? "Connected" : "Failed" ;
echo 
$connection_status;
mysqli_select_db($conn, DATABASE_NAME);
?> 


 i.e means if connected echo "Connected", else echo "failed".

Comments

Popular posts from this blog

PHP Chaining Function

PHP 4 - 7, Offers Chaining Function With Slight Differences, but this Post and Example Focuses on PHP 7's. Study the Example Below, Take note of the Power Array, Contatenation and Conditional Statements Have <?php class DBManager {     private $selectables = array();     private $table;     private $whereClause;     private $orderClause;     private $limit;     public function select() {         $this->selectables = func_get_args();         return $this;     }     public function from($table) {         $this->table = $table;         return $this;     }     public function where($where) {         $this->whereClause = $where;         return $this;     }     public function order($type) {         $this->orderClause = strtoupper($type);         return $this;     }     public function limit($limit) {         $this->limit = $limit;         return $this;     }     public function result() {         $query[] = "SELECT";         // if the selectables array is e