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.
Related
I've made a Search API with native PHP in the past, but I don't know how to make it in Codeigniter. The code below is not showing the data. Could someone point me in the right direction?
public function peta(){
$data = array();
// $query = "select * from tb_peta";
$cari = isset($_REQUEST['cari']) ? $_REQUEST['cari'] : '';
if ($cari != null) {
$result = $this->db->query("SELECT * FROM tb_peta WHERE nama LIKE "."'%".$cari."%'");
} else {
$result = $this->db->query( "SELECT * FROM tb_peta");
}
// $q = $this->db->query($query);
if ($q -> num_rows() >0) {
$data ['success'] = 1;
$data ['message'] = 'data ada';
$data ['data']=$q->result();
} else {
$data['result']='0';
$data['message'] ='kosong';
}
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$data[] = $row;
}
echo json_encode(array('planet' => $json_response));
}
Make use of codeigniter query builder.
public function peta(){
$data = array();
$cari = isset($_REQUEST['cari']) ? $_REQUEST['cari'] : '';
if ($cari != null) {
$this->db->like('name',$cari,'both');
$result = $this->db->get("tb_peta");
} else {
$result = $this->db->get("tb_peta");
}
if ($result->num_rows() >0) {
$data ['success'] = 1;
$data ['message'] = 'data ada';
$data ['data']=$result->result_array();
} else {
$data['result']='0';
$data['message'] ='kosong';
}
echo json_encode(array('planet' => $data));
}
I'm creating a web application that relies heavily upon getting data from MySQL using PHP. In ~50 functions I have very similar code requesting single data values from MySQL:
function get_profile_picture($whatmember) {
global $connection;
$whatmember = mysql_prep($whatmember);
$query = "SELECT picture_location FROM members WHERE member_id={$whatmember} LIMIT 1";
$returnval = mysqli_query($connection,$query);
if(!$returnval) {
return "Query failed: " . mysqli_error($connection);
}
if(mysqli_num_rows($returnval) > 0 ) {
$row = mysqli_fetch_assoc($returnval);
return $row["picture_location"];
}
return false;
}
So my question is this: is there a generic AND safe way to make the function so that I can just input "SELECT what-value FROM what-database.what-table WHERE what-criteria=what-value" that allows for arrays of results as well as single values? I made an attempt with the following, but it obviously is a hack and slash method that only gets single values:
function get_single_value($database_name,$column_name,$table_name,$criteria,$criteria_value) {
$database_name = mysql_prep($database_name);
$column_name = mysql_prep($column_name);
$table_name = mysql_prep($table_name);
$criteria = mysql_prep($criteria);
$criteria_value = mysql_prep($criteria_value);
if(!empty($column_name) && !empty($table_name) && !empty($criteria) && !empty($database_name)) {
global $connection;
global $gamesconnection;
global $locationconnection;
if($database_name=="connection") {
$database_connection = $connection;
} else if ($database_name=="games") {
$database_connection = $gamesconnection;
} else if ($database_name=="locations") {
$database_connection = $locationconnection;
} else {
die("Database connection doesn't exist for {$database_name}.");
}
$query = "SELECT {$column_name} FROM {$table_name} WHERE {$criteria}='{$criteria_value}' LIMIT 1";
$result = mysqli_query($database_connection,$query);
if(!$result) {
die("Unable to get {$column_name} from {$table_name}. Error: " . mysqli_error($database_connection) . " Query: " . $query);
}
if(mysqli_num_rows($result)>0) {
$row = mysqli_fetch_assoc($result);
return $row[$column_name];
}
}
return false;
}
And my get_profile_picture() function would then look more like this:
function get_profile_picture($whatmember) {
return get_single_value("connection","picture_location","members","member_id",$whatmember);
}
I'm still pretty new to PHP and MySQL so any pointers to improve my code would be great as well. Thanks in advance!
Alright I wrote my own. It might not have all the security of PDO, but I don't have the learn another framework in order to use it.
function get_from_database($database_variable) {
//PASS IN $database_variable WHICH IS AN OBJECT CONTAINING THE FOLLOWING POSSIBLE VALUES
$database_name = $database_variable["database_name"]; //DATABASE NAME
$column_name = $database_variable["column_name"]; //COLUMN(S) BEING REQUESTED
$table_name = $database_variable["table_name"]; //TABLE BEING SEARCHED
$criteria = $database_variable["criteria"]; // 'WHERE X'
$limit = $database_variable["limit"]; //ANY LIMITS, IF REQUIRED
$group_by = $database_variable["group_by"]; //ANY GROUPING, IF REQUIRED
$order_by = $database_variable["order_by"]; //ANY SORT ORDERING, IF REQUIRED
if(!empty($column_name) && !empty($table_name)&& !empty($database_name)) {
global $connection;
global $gamesconnection;
global $locationconnection;
global $olddataconnection;
if($database_name=="connection") {
$database_connection = $connection;
} else if ($database_name=="games") {
$database_connection = $gamesconnection;
} else if ($database_name=="locations") {
$database_connection = $locationconnection;
} else if ($database_name=="olddata") {
$database_connection = $olddataconnection;
} else {
error_log("\nDatabase connection doesn't exist for {$database_name}." . get_backtrace_info());
return false;
}
if(is_null($limit)) {
//IF LIMIT NOT SUPPLIED, MAKE LIMIT 0, IE NO LIMIT
$limit = 0;
}
if(is_int($limit)==false) {
//NOT AN INTEGER
error_log("\nError in limit provided: " . $limit . get_backtrace_info());
return false;
}
$query = " SELECT {$column_name}
FROM {$table_name} " . (!empty($criteria) /*CHECK IF CRITERIA WAS REQUIRED*/ ? "
WHERE {$criteria} " : "") . (!empty($group_by) /*CHECK IF GROUP BY WAS REQUIRED*/ ? "
GROUP BY {$group_by} " : "") . (!empty($order_by) /*CHECK IF ORDER BY WAS REQUIRED*/ ? "
ORDER BY {$order_by} " : "") . ($limit!==0 /*CHECK IF LIMIT WAS REQUIRED*/ ? "
LIMIT {$limit} " : "");
$result = mysqli_query($database_connection,$query);
if(!$result) {
error_log("\nUnable to process query, got error: " . mysqli_error($database_connection) . "\nQuery: " . $query . get_backtrace_info());
return false;
}
if(mysqli_num_rows($result)>0) {
//RESULT SUPPLIED
$row_array = array();
while($row = mysqli_fetch_assoc($result)) {
$row_array[] = $row;
}
mysqli_free_result($result);
return $row_array;
}
}
return false;
}
Function to trace function call back to source:
function get_backtrace_info(){
//GET INFORMATION ON WHICH FUNCTION CAUSED ERROR
$backtrace = debug_backtrace();
$backtrace_string = "";
for($i=0;$i<count($backtrace);$i++) {
$backtrace_string .= '\n';
if($i==0) {
$backtrace_string .= 'Called by ';
} else {
$backtrace_string .= 'Which was called by ';
}
$backtrace_string .= "{$backtrace[$i]['function']} on line {$backtrace[$i]['line']}";
}
return backtrace_string;
}
Now I can request data from MySQL as follows:
Single value requested:
function get_profile_picture($whatmember) {
$linked_member_code = get_linked_member_code($whatmember);
return get_from_database([ "database_name" => "connection",
"column_name" => "picture_location",
"table_name" => "members",
"criteria" => "linked_member_code='{$linked_member_code}' AND team_id=0",
"limit" => 1
])[0]["picture_location"];
}
2 values requested:
function get_city_and_region_by_id($whatid) {
$row = get_from_database([ "database_name" => "locations",
"column_name" => "city, region",
"table_name" => "cities",
"criteria" => "row_id={$whatid}",
"limit" => 1
]);
return $row[0]["city"] . ", " . $row[0]["region"];
}
Unknown number of rows:
function get_linked_teams($linkedmembercode) {
return get_from_database([ "database_name" => "connection",
"column_name" => "team_id",
"table_name" => "members",
"criteria" => "linked_member_code='{$linkedmembercode}' AND team_id!=0"
]);
}
Can someone tell me how to return the number of results if I use this function to grab data from the database? I have tried including this:
$this->number = $result->num_rows;
But that didn't do the trick. Also, if anyone can give me some advice to do the below code in a better way, that would be helpful too.
<?php
public function grabResults($table, $values = '*', $where = NULL, $field1 = NULL, $and = NULL, $field2 = NULL, $order = NULL)
{
$result = 'SELECT '.$values.' FROM '.$table;
if($where != NULL)
{
$result = 'SELECT '.$values.' FROM '.$table.' WHERE '.$field1.' = '.$where;
}
if($and != NULL)
{
$result = 'SELECT '.$values.' FROM '.$table.' WHERE '.$field1.' = '.$where.' AND '.$field2.' = '.$and;
}
if($order != NULL)
{
$result = 'SELECT '.$values.' FROM '.$table.' WHERE '.$field1.' = '.$where.' ORDER BY '.$order.' ASC';
}
$query = $this->data->mysqli->query($result);
if($query)
{
while($row = $query->fetch_assoc())
{
$rows[] = $row;
}
return $rows;
}
else {
return false;
}
}
?>
$result->num_rows;
sounds like a Codeigniter function that you tried to use in raw php.
Have you tried to count() the query?
$count=count($query);
I am passing a number of values to a function and then want to create a SQL query to search for these values in a database.
The input for this is drop down boxes which means that the input could be ALL or * which I want to create as a wildcard.
The problem is that you cannot do:
$result = mysql_query("SELECT * FROM table WHERE something1='$something1' AND something2='*'") or die(mysql_error());
I have made a start but cannot figure out the logic loop to make it work. This is what I have so far:
public function search($something1, $something2, $something3, $something4, $something5) {
//create query
$query = "SELECT * FROM users";
if ($something1== null and $something2== null and $something3== null and $something4== null and $something5== null) {
//search all users
break
} else {
//append where
$query = $query . " WHERE ";
if ($something1!= null) {
$query = $query . "something1='$something1'"
}
if ($something2!= null) {
$query = $query . "something2='$something2'"
}
if ($something3!= null) {
$query = $query . "something3='$something3'"
}
if ($something4!= null) {
$query = $query . "something4='$something4'"
}
if ($something5!= null) {
$query = $query . "something5='$something5'"
}
$uuid = uniqid('', true);
$result = mysql_query($query) or die(mysql_error());
}
The problem with this is that it only works in sequence. If someone enters for example something3 first then it wont add the AND in the correct place.
Any help greatly appreciated.
I would do something like this
criteria = null
if ($something1!= null) {
if($criteria != null)
{
$criteria = $criteria . " AND something1='$something1'"
}
else
{
$criteria = $criteria . " something1='$something1'"
}
}
... other criteria
$query = $query . $criteria
try with array.
function search($somethings){
$query = "SELECT * FROM users";
$filters = '';
if(is_array($somethings)){
$i = 0;
foreach($somethings as $key => $value){
$filters .= ($i > 0) ? " AND $key = '$value' " : " $key = '$value'";
$i++;
}
}
$uuid = uniqid('', true);
$query .= $filters;
$result = mysql_query($query) or die(mysql_error());
}
// demo
$som = array(
"something1" => "value1",
"something2" => "value2"
);
search( $som );
Here's an example of dynamically building a WHERE clause. I'm also showing using PDO and query parameters. You should stop using the deprecated mysql API and start using PDO.
public function search($something1, $something2, $something3, $something4, $something5)
{
$terms = array();
$values = array();
if (isset($something1)) {
$terms[] = "something1 = ?";
$values[] = $something1;
}
if (isset($something2)) {
$terms[] = "something2 = ?";
$values[] = $something2;
}
if (isset($something3)) {
$terms[] = "something3 = ?";
$values[] = $something3;
}
if (isset($something4)) {
$terms[] = "something4 = ?";
$values[] = $something4;
}
if (isset($something5)) {
$terms[] = "something5 = ?";
$values[] = $something5;
}
$query = "SELECT * FROM users ";
if ($terms) {
$query .= " WHERE " . join(" AND ", $terms);
}
if (defined('DEBUG') && DEBUG==1) {
print $query . "\n";
print_r($values);
exit();
}
$stmt = $pdo->prepare($query);
if ($stmt === false) { die(print_r($pdo->errorInfo(), true)); }
$status = $stmt->execute($values);
if ($status === false) { die(print_r($stmt->errorInfo(), true)); }
}
I've tested the above and it works. If I pass any non-null value for any of the five function arguments, it creates a WHERE clause for only the terms that are non-null.
Test with:
define('DEBUG', 1);
search('one', 'two', null, null, 'five');
Output of this test is:
SELECT * FROM users WHERE something1 = ? AND something2 = ? AND something5 = ?
Array
(
[0] => one
[1] => two
[2] => five
)
If you need this to be more dynamic, pass an array to the function instead of individual arguments.
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.