how to loop through multiple MySQL databases in a PHP script - php

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.

Related

Class not found in C:\wamp\www\system\core\Loader.php on line 303

OK, I am new to PHP so I plead you to have understanding.
I have made my new application, however I can't figure out why is it complaining about. I get very odd and strange error
db->query($sql);
if ($query->num_rows() > 0) {
$row = $query->row();
foreach ($row as $key => $val) {
$this->$key = $val;
}
return $row;
}
return null;
}
function getUser($info=NULL, $active=NULL) {
$sql = "SELECT * FROM tv_user WHERE 1 = 1 ";
if (!is_null($info)) {
if (empty($info->username) || empty($info->password)) {
return null;
}
if (!empty($info->username)) {
$sql .= " AND (username = '{$info->username}' OR email = '{$info->username}' OR id = '{$info->username}') ";
}
if (!empty($info->password)) {
$sql .= " AND password = '".md5($info->password)."' ";
}
}
if (!empty($active)) {
$sql .= " AND active = '{$active}' ";
}
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
$row = $query->row();
foreach ($row as $key => $val) {
$this->$key = $val;
}
return $row;
}
return null;
}
function getUsers($active=NULL) {
$sql = "SELECT * FROM tv_user WHERE 1 = 1";
if (!empty($active)) {
$sql .= " AND active = '{$active}'";
}
$query = $this->db->query($sql);
return $query->result();
}
function isUserExist($username=NULL, $active=NULL) {
$sql = "SELECT * FROM tv_user WHERE 1 = 1 ";
if (!empty($username)) {
$sql .= " AND username = '{$username}' ";
}
if (!empty($active)) {
$sql .= " AND active = '{$active}' ";
}
$query = $this->db->query($sql);
return ($query->num_rows() > 0);
}
function getUserByEmail($email, $active=NULL) {
if (empty($email)) { return null; }
$sql = "SELECT * FROM tv_user WHERE email = '{$email}' ";
if (!empty($active)) {
$sql .= " AND active = '{$active}' ";
}
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
$row = $query->row();
foreach ($row as $key => $val) {
$this->$key = $val;
}
return $row;
}
return null;
}
function getSocialUser($uid=NULL, $provider,$email=NULL, $active=NULL) {
if (empty($provider)) { return null; }
$sql = "SELECT * FROM tv_user WHERE 1 = 1 ";
if (!empty($uid)) { $sql .= " AND uid = '{$uid}' "; }
if (!empty($email)) { $sql .= " AND email = '{$email}' "; }
$sql .= " AND provider='{$provider}'";
if (!empty($active)) { $sql .= " AND active = '{$active}' "; }
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
$row = $query->row();
foreach ($row as $key => $val) {
$this->$key = $val;
}
return $row;
}
return null;
}
function uuid() {
return strtoupper(substr(dechex(time()).dechex(mt_rand(1,65535)), 0, 6));
}
function add($data) {
return $this->db->insert("tv_user", $data);
}
function update($data, $where) {
return $this->db->update("tv_user", $data, $where);
}
function delete($where) {
return $this->db->delete("tv_user", $where);
}
function login($username, $password) {
if (empty($username) || empty($password)) {
return FALSE;
}
$password = md5($password);
$sql = "SELECT * FROM tv_user WHERE username='{$username}' AND password='{$password}' AND active=1";
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
$user = $query->row();
$user_data = array();
foreach($user as $key => $val){
$user_data[$key] = $val;
}
$user_data["login"] = TRUE;
$this->session->set_userdata('user', $user_data);
if ($user->user_type == USR_ROOT) {
$this->session->set_userdata('root_addmin_logged_in', TRUE);
$this->session->set_userdata('addmin_logged_in', TRUE);
} else
if (in_array($user->user_type,array(USR_ADMIN,
USR_MODERATOR,
USR_TOUR,
USR_HOTEL,
USR_FLIGHT,
USR_VISA)
))
{
$this->session->set_userdata('root_addmin_logged_in', FALSE);
$this->session->set_userdata('addmin_logged_in', TRUE);
} else {
$this->session->set_userdata('root_addmin_logged_in', FALSE);
$this->session->set_userdata('addmin_logged_in', FALSE);
}
$this->session->set_userdata('logged_in', TRUE);
$this->session->set_userdata('logged_user', $user);
return TRUE;
}
return FALSE;
}
function logout() { $this->session->sess_destroy(); }
function verify_reset_password_code($email, $code) {
if (empty($email) || empty($code)) {
return FALSE;
}
$sql = "SELECT * FROM tv_user WHERE email = '{$email}' ";
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
$row = $query->row();
return ($code == md5(SITE_NAME.$row->fullname))? TRUE : FALSE;
} else {
return FALSE;
}
}
}
?>
which is interpreted as
PHP Fatal error: Class 'M_user' not found in C:\wamp\www\system\core\Loader.php on line 303
I am not very good in this since I am new. I have to say that I am running my application under WAMP.It may be something trivial, but I don't get it.
I have even included all modules in my autoload.php file as following:
$autoload['model'] = array(
'm_user',
'm_user_online',
'm_content_category',
'm_content',
'm_nation',
'm_mail',
'm_message',
'm_feedback',
'm_photo',
'm_tour',
'm_tour_rate',
'm_tour_departure',
'm_tour_departure_rate',
'm_tour_itinerary',
'm_tour_category',
'm_tour_activity',
'm_tour_destination',
'm_tour_tripnote',
'm_tour_request',
'm_visa',
'm_visa_tips',
'm_question',
'm_hotel',
'm_room',
'm_room_rate',
'm_album_category',
'm_album',
'm_tour_option_category'
);
Part of the code where it gets mentioned:
// --------------------------------------------------------------------
/**
* Model Loader
*
* This function lets users load and instantiate models.
*
* #param string the name of the class
* #param string name for the model
* #param bool database connection
* #return void
*/
public function model($model, $name = '', $db_conn = FALSE)
{
if (is_array($model))
{
foreach ($model as $babe)
{
$this->model($babe);
}
return;
}
if ($model == '')
{
return;
}
$path = '';
// Is the model in a sub-folder? If so, parse out the filename and path.
if (($last_slash = strrpos($model, '/')) !== FALSE)
{
// The path is in front of the last slash
$path = substr($model, 0, $last_slash + 1);
// And the model name behind it
$model = substr($model, $last_slash + 1);
}
if ($name == '')
{
$name = $model;
}
if (in_array($name, $this->_ci_models, TRUE))
{
return;
}
$CI =& get_instance();
if (isset($CI->$name))
{
show_error('The model name you are loading is the name of a resource that is already being used: '.$name);
}
$model = strtolower($model);
foreach ($this->_ci_model_paths as $mod_path)
{
if ( ! file_exists($mod_path.'models/'.$path.$model.'.php'))
{
continue;
}
if ($db_conn !== FALSE AND ! class_exists('CI_DB'))
{
if ($db_conn === TRUE)
{
$db_conn = '';
}
$CI->load->database($db_conn, FALSE, TRUE);
}
if ( ! class_exists('CI_Model'))
{
load_class('Model', 'core');
}
require_once($mod_path.'models/'.$path.$model.'.php');
$model = ucfirst($model);
$CI->$name = new $model();
$this->_ci_models[] = $name;
return;
}
// couldn't find the model
show_error('Unable to locate the model you have specified: '.$model);
}
This is my m_user.php class:
<?
class M_User extends CI_Model
{
function load($id)
{
$sql = "SELECT * FROM tv_user WHERE id = '{$id}' ";
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
$row = $query->row();
foreach ($row as $key => $val) {
$this->$key = $val;
}
return $row;
}
return null;
}
function getUser($info=NULL, $active=NULL)
{
$sql = "SELECT * FROM tv_user WHERE 1 = 1 ";
if (!is_null($info)) {
if (empty($info->username) || empty($info->password)) {
return null;
}
if (!empty($info->username)) {
$sql .= " AND (username = '{$info->username}' OR email = '{$info->username}' OR id = '{$info->username}') ";
}
if (!empty($info->password)) {
$sql .= " AND password = '".md5($info->password)."' ";
}
}
if (!empty($active)) {
$sql .= " AND active = '{$active}' ";
}
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
$row = $query->row();
foreach ($row as $key => $val) {
$this->$key = $val;
}
return $row;
}
return null;
}
function getUsers($active=NULL)
{
$sql = "SELECT * FROM tv_user WHERE 1 = 1";
if (!empty($active)) {
$sql .= " AND active = '{$active}'";
}
$query = $this->db->query($sql);
return $query->result();
}
function isUserExist($username=NULL, $active=NULL)
{
$sql = "SELECT * FROM tv_user WHERE 1 = 1 ";
if (!empty($username)) {
$sql .= " AND username = '{$username}' ";
}
if (!empty($active)) {
$sql .= " AND active = '{$active}' ";
}
$query = $this->db->query($sql);
return ($query->num_rows() > 0);
}
function getUserByEmail($email, $active=NULL)
{
if (empty($email)) {
return null;
}
$sql = "SELECT * FROM tv_user WHERE email = '{$email}' ";
if (!empty($active)) {
$sql .= " AND active = '{$active}' ";
}
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
$row = $query->row();
foreach ($row as $key => $val) {
$this->$key = $val;
}
return $row;
}
return null;
}
function getSocialUser($uid=NULL, $provider,$email=NULL, $active=NULL)
{
if (empty($provider)) {
return null;
}
$sql = "SELECT * FROM tv_user WHERE 1 = 1 ";
if (!empty($uid)) {
$sql .= " AND uid = '{$uid}' ";
}
if (!empty($email)) {
$sql .= " AND email = '{$email}' ";
}
$sql .= " AND provider='{$provider}'";
if (!empty($active)) {
$sql .= " AND active = '{$active}' ";
}
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
$row = $query->row();
foreach ($row as $key => $val) {
$this->$key = $val;
}
return $row;
}
return null;
}
function uuid()
{
return strtoupper(substr(dechex(time()).dechex(mt_rand(1,65535)), 0, 6));
}
function add($data)
{
return $this->db->insert("tv_user", $data);
}
function update($data, $where)
{
return $this->db->update("tv_user", $data, $where);
}
function delete($where)
{
return $this->db->delete("tv_user", $where);
}
function login($username, $password)
{
if (empty($username) || empty($password)) {
return FALSE;
}
$password = md5($password);
$sql = "SELECT * FROM tv_user WHERE username='{$username}' AND password='{$password}' AND active=1";
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
$user = $query->row();
$user_data = array();
foreach($user as $key => $val){
$user_data[$key] = $val;
}
$user_data["login"] = TRUE;
$this->session->set_userdata('user', $user_data);
if ($user->user_type == USR_ROOT) {
$this->session->set_userdata('root_addmin_logged_in', TRUE);
$this->session->set_userdata('addmin_logged_in', TRUE);
}
else if (in_array($user->user_type, array(USR_ADMIN,USR_MODERATOR,USR_TOUR,USR_HOTEL,USR_FLIGHT,USR_VISA))) {
$this->session->set_userdata('root_addmin_logged_in', FALSE);
$this->session->set_userdata('addmin_logged_in', TRUE);
}
else {
$this->session->set_userdata('root_addmin_logged_in', FALSE);
$this->session->set_userdata('addmin_logged_in', FALSE);
}
$this->session->set_userdata('logged_in', TRUE);
$this->session->set_userdata('logged_user', $user);
return TRUE;
}
return FALSE;
}
function logout()
{
$this->session->sess_destroy();
}
function verify_reset_password_code($email, $code)
{
if (empty($email) || empty($code)) {
return FALSE;
}
$sql = "SELECT * FROM tv_user WHERE email = '{$email}' ";
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
$row = $query->row();
return ($code == md5(SITE_NAME.$row->fullname))? TRUE : FALSE;
} else {
return FALSE;
}
}
}
?>
Set
short_open_tag=On
in php.ini
And restart your Apache server.
As per the comments:
Your first chunk of PHP is appearing in your HTML view - good idea to include a screenshot! That would indicate that it is not being parsed as PHP, and instead is being parse as HTML, so I would check to see if a <?php appears at the start.

My function is returning false when it should return true

My function is always returning false when it should return true, and I can't find why
public function isReselling($key)
{
if ($this->validateKey($key)) {
return false;
}
$apis = mysql_connect("mysql.hostinger.fr", "u770656121_uapi", "testpass") or die(mysql_error());
mysql_select_db("u770656121_api", $apis);
$sql = "
SELECT * FROM api_id
";
$result = mysql_query($sql, $apis);
while($row = mysql_fetch_array($result)) {
$blacklisttho = $row['Banned'];
if ($blacklisttho == 1) {
return true;
}
}
return false;
}
Well, you need to check where exactly the 'return' is beign made, and investigate based on that:
public function isReselling($key)
{
if ($this->validateKey($key)) {
die('validate fails');
return false;
}
$apis = mysql_connect("mysql.hostinger.fr", "u770656121_uapi", "testpass") or die(mysql_error());
mysql_select_db("u770656121_api", $apis);
$sql = "
SELECT * FROM api_id
";
$result = mysql_query($sql, $apis);
while($row = mysql_fetch_array($result)) {
$blacklisttho = $row['Banned'];
if ($blacklisttho == 1) {
return true;
}
}
die('no results.');
return false;
}
and btw, you don't want to have multiple 'returns' around the code, that's bad practice.
I would change your code to something like:
public function isReselling($key)
{
$retValue = false;
if ($this->validateKey($key) === false) {
$apis = mysql_connect("mysql.hostinger.fr", "u770656121_uapi", "testpass") or die(mysql_error());
mysql_select_db("u770656121_api", $apis);
$sql = "SELECT * FROM api_id";
$result = mysql_query($sql, $apis);
while($row = mysql_fetch_array($result)) {
if ($row['Banned'] == 1) {
$retValue = true;
break;
}
}
}
return $retValue;
}

Get row from SQL with PHP

I am using the following method to query from my SQL database:
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
$result = $result = query("SELECT * FROM users WHERE email='$email' limit 1");
$name = (what goes here?)
I am trying to get the string name from users, how can I do this?
If your query is right then
try this:
function query() {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
$result = query("SELECT * FROM users WHERE email='$email' limit 1");
$name = $result['result'][0]['name'];
You forgot to pass the value to the function
function query($sql) {
global $link;
$debug = false;
//get the sql query
$args = func_get_args();
$sql = array_shift($args);
//secure the input
for ($i=0;$i<count($args);$i++) {
$args[$i] = urldecode($args[$i]);
$args[$i] = mysqli_real_escape_string($link, $args[$i]);
}
//build the final query
$sql = vsprintf($sql, $args);
if ($debug) print $sql;
//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {
$rows = array();
if ($result!==true)
while ($d = mysqli_fetch_assoc($result)) {
array_push($rows,$d);
}
//return json
return array('result'=>$rows);
} else {
//error
return array('error'=>'Database error');
}
}
$result = $result = query("SELECT * FROM users WHERE email='$email' limit 1")
$name = "";
if(! isset($result["error"]) and isset($result["name"])) // check it returns error or not. then check name field exist or not.
{
$name = $result["name"];
}
echo $name;

Is converting mysql to mysqli extremely necessary?

Here's my deal:
I found a simple ACL, and have absolutely fallen in love with it. The problem? It's all in mysql, not mysqli. The rest of my site is written in mysqli, so this bothers me a ton.
My problem is that the ACL can easily connect without global variables because I already connected to the database, and mysql isn't object oriented.
1) Is it needed to convert to mysqli?
2) How can I easily convert it all?
Code:
<?
class ACL
{
var $perms = array(); //Array : Stores the permissions for the user
var $userID = 0; //Integer : Stores the ID of the current user
var $userRoles = array(); //Array : Stores the roles of the current user
function __constructor($userID = '')
{
if ($userID != '')
{
$this->userID = floatval($userID);
} else {
$this->userID = floatval($_SESSION['userID']);
}
$this->userRoles = $this->getUserRoles('ids');
$this->buildACL();
}
function ACL($userID = '')
{
$this->__constructor($userID);
//crutch for PHP4 setups
}
function buildACL()
{
//first, get the rules for the user's role
if (count($this->userRoles) > 0)
{
$this->perms = array_merge($this->perms,$this->getRolePerms($this->userRoles));
}
//then, get the individual user permissions
$this->perms = array_merge($this->perms,$this->getUserPerms($this->userID));
}
function getPermKeyFromID($permID)
{
$strSQL = "SELECT `permKey` FROM `permissions` WHERE `ID` = " . floatval($permID) . " LIMIT 1";
$data = mysql_query($strSQL);
$row = mysql_fetch_array($data);
return $row[0];
}
function getPermNameFromID($permID)
{
$strSQL = "SELECT `permName` FROM `permissions` WHERE `ID` = " . floatval($permID) . " LIMIT 1";
$data = mysql_query($strSQL);
$row = mysql_fetch_array($data);
return $row[0];
}
function getRoleNameFromID($roleID)
{
$strSQL = "SELECT `roleName` FROM `roles` WHERE `ID` = " . floatval($roleID) . " LIMIT 1";
$data = mysql_query($strSQL);
$row = mysql_fetch_array($data);
return $row[0];
}
function getUserRoles()
{
$strSQL = "SELECT * FROM `user_roles` WHERE `userID` = " . floatval($this->userID) . " ORDER BY `addDate` ASC";
$data = mysql_query($strSQL);
$resp = array();
while($row = mysql_fetch_array($data))
{
$resp[] = $row['roleID'];
}
return $resp;
}
function getAllRoles($format='ids')
{
$format = strtolower($format);
$strSQL = "SELECT * FROM `roles` ORDER BY `roleName` ASC";
$data = mysql_query($strSQL);
$resp = array();
while($row = mysql_fetch_array($data))
{
if ($format == 'full')
{
$resp[] = array("ID" => $row['ID'],"Name" => $row['roleName']);
} else {
$resp[] = $row['ID'];
}
}
return $resp;
}
function getAllPerms($format='ids')
{
$format = strtolower($format);
$strSQL = "SELECT * FROM `permissions` ORDER BY `permName` ASC";
$data = mysql_query($strSQL);
$resp = array();
while($row = mysql_fetch_assoc($data))
{
if ($format == 'full')
{
$resp[$row['permKey']] = array('ID' => $row['ID'], 'Name' => $row['permName'], 'Key' => $row['permKey']);
} else {
$resp[] = $row['ID'];
}
}
return $resp;
}
function getRolePerms($role)
{
if (is_array($role))
{
$roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` IN (" . implode(",",$role) . ") ORDER BY `ID` ASC";
} else {
$roleSQL = "SELECT * FROM `role_perms` WHERE `roleID` = " . floatval($role) . " ORDER BY `ID` ASC";
}
$data = mysql_query($roleSQL);
$perms = array();
while($row = mysql_fetch_assoc($data))
{
$pK = strtolower($this->getPermKeyFromID($row['permID']));
if ($pK == '') { continue; }
if ($row['value'] === '1') {
$hP = true;
} else {
$hP = false;
}
$perms[$pK] = array('perm' => $pK,'inheritted' => true,'value' => $hP,'Name' => $this->getPermNameFromID($row['permID']),'ID' => $row['permID']);
}
return $perms;
}
function getUserPerms($userID)
{
$strSQL = "SELECT * FROM `user_perms` WHERE `userID` = " . floatval($userID) . " ORDER BY `addDate` ASC";
$data = mysql_query($strSQL);
$perms = array();
while($row = mysql_fetch_assoc($data))
{
$pK = strtolower($this->getPermKeyFromID($row['permID']));
if ($pK == '') { continue; }
if ($row['value'] == '1') {
$hP = true;
} else {
$hP = false;
}
$perms[$pK] = array('perm' => $pK,'inheritted' => false,'value' => $hP,'Name' => $this->getPermNameFromID($row['permID']),'ID' => $row['permID']);
}
return $perms;
}
function userHasRole($roleID)
{
foreach($this->userRoles as $k => $v)
{
if (floatval($v) === floatval($roleID))
{
return true;
}
}
return false;
}
function hasPermission($permKey)
{
$permKey = strtolower($permKey);
if (array_key_exists($permKey,$this->perms))
{
if ($this->perms[$permKey]['value'] === '1' || $this->perms[$permKey]['value'] === true)
{
return true;
} else {
return false;
}
} else {
return false;
}
}
function getUsername($userID)
{
$strSQL = "SELECT `username` FROM `users` WHERE `ID` = " . floatval($userID) . " LIMIT 1";
$data = mysql_query($strSQL);
$row = mysql_fetch_array($data);
return $row[0];
}
}
?>
Just add a $mysqli property to this class and have the MySQLi object passed to it in constructor.
class ACL {
private $mysqli;
public function __construct(MySQLi $mysqli) {
$this->mysqli = $mysqli;
/* rest of your code */
}
}
The rest is pretty much search and replace.
The code is written to support PHP4. That tells me two things: firstly, the author couldn't use mysqli even if he wanted to, because PHP4 didn't have it, and secondly, the code is probably pretty old, and was written before the PHP devs started really trying to push developers to use mysqli instead of mysql.
If it's well written, then converting it to use mysqli instead should be a piece of cake. The API differences between mysql and mysqli at a basic level are actually pretty minimal. The main difference is the requirement to pass the connection object to the query functions. This was optional in mysql and frequently left out, as it seems to have been in this code.
So your main challenge is getting that connection object variable to be available wherever you make a mysqli function call. The easy way to do that is just to make it a property of the class, so it's available everywhere in the class.
I also recommend you drop the other php4 support bits; they're not needed, and they get in the way.

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