Okay The idea here is to do OO coding.
Code: Select all
<?php
class Model{
function Model(){
//echo 'Model class is initialising....';
}
function connectDB(){
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'test';
mysql_connect($host,$user,$pass) or print mysql_error();
mysql_select_db($db) or print mysql_error();
}
function getData($table,$option,$whereClause){
/**
* DECLARE LOCAL VARIABLES
**/
$counter = 0;
$data = array();
/**
* BUILD SQL QUERY
**/
$sql_query = "SELECT ";
foreach($option as $value){
if((count($option)-1)==$counter){
$sql_query.=$value;
}else{
$sql_query.=$value.',';
}
$counter = $counter+1;
}
$sql_query.= " FROM ".$table;
$sql_query.= " Where ".$whereClause;
//echo $sql_query;
/**
* RUN SQL QUERY AND RETUN END RESULT
**/
$result = mysql_query($sql_query);
if(!$result) {
echo 'Could not run query: ' . mysql_error();
}else{
while($row = mysql_fetch_array($result)){
$data[] = $row;
}
}
return $data;
}
}
?>
And a call to this class from the presentation layer
Code: Select all
require_once('Model.class.php');
$mInv = new Model();
$mInv->connectDB();
$userData = $mInv->getData("user",array('id','name'),"status = 'active'");
I think this is clean code which will save you time and hassle from using mysql database functions everytime you need to retrieve data from the database. So, I am trying to separate my database part from my presentation part (sort of like MVC concept - I am trying to build a mini framework for my small projects.)
So, now as you can see, the $data array is being returned to my presentation part but I am unable to find all the values inside $data. Or perhaps I am not even assigning all the values in the $data array in my function. This is where I am clueless.
P:S: I am learning codeigniter and I know they have cool stuff to solve this problem but I am trying to understand the inner bits.
Many Thanks