MySQL last entry PHP sorted by date - php

I want to display the latest entry from a MySQL database with PHP.
The table (bird_playlog) looks like that:
interpret: Tiny Dancers
title: Bonfire Of The Night
date: 2012-06-11 14:30:58
Screenshot:
The MySQL Connect script:
<?php
class mw_sql{
private $host;
private $user;
private $pass;
private $db;
private $connection = null;
public $connected = false;
public function __construct($data){
$this->host = $data['host'];
$this->user = $data['user'];
$this->pass = $data['pass'];
$this->db = $data['db'];
}
public function __destruct(){
if($this->connected) mysql_close($this->connection);
}
public function connect(){
$this->connection = mysql_connect($this->host, $this->user, $this->pass, true);
if(!$this->connection){
echo '<pre>MySQL connect failed</pre>';
$this->connected = false;
}else{
if(#mysql_select_db($this->db, $this->connection)){
$this->connected = true;
}else{
echo '<pre>MySQL select db failed</pre>';
echo '<pre>'.mysql_error($this->connection).'</pre>';
$this->connected = false;
}
}
return $this->connected;
}
public function select($table, $fields=null, $key=null, $where=null, $sort=null, $sort_dir='ASC', $limit=null){
$cols = (is_array($fields) && $fields != null) ? mysql_real_escape_string(implode(', ', $fields), $this->connection) : '*';
$where_clause = ($where != null) ? ' WHERE '.$where : '';
$sort_clause = ($sort != null) ? ' ORDER BY '.$sort.' '.$sort_dir : '';
$limit_clause = ($limit != null) ? ' LIMIT '.$limit : '';
$query = "SELECT ".$cols." FROM ".$table.$where_clause.$sort_clause.$limit_clause;
$res = #mysql_query($query, $this->connection);
if(!$res){
return false;
}else{
$data = array();
if(mysql_num_rows($res) > 0){
while($dat = mysql_fetch_assoc($res)){
if($key == null) array_push($data, $dat);
else $data[$dat[$key]] = $dat;
}
}
return $data;
}
}
public function query($query){
$res = #mysql_query($query, $this->connection);
if(!$res){
echo mysql_error();
return false;
}else{
return $res;
}
}
public function insert($table, $fields, $values){
$vals = array();
foreach($values as $value){
array_push($vals, mysql_real_escape_string($value, $this->connection));
}
$query = "INSERT INTO ".$table." (".mysql_real_escape_string(implode(', ', $fields), $this->connection).") VALUES ('".implode("', '", $vals)."')";
$res = #mysql_query($query, $this->connection);
if(!$res){
pre(mysql_error($this->connection));
return false;
}
return true;
}
public function update($table, $fields, $values, $where, $error_no_rows=true){
$update = array();
foreach($fields as $key => $value){
if($values[$key] == 'increment'){
array_push($update, $value."=".$value.'+1');
}else{
array_push($update, mysql_real_escape_string($value, $this->connection)."='".mysql_real_escape_string($values[$key], $this->connection)."'");
}
}
$query = "UPDATE ".$table." SET ".implode(', ', $update)." WHERE ".$where;
$res = #mysql_query($query, $this->connection);
if(!$res){
pre(mysql_error($this->connection));
return false;
}
if(mysql_affected_rows($this->connection) == 0 && $error_no_rows){
return false;
}
return true;
}
public function delete($table, $where){
$query = "DELETE FROM ".$table." WHERE ".$where;
echo '<pre>'.$query.'</pre>';
$res = #mysql_query($query, $this->connection);
if(!$res) return false;
return true;
}
} ?>
And the script which shows the latest entry looks like this:
<?php
require_once('mw_sql.class.php');
$cuelist_db_conf = array(
'host' => 'w00b2ffc.kasserver.com',
'user' => 'd0144421',
'pass' => '****',
'db' => 'd0144421',
'table' => 'bird_playlog'
);
$cuelist_db = new mw_sql($cuelist_db_conf);
$cuelist_db->connect();
$last_track = $cuelist_db->select('bird_playlog', array('interpret', 'title'), 'date', 'DESC', 1);
echo $last_track[0]['interpret']; ?>
But the script doesn't show $last_track[0]['interpret'];, so what is wrong? I have no error message...
Thanks for your help! David
UPDATE:
This works:
$con = mysql_connect("w00b2ffc.kasserver.com","d0144421","****");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("d0144421", $con);
$last_track = mysql_query("SELECT * FROM bird_playlog ORDER BY date DESC LIMIT 1");
while($row = mysql_fetch_assoc($last_track)) {
extract($row);
}

I think you should pass null if you don't want.
Because the function originally have 7 parameters to accept and you are passing only 5 so it will not take as you want. It seems that $key you dont want than at for $key you should pass null.
Because if you pass 5 parameter than function will take it as the first 5 parameters and the last two will be taken as default even if you don't want.
I hope this will solve your problem.

Related

How to write helper class for different select operation?

Guys i want different "select" operation as per my needs, but i just need one helper function for all select operation , How do i get it??
This is my helper class Database.php
<?php
class Database
{
public $server = "localhost";
public $user = "root";
public $password = "";
public $database_name = "employee_application";
public $table_name = "";
public $database_connection = "";
public $class_name = "Database";
public $function_name = "";
//constructor
public function __construct(){
//establishes connection to database
$this->database_connection = new mysqli($this->server, $this->user, $this->password, $this->database_name);
if($this->database_connection->connect_error)
die ("Connection failed".$this->database_connection->connect_error);
}
//destructor
public function __destruct(){
//closes database connection
if(mysqli_close($this->database_connection))
{
$this->database_connection = null;
}
else
echo "couldn't close";
}
public function run_query($sql_query)
{
$this->function_name = "run_query";
try{
if($this->database_connection){
$output = $this->database_connection->query($sql_query);
if($output){
$result["status"] = 1;
$result["array"] = $output;
}
else{
$result["status"] = 0;
$result["message"] = "Syntax error in query";
}
}
else{
throw new Exception ("Database connection error");
}
}
catch (Exception $error){
$result["status"] = 0;
$result["message"] = $error->getMessage();
$this->error_table($this->class_name, $this->function_name, "connection error", date('Y-m-d H:i:s'));
}
return $result;
}
public function get_table($start_from, $per_page){
$this->function_name = "get_table";
$sql_query = "select * from $this->table_name LIMIT $start_from, $per_page";
return $this->run_query($sql_query);
}
}
?>
In the above code get_table function performs basic select operation....
Now i want get_table function to perform all this below operations,
$sql_query = "select e.id, e.employee_name, e.salary, dept.department_name, desi.designation_name, e.department, e.designation
from employees e
LEFT OUTER JOIN designations desi ON e.designation = desi.id
LEFT OUTER JOIN departments dept ON e.department = dept.id
ORDER BY e.employee_name
LIMIT $start_from, $per_page";
$sql_query = "select id, designation_name from designations ORDER BY designation_name";
$sql_query = "select * from departments";
$sql_query = "select * from departments Limit 15,10";
So how to overcome this issue, can anyone help me out?
If you expand your class a bit, you could achieve what you are looking for. Something like this:
<?php
class Database
{
public $sql;
public $bind;
public $statement;
public $table_name;
protected $orderby;
protected $set_limit;
protected $function_name;
protected $sql_where;
protected $i;
protected function reset_class()
{
// reset variables
$this->sql = array();
$this->function_name = false;
$this->table_name = false;
$this->statement = false;
$this->sql_where = false;
$this->bind = array();
$this->orderby = false;
$this->set_limit = false;
}
protected function run_query($statement)
{
echo (isset($statement) && !empty($statement))? $statement:"";
}
public function get_table($start_from = false, $per_page = false)
{
// Compile the sql into a statement
$this->execute();
// Set the function if not already set
$this->function_name = (!isset($this->function_name) || isset($this->function_name) && $this->function_name == false)? "get_table":$this->function_name;
// Set the statement
$this->statement = (!isset($this->statement) || isset($this->statement) && $this->statement == false)? "select * from ".$this->table_name:$this->statement;
// Add on limiting
if($start_from != false && $per_page != false) {
if(is_numeric($start_from) && is_numeric($per_page))
$this->statement .= " LIMIT $start_from, $per_page";
}
// Run your query
$this->run_query($this->statement);
// Reset the variables
$this->reset_class();
return $this;
}
public function select($value = false)
{
$this->sql[] = "select";
$this->function_name = "get_table";
if($value != false) {
$this->sql[] = (!is_array($value))? $value:implode(",",$value);
}
else
$this->sql[] = "*";
return $this;
}
public function from($value = false)
{
$this->sql[] = "from";
$this->sql[] = "$value";
return $this;
}
public function where($values = array(), $not = false, $group = false,$operand = 'and')
{
if(empty($values))
return $this;
$this->sql_where = array();
if(isset($this->sql) && !in_array('where',$this->sql))
$this->sql[] = 'where';
$equals = ($not == false || $not == 0)? "=":"!=";
if(is_array($values) && !empty($values)) {
if(!isset($this->i))
$this->i = 0;
foreach($values as $key => $value) {
$key = trim($key,":");
if(isset($this->bind[":".$key])) {
$auto = str_replace(".","_",$key).$this->i;
// $preop = $operand." ";
}
else {
// $preop = "";
$auto = str_replace(".","_",$key);
}
$this->bind[":".$auto] = $value;
$this->sql_where[] = $key." $equals ".":".$auto;
$this->i++;
}
if($group == false || $group == 0)
$this->sql[] = implode(" $operand ",$this->sql_where);
else
$this->sql[] = "(".implode(" $operand ",$this->sql_where).")";
}
else {
$this->sql[] = $values;
}
if(is_array($this->bind))
asort($this->bind);
return $this;
}
public function limit($value = false,$offset = false)
{
$this->set_limit = "";
if(is_numeric($value)) {
$this->set_limit = $value;
if(is_numeric($offset))
$this->set_limit = $offset.", ".$this->set_limit;
}
return $this;
}
public function order_by($column = array())
{
if(is_array($column) && !empty($column)) {
foreach($column as $colname => $orderby) {
$array[] = $colname." ".str_replace(array("'",'"',"+",";"),"",$orderby);
}
}
else
$array[] = $column;
$this->orderby = implode(", ",$array);
return $this;
}
public function execute()
{
$limit = (isset($this->set_limit) && !empty($this->set_limit))? " LIMIT ".$this->set_limit:"";
$order = (isset($this->orderby) && !empty($this->orderby))? " ORDER BY ".$this->orderby:"";
$this->statement = (is_array($this->sql))? implode(" ", $this->sql).$order.$limit:"";
return $this;
}
public function use_table($table_name = 'employees')
{
$this->table_name = $table_name;
return $this;
}
}
To use:
// Create instance
$query = new Database();
// Big query
$query ->select(array("e.id", "e.employee_name", "e.salary", "dept.department_name", "desi.designation_name", "e.department", "e.designation"))
->from("employees e LEFT OUTER JOIN designations desi ON e.designation = desi.id LEFT OUTER JOIN departments dept ON e.department = dept.id")
->order_by(array("e.employee_name"=>""))
->limit(1,5)->get_table();
// More advanced select
$query ->select(array("id", "designation_name"))
->from("designations")
->order_by(array("designation_name"=>""))
->get_table();
// Simple select
$query ->use_table("departments")
->get_table();
// Simple select with limits
$query ->use_table("departments")
->get_table(10,15);
?>
Gives you:
// Big query
select e.id,e.employee_name,e.salary,dept.department_name,desi.designation_name,e.department,e.designation from employees e LEFT OUTER JOIN designations desi ON e.designation = desi.id LEFT OUTER JOIN departments dept ON e.department = dept.id ORDER BY e.employee_name LIMIT 5, 1
// More advanced select
select id,designation_name from designations ORDER BY designation_name
// Simple select
select * from departments
// Simple select with limits
select * from departments LIMIT 10, 15

Insert MySql data from array [duplicate]

This question already has an answer here:
Mysqli prepared statements build INSERT query dynamically from array
(1 answer)
Closed 6 months ago.
<?php
$files=array(name1,name2,name3,);
$conn = new mysqli($host, $user, $pass, $name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO parmi_files (name)
VALUES ('$files')"; ///// -problem is here
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
?>
I want to insert each value from array to MySql row, please solve it out.
Iterate through the items in the array and add them individually:
foreach ($arrayWithValues as $key=>$value) {
$sql = "INSERT INTO parmi_files (name) VALUES ('$value')";
mysqli_query($conn, $sql);
}
Something like this to insert multiple records at once:
$files = array('name1', 'name2', 'name3');
// ...
$filesMap = implode(',', array_map(function($value) {
return "('" . $conn->real_escape_string($value) . "')";
}, $files));
$sql = "INSERT INTO parmi_files (name) VALUES $filesMap";
You could use a PDO abstraction layer for this
I have made a class for this in the past
It uses: PDO, bound parameters, prepared statements
and it inserts everything in one sql query and the insert looks like this:
$db->insertRows('test_table', $default_row, $rows);
The full code
(which might seem a bit long, but makes sense if you read it) including the code for the connection would look like:
<?php
// Establish connection (on demand)
$db = new PdoHelper(function(){
$db_server = 'localhost';
$db_port= '3306';
$db_name = 'your_database';
$db_user = 'your_username';
$db_pass = 'your_password';
$dsn = 'mysql:host='.$db_server.';dbname='.$db_name.';port='.$db_port;
$driver_options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'",
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
);
$dbh = new PDO( $dsn, $db_user, $db_pass, $driver_options );
return $dbh;
});
// Make a blank sample to have default values for row keys
$default_row = array(
'a'=>null,
'b'=>null,
'c'=>null,
);
// The rows that we want to insert, with columns in the wrong order and nonsense
$rows = array(
array(
'b'=>'a2',
'c'=>'a3',
),
array(
'c'=>'b3',
'b'=>'b2',
),
array(
'b'=>'c2',
'c'=>'c3',
'nonsense'=>'boo',
),
);
// The actual insert query
// INSERT INTO `test_table` (`a`,`b`,`c`) VALUES (null,'a2','a3'), (null,'b2','b3'), (null,'c2','c3')
$db->insertRows('test_table', $default_row, $rows);
// The class that does it all
class PdoHelper {
private $db, $factory;
public function __construct($factory)
{
$this->factory = $factory;
}
public function connect()
{
$cb = $this->factory;
$this->db = $cb();
}
public function release()
{
$this->db = null;
}
public function implyConnect()
{
if(!$this->db){
$this->connect();
}
}
public function begin()
{
$this->implyConnect();
if($this->db instanceof PDO){
$this->db->beginTransaction();
}
}
public function commit()
{
$this->implyConnect();
if($this->db instanceof PDO){
$this->db->commit();
}
}
public function prepare($sql, $data=null, $callback=null)
{
$err = null;
$flat_data = array();
if($data){
$flat_data = self::flatten($data);
$sql = preg_replace_callback('/\?/isu', function($v) use (&$data) {
$val = array_shift($data);
if(is_array($val)){
return self::arrayToPlaceholder($val);
}
return '?';
}, $sql);
}
$this->implyConnect();
if($this->db instanceof PDO){
$stmt = $this->db->prepare($sql);
if($stmt instanceof PDOStatement){
$i = 1;
foreach($flat_data as $v) {
if(is_int($v)){
// workaround for a PDO bug with LIMIT ?,?
$stmt->bindValue($i++, $v, PDO::PARAM_INT);
}else{
$stmt->bindValue($i++, $v, PDO::PARAM_STR);
}
}
}
}
if($callback){
return call_user_func_array($callback, array($stmt));
}
return $stmt;
}
public function query($sql)
{
$res = false;
$args = func_get_args();
$data = array();
$callback = null;
if(isset($args[2])){
$data = $args[1];
$callback = $args[2];
}else
if(isset($args[1])){
if(is_callable($args[1])){
$callback = $args[1];
}else{
$data = $args[1];
}
}
$this->implyConnect();
$stmt = $this->prepare($sql, $data);
$res = $stmt->execute();
if($res && $callback && is_callable($callback)){
return call_user_func_array($callback, array($stmt, $this->db));
}
return $stmt;
}
// Helper functions
public function insertRows($table, $default, $rows=array(), $flag=null, $chunk_size=500)
{
if(empty($rows)){
return null;
}
$chunks = array_chunk($rows, $chunk_size);
foreach($chunks as $rows){
$data = array();
$data[] = $this->extend($default, $rows);
// http://stackoverflow.com/questions/1542627/escaping-column-names-in-pdo-statements
$flag = strtolower($flag);
$flags = array(
'ignore'=>'INSERT IGNORE INTO ',
'replace'=>'REPLACE INTO ',
);
$cols = array();
foreach($default as $k=>$v){
$k = str_replace('`', '``', $k);
$cols[] = '`'.$k.'`';
}
$sql = (isset($flags[$flag])?$flags[$flag]:'INSERT INTO ').$table.' ('.implode(',', $cols).') VALUES ?';
if($flag==='update'){
$cols = array();
foreach($default as $k=>$v){
$k = str_replace('`', '``', $k);
$cols[] = '`'.$k.'`=VALUE('.$k.')';
}
$sql .= ' ON DUPLICATE KEY UPDATE '.implode(', ', $cols);
}
$res = $this->query($sql, $data);
if(!$res){
return $res;
}
}
return $res;
}
public function insertRow($table, $default, $row, $flag=null)
{
$rows = array($row);
return $this->insertRows($table, $default, $rows, $flag);
}
// Helper functions
public static function extend($set, $rows)
{
foreach($rows as $k=>$v){
$v = array_intersect_key($v, $set);
$rows[$k] = array_replace($set, $v);
}
return $rows;
}
public static function flatten($x)
{
$d = array();
if(is_array($x)){
foreach($x as $k=>$v){
$d = array_merge($d, self::flatten($v));
}
}else{
$d[] = $x;
}
return $d;
}
public static function arrayToPlaceholder($array, $timeZone=null) {
return implode(',', array_map(function($v) use($timeZone){
if(is_array($v)){
return '('.self::arrayToPlaceholder($v, $timeZone).')';
}
return '?';
}, $array));
}
public function arrayToList($array, $timeZone=null) {
return implode(',',array_map(function($v) use($timeZone){
if(is_array($v)){
return '('.self::arrayToList($v, $timeZone).')';
}
$this->implyConnect();
return $this->escape($v);
},$array));
}
public function escape($val, $stringifyObjects=false, $timeZone=false) {
if(is_null($val)) return 'NULL';
if(is_bool($val)) return ($val) ? 'true' : 'false';
if(is_int($val)) return (string)$val;
if(is_float($val)) return (string)$val;
if (is_array($val)) {
return $this->arrayToList($val, $timeZone);
}
if(is_callable($val)){ return null; } // TODO
$val = preg_replace_callback('/[\0\n\r\b\t\\\'\"\x1a]/um', function($s) {
switch($s) {
case "\0": return "\\0";
case "\n": return "\\n";
case "\r": return "\\r";
case "\b": return "\\b";
case "\t": return "\\t";
case "\x1a": return "\\Z";
default: return "\\".$s;
}
}, $val);
return $this->db->Quote($val);
}
// Debug functions
public function getSQL($sql, $data){
foreach($data as $k=>$v){
if(is_array($v)){
$data[$k] = self::arrayToList($v);
}else{
$this->implyConnect();
$data[$k] = $this->escape($v);
}
}
$sql = preg_replace_callback('/\?/', function($match) use(&$data)
{
return array_shift($data);
}, $sql);
return $sql;
}
}

How do I create a user defined function for mysqli_num_rows in php OOPs?

I have tried my best to find out the result on my own, but have failed.
Here's the source code that I have tried at my level best.
<?php
class DataBase
{
private $connect;
private $dbUser;
private $dbHost;
private $dbPassword;
private $dbDatabase;
private $numRows;
private $results;
public function connect($host, $username, $pass, $db)
{
$this->dbHost = $host;
$this->dbUser = $username;
$this->dbPassword = $pass;
$this->dbDatabase = $db;
return $this->connect = mysqli_connect($this->dbHost, $this->dbUser, $this->dbPassword, $this->dbDatabase);
}
public function disConnect($connect) {
return mysqli_close($this->connect = $connect);
}
public function select($table, $where = array(), $orderBy = NULL) {
if (count($where) === 3) {
$operators = array('=', '<', '>', '>=', '<=', 'LIKE');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if (in_array($operator, $operators)) {
$query = "SELECT * FROM {$table} WHERE '". $field . $operator . $value . "'";
}
if (mysqli_query($this->connect, $query)) {
return true;
} else {
die(mysqli_error($this->connect));
}
}
}
public function countRows($queryRes)
{
if (mysqli_num_rows($queryRes) > 0) {
return true;
} else {
return false;
}
}
}
I get the error:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\wamp\www\Practice\index.php on line 70
and line 70 is: if (mysqli_num_rows($queryRes) > 0) {
Here's where and how I call the method:
$suc = "";
if (isset($_POST['btnSubmit'])) {
$con = new DataBase();
$objDb = $con->connect('localhost', 'root', '', 'practice');
$username = $_POST["username"];
$suc = $con->select('users', ['username', 'LIKE', '%'.$username.'%']);
if ($suc) {
print_r($con->countRows($suc));
} else {
echo "Unable to Find Record !";
}
//print_r($suc);
$con->disConnect($objDb);
}
?>
Kindly guide me where am I making the mistake.
Thanks
function countRows($sql)
{
$rst = #mysql_query($sql)or trigger_error("SQxxxL", E_USER_ERROR);
return $numrows = mysql_num_rows($rst);
}
You have $numRows class property. Why you are not using it?
Set query number of rows count into $this->numRows property.
Change your select() method:
public function select($table, $where = array(), $orderBy = NULL) {
if (count($where) === 3) {
$operators = array('=', '<', '>', '>=', '<=', 'LIKE');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if (in_array($operator, $operators)) {
$query = "SELECT * FROM {$table} WHERE '". $field . $operator . $value . "'";
}
$result = mysqli_query($this->connect, $query);
if ($result) {
$this->numRows = mysqli_num_rows($result);
return true;
} else {
die(mysqli_error($this->connect));
}
}
}
And change your countRows() method like yhis:
public function countRows($queryRes)
{
return $this->numRows == 0 ? false : true;
}

how to loop through multiple MySQL databases in a PHP script

I have inherited the below code, which creates a web interface for a MySQL database named 'database_name' and defined by the variable $database.
I want to add an additional database to this script, so that the same interface can be created this second database (which is set up in exactly the same way as the first database with the same tables names, etc., but contains different data). Is there a way to make $database a string array which I can loop over for multiple database names?
<?php
class DatabaseInterface {
public $host = "localhost"; //(name or ip address)
public $userName = "aksfhah";
public $passWord = "**********";
public $database = 'database_name';
public $tableData = "measurements";
public $tableMinbins = "minbins";
public $tableHourbins = "hourbins";
public $tableDaybins = "daybins";
public $tableDescriptions = "measurementDescriptions";
public $tableSpecs = "experimentDescriptions";
public $connection;
public function __construct($databaseName = "database_name") {
$this->database = $databaseName;
$this->connect();
}
public function connect($databaseName = null) {
$dbh = mysql_connect($this->host, $this->userName, $this->passWord);
if (is_null($databaseName)) {
mysql_select_db($this->database);
} else {
mysql_select_db($databaseName);
}
$this->connection = $dbh;
return $dbh;
}
public function initializeDatabase() {
$this->createDataTable($this->tableData);
$query = "create table if not exists $this->tableDescriptions (id int auto_increment primary key,type varchar(255),
description varchar(255), experimentname varchar(255), unique Key(description,experimentname)) engine=myisam";
mysql_query($query); //create a table if it does not exist
echo mysql_error(); //report error if one occurred
}
private function createDataTable($tableName) {
$query = "CREATE TABLE IF NOT EXISTS $tableName (
id smallint(5) unsigned NOT NULL,
time datetime NOT NULL,
measurement float DEFAULT NULL,
rebinned tinyint(4) DEFAULT '0',
PRIMARY KEY (id,time),
KEY (rebinned,id)
) ENGINE=MyISAM";
mysql_query($query); //create a table if it does not exist
echo mysql_error(); //report error if one occurred
}
public function insertByDescription($time, $value, $channelDescription, $experimentDescription, $type = "other") {
$sensorID = $this->createIdFromDescription($channelDescription, $experimentDescription, $type);
return $this->insertById($time, $value, $sensorID);
}
public function insertMultipleById($timeArray, $valueArray, $sensorID,$tableName=null) {
if(is_null($tableName)){
$tableName= $this->tableData;
}
if (count($timeArray) == 0)
return 0;
$query = "insert ignore into $tableName (id,time,measurement)
VALUES ";
for ($index = 0; $index < count($timeArray); $index++) {
$timeString = $timeArray[$index]->format("Y-m-d H:i:s");
$value = $valueArray[$index];
$query = $query . "('$sensorID','$timeString','$value'),";
}
$query = substr($query, 0, strlen($query) - 1); //trim final comma
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error();
return false;
} else
return mysql_affected_rows();
}
public function insertMultipleByDescription($timeArray, $valueArray, $channelDescription, $experimentDescription, $type = "other",$tableName=null) {
$sensorID = $this->createIdFromDescription($channelDescription, $experimentDescription, $type);
return $this->insertMultipleById($timeArray, $valueArray, $sensorID,$tableName);
}
public function insertById(DateTime $time, $value, $sensorID) {
$timeString = $time->format("Y-m-d H:i:s");
$query = "insert ignore into $this->tableData (id,time,measurement)
VALUES ('$sensorID','$timeString','$value')";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error();
return false;
} else if (mysql_affected_rows() == 0) {
return false;
} else {
return true;
}
}
public function createIdFromDescription($channelDescription, $experimentDescription, $type) {
$sensorId = $this->getIdFromDescription($channelDescription, $experimentDescription);
if (!$sensorId) {
$query = "insert ignore into $this->tableDescriptions (description,experimentname,type)
VALUES ('$channelDescription','$experimentDescription','$type')";
$result = mysql_query($query);
$sensorId = mysql_insert_id();
}
return $sensorId;
}
public function getIdFromDescription($measurementDescription, $experimentDescription) {
$sensorId = false;
$query = "select id from $this->tableDescriptions where description like '$measurementDescription'
&& experimentname like '$experimentDescription'";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
if (mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
$sensorId = $row['id'];
}
return $sensorId;
}
function getDataById($id, $startDate, $endDate, $interval = "") {
$data = array();
$startDateString = $startDate->format("Y-m-d H:i:s");
$endDateString = $endDate->format("Y-m-d H:i:s");
$query = "select time,measurement from $this->tableData where id='$id' && time>='$startDateString' && time <='$endDateString' order by time asc " . $interval = "" ? "" : "group by $interval";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
while ($row = mysql_fetch_array($result)) {
//$time = new DateTime($row['time']);
$data[] = array($row['time'], $row['measurement'] * 1);
}
return $data;
}
public function getMostRecentData($id, $table) {
$query = "select date(max(time)) as time,measurement from $table where id='$id'";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
} elseif (mysql_num_rows($result) > 0) {
$row = mysql_fetch_array($result);
return $row;
} else {
return false;
}
}
public function getExperimentList() {
$list = array();
$query = "select distinct experimentname from $this->tableDescriptions";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
while ($row = mysql_fetch_array($result)) {
$list[] = $row['experimentname'];
}
return $list;
}
public function getChannelList($experimentDescription) {
$list = array();
$query = "select id,description,type from $this->tableDescriptions where experimentname='$experimentDescription'";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
while ($row = mysql_fetch_array($result)) {
$list[$row['description']] = array("id" => $row['id'], "type" => $row['type']);
}
return $list;
}
public function getDescriptionFromId($id) {
$query = "select * from $this->tableDescriptions where id='$id'";
$result = mysql_query($query);
if (mysql_error()) {
echo mysql_error(); //report error if one occurred
return false;
}
if (mysql_num_fields($result) > 0) {
$row = mysql_fetch_array($result);
return array($row['type'], $row['description'], $row['experimentname']);
} else {
return false;
}
}
public function getDisplayName($experimentName) {
$query = "select displayName from $this->tableSpecs where experimentName='$experimentName'";
$result = mysql_query($query);
echo mysql_error();
$row = mysql_fetch_array($result);
if ($row) {
return $row['displayName'];
} else {
return false;
}
}
public function simpleQuery($query) {
$result = mysql_query($query);
echo mysql_error();
if ($result) {
$row = mysql_fetch_array($result);
if ($row) {
return $row[0];
} else {
return FALSE;
}
} else {
return FALSE;
}
}
public function rebin($tableSource, $tableTarget, $numSeconds, $sum = false) {
$this->createDataTable($tableTarget);
echo "Updating $tableSource to set rebinned from 0 to 2...";
$query = "update $tableSource set rebinned=2 where rebinned =0;";
mysql_query($query);
echo mysql_error();
echo "Done.\n";
$numRows = mysql_affected_rows();
echo "Found $numRows records in $tableSource that need rebinning...\n";
$query = "select id,from_unixtime(floor(unix_timestamp(min(time))/$numSeconds)*$numSeconds) as mintime from $tableSource where rebinned=2 group by id;";
$result = mysql_query($query);
echo mysql_error();
if ($result) {
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$mintime = $row['mintime'];
echo $id . "...";
$query = "INSERT INTO $tableTarget (id,time,measurement,rebinned)
SELECT id,from_unixtime(floor(unix_timestamp(time)/$numSeconds)*$numSeconds)," . ($sum ? "sum" : "avg") . "(measurement) as measurement,0
FROM $tableSource WHERE id=$id && time>='$mintime'
GROUP BY id,floor(unix_timestamp(time)/$numSeconds)
ON DUPLICATE KEY UPDATE measurement=values(measurement), rebinned=0;";
mysql_query($query);
//echo $query;
echo mysql_error();
echo "Done.\n";
}
echo "Updating $tableSource to set rebinned from 2 to 1...";
$query = "update $tableSource set rebinned=1 where rebinned =2;";
mysql_query($query);
echo mysql_error();
echo "Done.\n";
}
}
public function getDCPower($experimentName, $startDate, $endDate) {
$out = array();
$query = $this->buildDCPowerQuery($experimentName, $this->tableMinbins);
if ($query) {
if ($startDate != "") {
$query = $query . " && m0.time>='$startDate' ";
}
if ($endDate != "") {
$query = $query . " && m0.time<='$endDate' ";
}
echo $query;
$result = mysql_query($query);
echo mysql_error();
while ($row = mysql_fetch_array($result)) {
// echo $row['time'].", ".$row['power']."\n";
$out[] = array($row['time'], $row['power'] + 0);
}
return $out;
} else {
return FALSE;
}
}
}
?>
Is there a way to make $database a string array which I can loop over for multiple database names?
No, it does not work that way. The script you have defines a class. You have to look in the file that uses that class, where there will be something like
$interface = new DatabaseInterface("database1");
There you'll be able to do things such as
$interface = array();
$interface[0] = new DatabaseInterface("database1");
$interface[1] = new DatabaseInterface("database2");
and use two instances of the interface against the two databases.

Connect to MySQL database using PHP OOP concept

I'm writing a class and handful of functions to connect to the database and retrieve the information from the tables. I went through previous posts having similar titles, but most of them have written using mysql functions and I am using mysqli functions.
I want somebody who can go through this simple script and let me know where I am making my mistake.
This is my class.connect.php:
<?php
class mySQL{
var $host;
var $username;
var $password;
var $database;
public $dbc;
public function connect($set_host, $set_username, $set_password, $set_database)
{
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
$this->database = $set_database;
$this->dbc = mysqli_connect($this->host, $this->username, $this->password, $this->database) or die('Error connecting to DB');
}
public function query($sql)
{
return mysqli_query($this->dbc, $sql) or die('Error querying the Database');
}
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql));
return $array;
}
public function close()
{
return mysqli_close($this->dbc);
}
}
?>
This is my index.php:
<?php
require_once ("class.connect.php");
$connection = new mySQL();
$connection->connect('localhost', 'myDB', 'joker', 'names_list');
$myquery = "SELECT * FROM list";
$query = $connection->query($myquery);
while($array = $connection->fetch($query))
{
echo $array['first_name'] . '<br />';
echo $array['last_name'] . '<br />';
}
$connection->close();
?>
I am getting the error saying that Error querying the Database.
Few problems :-
you don't die without provide a proper mysql error (and is good practice to exit gracefully)
fetch method is only FETCH the first row
mysqli have OO method, why you still using procedural function?
The problem is either this:
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql));
return $array;
}
or this:
while($array = $connection->fetch($query))
Because you are using the result from the query to query again. Basically, you are doing:
$r = mysqli_query($this->dbc, $sql);
$array = mysqli_fetch_array(mysqli_query($this->dbc, $r));
And you are getting an error, because $r is not a query string. When it's converted to a string, it's a "1" (from your other comment).
Try changing the function to (changed name of variable so you can see the difference):
public function fetch($result)
{
return mysqli_fetch_array($result);
}
or just call the function directly.
If you don't do your own db abstraction for learning php and mysql, you can use Medoo (http://medoo.in/).
It's a free and tiny db framework, that could save a huge work and time.
Obviously an error occurs on SELECT * FROM list you can use mysqli_error to find the error:
return mysqli_query($this->dbc, $sql) or die('Error:'.mysqli_error($this->dbc));
This will display the exact error message and will help you solve your problem.
Try to check this
https://pramodjn2.wordpress.com/
$database = new db();
$query = $database->select(‘user’);
$st = $database->result($query);
print_r($st);
class db {
public $server = ‘localhost';
public $user = ‘root';
public $passwd = ‘*****';
public $db_name = ‘DATABASE NAME';
public $dbCon;
public function __construct(){
$this->dbCon = mysqli_connect($this->server, $this->user, $this->passwd, $this->db_name);
}
public function __destruct(){
mysqli_close($this->dbCon);
}
/* insert function table name, array value
$values = array(‘first_name’ => ‘pramod’,’last_name’=> ‘jain’);
*/
public function insert($table,$values)
{
$sql = “INSERT INTO $table SET “;
$c=0;
if(!empty($values)){
foreach($values as $key=>$val){
if($c==0){
$sql .= “$key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= “, $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$c++;
}
}else{
return false;
}
$this->dbCon->query($sql) or die(mysqli_error());
return mysqli_insert_id($this->dbCon);
}
/* update function table name, array value
$values = array(‘first_name’ => ‘pramod’,’last_name’=> ‘jain’);
$condition = array(‘id’ =>5,’first_name’ => ‘pramod!’);
*/
public function update($table,$values,$condition)
{
$sql=”update $table SET “;
$c=0;
if(!empty($values)){
foreach($values as $key=>$val){
if($c==0){
$sql .= “$key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= “, $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$c++;
}
}
$k=0;
if(!empty($condition)){
foreach($condition as $key=>$val){
if($k==0){
$sql .= ” WHERE $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= ” AND $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$k++;
}
}else{
return false;
}
$result = $this->dbCon->query($sql) or die(mysqli_error());
return $result;
}
/* delete function table name, array value
$where = array(‘id’ =>5,’first_name’ => ‘pramod’);
*/
public function delete($table,$where)
{
$sql = “DELETE FROM $table “;
$k=0;
if(!empty($where)){
foreach($where as $key=>$val){
if($k==0){
$sql .= ” where $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= ” AND $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$k++;
}
}else{
return false;
}
$del = $result = $this->dbCon->query($sql) or die(mysqli_error());
if($del){
return true;
}else{
return false;
}
}
/* select function
$rows = array(‘id’,’first_name’,’last_name’);
$where = array(‘id’ =>5,’first_name’ => ‘pramod!’);
$order = array(‘id’ => ‘DESC’);
$limit = array(20,10);
*/
public function select($table, $rows = ‘*’, $where = null, $order = null, $limit = null)
{
if($rows != ‘*’){
$rows = implode(“,”,$rows);
}
$sql = ‘SELECT ‘.$rows.’ FROM ‘.$table;
if($where != null){
$k=0;
foreach($where as $key=>$val){
if($k==0){
$sql .= ” where $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= ” AND $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$k++;
}
}
if($order != null){
foreach($order as $key=>$val){
$sql .= ” ORDER BY $key “.htmlentities($val, ENT_QUOTES).””;
}
}
if($limit != null){
$limit = implode(“,”,$limit);
$sql .= ” LIMIT $limit”;
}
$result = $this->dbCon->query($sql);
return $result;
}
public function query($sql){
$result = $this->dbCon->query($sql);
return $result;
}
public function result($result){
$row = $result->fetch_array();
$result->close();
return $row;
}
public function row($result){
$row = $result->fetch_row();
$result->close();
return $row;
}
public function numrow($result){
$row = $result->num_rows;
$result->close();
return $row;
}
}
The mysqli_fetch_array function in your fetch method requires two parameters which are the SQL result and the kind of array you intend to return. In my case i use MYSQLI_ASSOC.
That is it should appear like this:
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql), MYSQLI_ASSOC);
return $array;
}
**classmysql.inc.php**
<?php
class dbclass {
var $CONN;
function dbclass() { //constructor
$conn = mysql_connect(SERVER_NAME,USER_NAME,PASSWORD);
//$conn = mysql_connect(localhost,root,"","");
if(!$conn)
{ $this->error("Connection attempt failed"); }
if(!mysql_select_db(DB_NAME,$conn))
{ $this->error("Database Selection failed"); }
$this->CONN = $conn;
return true;
}
//_____________close connection____________//
function close(){
$conn = $this->CONN ;
$close = mysql_close($conn);
if(!$close){
$this->error("Close Connection Failed"); }
return true;
}
function error($text) {
$no = mysql_errno();
$msg = mysql_error();
echo "<hr><font face=verdana size=2>";
echo "<b>Custom Message :</b> $text<br><br>";
echo "<b>Error Number :</b> $no<br><br>";
echo "<b>Error Message :</b> $msg<br><br>";
echo "<hr></font>";
exit;
}
//_____________select records___________________//
function select ($sql=""){
if(empty($sql)) { return false; }
if(!eregi("^select",$sql)){
echo "Wrong Query<hr>$sql<p>";
return false; }
if(empty($this->CONN)) { return false; }
$conn = $this->CONN;
$results = #mysql_query($sql,$conn);
if((!$results) or empty($results)) { return false; }
$count = 0;
$data = array();
while ( $row = mysql_fetch_array($results)) {
$data[$count] = $row;
$count++; }
mysql_free_result($results);
return $data;
}
//________insert record__________________//
function insert ($sql=""){
if(empty($sql)) { return false; }
if(!eregi("^insert",$sql)){ return false; }
if(empty($this->CONN)){ return false; }
$conn = $this->CONN;
$results = #mysql_query($sql,$conn);
if(!$results){
$this->error("Insert Operation Failed..<hr>$sql<hr>");
return false; }
$id = mysql_insert_id();
return $id;
}
//___________edit and modify record___________________//
function edit($sql="") {
if(empty($sql)) { return false; }
if(!eregi("^update",$sql)){ return false; }
if(empty($this->CONN)){ return false; }
$conn = $this->CONN;
$results = #mysql_query($sql,$conn);
$rows = 0;
$rows = #mysql_affected_rows();
return $rows;
}
//____________generalize for all queries___________//
function sql_query($sql="") {
if(empty($sql)) { return false; }
if(empty($this->CONN)) { return false; }
$conn = $this->CONN;
$results = mysql_query($sql,$conn) or $this->error("Something wrong in query<hr>$sql<hr>");
if(!$results){
$this->error("Query went bad ! <hr>$sql<hr>");
return false; }
if(!eregi("^select",$sql)){return true; }
else {
$count = 0;
$data = array();
while ( $row = mysql_fetch_array($results))
{ $data[$count] = $row;
$count++; }
mysql_free_result($results);
return $data;
}
}
function extraqueries($sql="") {
if(empty($sql)) { return false; }
if(empty($this->CONN)) { return false; }
$conn = $this->CONN;
$results = mysql_query($sql,$conn) or $this->error("Something wrong in query<hr>$sql<hr>");
if(!$results){
$this->error("Query went bad ! <hr>$sql<hr>");
return false; }
else {
$count = 0;
$data = array();
while ( $row = mysql_fetch_array($results))
{ $data[$count] = $row;
$count++; }
mysql_free_result($results);
return $data;
}
}
}
?>
**config.inc.php**
<?php
ini_set("memory_limit","70000M");
ini_set('max_execution_time', 900);
ob_start();
session_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
############################################
# Database Server
############################################
if($_SERVER['HTTP_HOST']=="localhost")
{
define("DB_NAME","DB_NAME");
define("SERVER_NAME","SERVER_NAME");
define("USER_NAME","USER_NAME");
define("PASSWORD","PASSWORD");
}
else
{
define("DB_NAME","DB_NAME");
define("SERVER_NAME","SERVER_NAME");
define("USER_NAME","USER_NAME");
define("PASSWORD","PASSWORD");
}
#############################################
# File paths
#############################################
// For the Database file path
include("system/classmysql.inc.php");
//For the inc folders
define("INC","inc/");
//For the Function File of the pages folders
define("FUNC","func/");
//For the path of the system folder
define("SYSTEM","system/");
$table_prefix = 'dep_';
################################################################
# Database Class
################################################################
$obj_db = new dbclass();
?>
**Function Page**
<?php
// IF admin is not logged in
if(!isset($_SESSION['session_id']))
{
header("location:index.php");
}
$backpage = 'page.php?type=staff&';
if(isset($_REQUEST['endbtn']) && trim($_REQUEST['endbtn']) == "Back")
{
header("location:".$backpage);
die();
}
// INSERT into database.
if(isset($_REQUEST['submit']) && trim($_REQUEST['submit']) == "Submit")
{
$pass = addslashes(trim($_REQUEST['password']));
$password = encrypt($pass, "deppro");
$username = addslashes(trim($_REQUEST['username']));
$sql = "select * from ".$table_prefix."users where `UserName` ='".$username."'";
$result = $obj_db->select($sql);
if(count($result) == 0)
{
$insert="INSERT INTO ".$table_prefix."users (`UserName`)VALUES ('".$username."')";
$sql=$obj_db->insert($insert);
$newuserid = mysql_insert_id($obj_db->CONN);
}
header("location:".$backpage."msg=send&alert=2");
die();
}
// DELETE record from database
if(isset($_REQUEST['action']) && trim($_REQUEST['action'])==3)
{
if(isset($_REQUEST['id']) && trim($_REQUEST['id']!=""))
{
$id = site_Decryption($_REQUEST['id']);
$sql_del = "Delete from ".$table_prefix."users where StaffID ='$id'";
$del = $obj_db->sql_query($sql_del);
header("location:".$backpage."msg=delete&alert=2");
die();
}
}
// UPDATE the record
$action=1;
if((isset($_REQUEST['action']) && trim($_REQUEST['action'])==2) && (!(isset($_REQUEST['submit']) && trim($_REQUEST['submit']) == "Submit")))
{
if(isset($_REQUEST['id']) && trim($_REQUEST['id']!=""))
{
$id = site_Decryption($_REQUEST['id']);
//$id = $_SESSION['depadmin_id'];
$sql = "select * from ".$table_prefix."users where StaffID ='$id'";
$result = $obj_db->select($sql);
if($result)
{
foreach($result as $row)
{
$title = stripslashes($row['StaffTitle']);
$action=2;
}
}
if(isset($_REQUEST['submit']) && trim($_REQUEST['submit']) == "Update")
{
$title = addslashes(trim($_REQUEST['title']));
$sql_upd ="UPDATE ".$table_prefix."users SET `StaffTitle` = '$title' WHERE StaffID ='$id'";
$result = $obj_db->sql_query($sql_upd);
$action=1;
header("location:".$backpage."msg=edited&alert=2");
die();
}
}
}
if(isset($_REQUEST['vid']) && trim($_REQUEST['vid']!=""))
{
$id = site_Decryption($_REQUEST['vid']);
$sql = "select * from ".$table_prefix."users where StaffID ='$id'";
$result = $obj_db->select($sql);
if($result)
{
foreach($result as $row)
{
$username = stripslashes($row['UserName']);
}
}
}
?>
<td class="center"><span class="editbutton"> </span> <span class="deletebutton"> </span> <a class="lightbox" title="View" href="cpropertyview.php?script=view&vid=<?php echo site_Encryption($sql[$j]['PropertyID']); ?>&lightbox[width]=55p&lightbox[height]=60p"><span class="viewbutton"> </span></a></td>

Categories