PHP / Programming · 2012-12-14

Basic PHP Data Setup

Ideally, when setting up a data-driven PHP site, you should have your configuration and database connection code separate from your code that generates content.  What I want to display is a simple way to keep things separate and simple to work with.

I use a config/index/data file structure.  There are ways to further break apart your code that may allow for more scalability but for the average guy’s website, this is pretty sufficient.

config.php file


<?php

session_start();

// fill out database connection variables
$db_loc = 'localhost';
$db_user = 'root';
$db_pw = '';
$db_db = 'database_name';

// include the Data file to make the database connection
include_once('Data.php');
// instantiate a Data object passing in your connection variables
$d = new Data($db_loc,$db_user,$db_pw,$db_db);
?>

index.php file


<?php
include_once('config.php');
//make array to capture results from query
$my_res = array();
// make query using Data object
$my_res = $d->q('SELECT * FROM company');

// loop through the multidimentional array outputting the values
for($i = 0; $i < sizeof($my_res); $i++){
echo $my_res[$i]['comp_name'];
}

// close out connection object
$d->close();
?>

 

Data.php file


<?php
class Data{
function __construct($db_loc, $db_user, $db_pw, $db_db){
// make class variable to use for querying
$this->c = new mysqli($db_loc, $db_user, $db_pw, $db_db);
// detect errors
if ($this->c->connect_errno) {
echo "Failed to connect to MySQL: (" . $this->c->connect_errno . ") " . $this->c->connect_error;
}
}

/*
Give it a query and it returns the array
*/
function q($query){
// capture results of query
$r = $this->c->query($query);
// make an array to hold the results
$res_arr = array();
// loop through the result set
while($row = $r->fetch_assoc()){
// pass row into result array
$res_arr [] = $row;
}
// return the results
return $res_arr;
}

/*
function to close out connection
*/
function close(){
$this->c->close();
}

}
?>

 

From there, all queries can be made from the index page by simply using the code in the index.php file.