I am fairly new to PHP slim but it's working great for me actually. But I have a problem that I think is really strange! I have a PHP file with all my API functions to get or edit data in my database. Each of these functions works great seperatly but when I uncomment them all and they are all active I get a 404 error when I want to use them or when I surf directly to them in my browser.
Here you can see all the functions I want to use:
//PHPSLIM
require '.././libs/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$categories = new \Slim\Slim();
$categories = \Slim\Slim::getInstance();
$categories->get('/categories', function(){
global $conn, $servername, $username, $password, $dbname;
mysql_connect($servername, $username, $password);
mysql_select_db($dbname);
$result = mysql_query("SELECT `categoryID`, `categoryName` FROM `category`");
while($line = mysql_fetch_array($result, MYSQL_NUM)) {
$cat[] = $line;
}
echoResponseCat(200, $cat);
});
function echoResponseCat($status_code, $response) {
global $categories;
$categories->status($status_code);
header('Content-Type: application/json');
$categories->contentType('application/json');
echo json_encode($response,JSON_NUMERIC_CHECK);
}
$categories->run();
//ALTER ORDER STATUS
$status = new \Slim\Slim();
$status = \Slim\Slim::getInstance();
$status->get('/orderPrepared/:orderID', function ($orderID) {
global $conn, $servername, $username, $password, $dbname;
if(isset($orderID)){
$sql = "UPDATE `order` SET `orderStatus`= 'done' WHERE `orderID` = '$orderID'";
mysql_connect($servername, $username, $password);
mysql_select_db($dbname);
$result = $conn->query($sql);
}
});
$status->run();
$app = new \Slim\Slim();
$app = \Slim\Slim::getInstance();
//GET ALL ORDERS
$app->get('/orders', function(){
$extranames = "";
$extrasprice = 0;
global $conn, $servername, $username, $password, $dbname;
$sql = "SELECT `orderID`, `customerID`, `storeID`, `orderDate`, `orderDeliveryDate`, `orderStatus` FROM `order`";
mysql_connect($servername, $username, $password);
mysql_select_db($dbname);
$query = mysql_query("SELECT `orderID`, `customerID`, `orderDate`, `orderDeliveryDate`, `orderStatus` FROM `order`");
$ordersall = array();
while($line = mysql_fetch_array($query, MYSQL_ASSOC)){
$orders[] = $line;
}
$count = 0;
$extrasprice = 0;
$ordersall = array();
$orderKeys = array('orderID', 'customerID', 'customerName', 'orderDate', 'orderDeliveryDate', 'orderStatus');
$orderKeys = array_combine($orderKeys, $orderKeys);
foreach($orders as $key => $looporders){
$extracounter = 1;
$sql = "SELECT `orderdetailID`, `productID`, `orderdetailAantal` FROM `orderdetail` WHERE `orderID` = '$looporders[orderID]'";
$result = $conn->query($sql);
//echo("orderID " . $looporders["orderID"] . " " . $result->num_rows ."/");
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$sql2 = "SELECT `productTitle`, `productPrijs` FROM `products` WHERE `productID` = '$row[productID]'";
$result2 = $conn->query($sql2);
if($result2->num_rows > 0) {
while($row2 = $result2->fetch_assoc()){
$productTitle = $row2["productTitle"];
$productPrijs = $row2["productPrijs"];
}
}
$sql3 = "SELECT `customerName` FROM `customers` WHERE `customerID` = '$looporders[customerID]'";
$result3 = $conn->query($sql3);
if($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()){
$customerName = $row3["customerName"];
}
}
$sql4 = "SELECT `extraID` FROM `orderdetailextra` WHERE `orderdetailID` = '$row[orderdetailID]'";
$result4 = $conn->query($sql4);
if ($result4->num_rows > 0) {
while($row4 = $result4->fetch_assoc()) {
$sql5 = "SELECT `extraName`, `extraPrice` FROM `extra` WHERE `extraID` = '$row4[extraID]'";
$result5 = $conn->query($sql5);
if ($result5->num_rows > 0) {
while($row5 = $result5->fetch_assoc()) {
$extranames = $extranames . $row5["extraName"]. ', ';
$extrasprice += $row5["extraPrice"];
}
}
}
}
$orderID = $looporders["orderID"];
if(!isset($ordersall[$orderID])){
$ordersall[$orderID] = array_intersect_key($looporders,$orderKeys);
$ordersall[$orderID]["customerName"] = $customerName;
$ordersall[$orderID]['details'] = array();
$newdata = array(
"orderdetailID" => $row["orderdetailID"],
"productTitle" => $productTitle,
"productPrijs" => $productPrijs,
"aantal" => $row["orderdetailAantal"],
"extras" => substr($extranames, 0, -2),
"extrasPrice" => $extrasprice
);
array_push($ordersall[$orderID]['details'], $newdata);
}
else if(isset($ordersall[$orderID])){
$newdata = array(
"orderdetailID" => $row["orderdetailID"],
"productTitle" => $productTitle,
"productPrijs" => $productPrijs,
"aantal" => $row["orderdetailAantal"],
"extras" => substr($extranames, 0, -2),
"extrasPrice" => $extrasprice
);
array_push($ordersall[$orderID]['details'], $newdata);
}
$count++;
$extranames ="";
$extrasprice = 0;
}
}
}
echoResponse(200, $ordersall);
});
$app->run();
//GET ALL ORDERS FOR 1 CUSTOMER
$app->get('/orderoverview/:customerID', function ($customerID) {
global $conn, $servername, $username, $password, $dbname;
//1.1 GET ORDER (ID) AND NAME OF CUSTOMER
$sql = "SELECT `customerName` FROM `customers` WHERE `customerID` = $customerID";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$customername = $row["customerName"];
}
}
else {
echo "Customer name failure";
}
$sql = "SELECT `orderID` FROM `order` WHERE `customerID` = $customerID";
$result = $conn->query($sql);
if($result->num_rows > 1){
echo "You already have a pending order! <br>";
}
else if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$orderID = $row["orderID"];
}
step2($orderID, $customername);
} else {
echo "GET orderID failure";
}
});
$app->run();
Can someone tell me what I'm doing wrong?
You are calling run after each controller. But you only need to do this once. For your whole application
$app = new \Slim\Slim();
$app->get('/orderPrepared/:orderID', function ($orderID) {
});
.. assign all your controllers ..
$app->run();
Related
Firstly I got the workers name from BIRTHDAYS and then want to get e-mail address from USERS.There is no problem to take workers name's from Table1 but when I try to get the e-mail addresses the db returns me NULL.My DB is mssql.
<?php
include_once("connect.php");
$today = '05.07';
$today1 = $today . "%";
$sql = "SELECT NAME FROM BIRTHDAYS WHERE BIRTH LIKE '$today1' ";
$stmt = sqlsrv_query($conn,$sql);
if($stmt == false){
echo "failed";
}else{
$dizi = array();
while($rows = sqlsrv_fetch_array($stmt,SQLSRV_FETCH_ASSOC))
{
$dizi[] = array('NAME' =>$rows['NAME']);
$newarray = json_encode($dizi,JSON_UNESCAPED_UNICODE);
}
}
foreach(json_decode($newarray) as $nameObj)
{
$nameArr = (array) $nameObj;
$names = reset($nameArr);
mb_convert_case($names, MB_CASE_UPPER, 'UTF-8');
echo $sql2 = "SELECT EMAIL FROM USERS WHERE NAME = '$names' ";
echo "<br>";
$stmt2 = sqlsrv_query($conn,$sql2);
if($stmt2 == false)
{
echo "failed";
}
else
{
$dizi2 = array();
while($rows1 = sqlsrv_fetch_array($stmt2,SQLSRV_FETCH_ASSOC))
{
$dizi1[] = array('EMAIL' =>$rows['EMAIL']);
echo $newarray1 = json_encode($dizi1,JSON_UNESCAPED_UNICODE);
}
}
}
?>
while($rows1 = sqlsrv_fetch_array($stmt2,SQLSRV_FETCH_ASSOC))
{
$dizi1[] = array('EMAIL' =>$rows['EMAIL']);
echo $newarray1 = json_encode($dizi1,JSON_UNESCAPED_UNICODE);
}
you put in $rows1 and would take it from $rows NULL is correct answer :)
take $rows1['EMAIL'] and it would work
and why foreach =?
you can put the statement in while-loop like this:
while ($rows = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$names = $rows['NAME'];
$sql2 = "SELECT EMAIL FROM USERS WHERE NAME = '$names' ";
echo "<br>";
$stmt2 = sqlsrv_query($conn, $sql2);
if ($stmt2 == false) {
echo "failed";
} else {
$dizi2 = array();
while ($rows1 = sqlsrv_fetch_array($stmt2, SQLSRV_FETCH_ASSOC)) {
$dizi1[] = array('EMAIL' => $rows1['EMAIL']);
echo $newarray1 = json_encode($dizi1, JSON_UNESCAPED_UNICODE);
}
}
}
This is the code that is not working:
$query = "SELECT * FROM $table WHERE text_id > '$last_id'"; //SELECT NEW MESSAGES
$result = mysqli_query($connection,$query);
if ($result && mysqli_num_rows($result) > 0)
{
//THIS SHOULD NOT BE RUNNING
}
I've verified over and over in phpMyAdmin and the text_id in the table and $last_id are both the integer value '1'. That being said, the condition equates to true every time the code runs.
Am I messing this code up, or is my thinking improper?
Here is entire script:
<?php
session_start();
$alias = $_SESSION['username'];
$host = 'localhost';
$user = '*';
$pass = '*';
$database = 'vethergen_db_accounts';
$table = 'table_messages';
$last_id_table = 'table_chat_sync';
$connection = mysqli_connect($host, $user, $pass) or die ("Unable to connect!");
mysqli_select_db($connection,$database) or die ("Unable to select database!");
$last_id_query = "SELECT alias FROM $last_id_table WHERE alias = '$alias'";
$last_id_result = mysqli_query($connection,$last_id_query);
$last_id_rows = mysqli_fetch_array($last_id_result);
if ($last_id_rows['alias'] === $alias)
{
$last_id = $last_id_rows['last_id'];
$query = "SELECT * FROM $table WHERE text_id > '$last_id'"; //SELECT NEW MESSAGES
$result = mysqli_query($connection,$query);
if ($result && mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
if ($row['alias'] === "Vether")
{
echo '<p id = "chat_text">'.'<b>'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
else
{
echo '<p id = "chat_text">'.'<b class = "bold_green">'.$row['alias'].'</b>'.': '.$row['text']."</p>";
echo '<p id = "time_stamp">'.$row['time'].'</p>';
echo '<p id = "chat_number">'.$row['text_id'].'</p>';
}
echo '<hr class = "chat_line"></hr>';
$last_row_id = $row['text_id'];
}
}
//UPDATE LAST SYNC ID
$update_query = "UPDATE $last_id_table SET last_id = '$last_row_id' WHERE alias = '$alias'";
mysqli_query($connection,$update_query);
}
else
{
$update_query = "INSERT INTO $last_id_table (alias, last_id) VALUES('$alias','-1')";
mysqli_query($connection,$update_query);
}
?>
You should change ;
WHERE text_id > '$last_id'
to
WHERE text_id > $last_id
text_id column is integer and can't be compared like string.
I am trying to create a JSON object as an array from the data received from the SQL Query. Currently the encoded JSON I have got is:
[{"firstname":"Student","lastname":"1"},{"firstname":"Student","lastname":"2"},{"firstname":"Student","lastname":"3"}]
The values I want to insert from another array, the values are in corresponding order to the each array in the JSON above: (JSON)
["85.00000","50.00000","90.00000"]
So the JSON should look like:
{"firstname":"Student","lastname":"1","grade":"85.00000"}
My Current Code:
//Provisional Array Setup for Grades
$grade = array();
$userid = array();
$sqldata = array();
foreach($json_d->assignments[0]->grades as $gradeInfo) {
$grade[] = $gradeInfo->grade;
$userid[] = $gradeInfo->userid;
}
//Server Details
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "moodle";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
foreach($userid as $id) {
$sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$sqldata[] = $row;
}
} else {
echo "ERROR!";
}
}
$sqlr = json_encode($sqldata);
$grd = json_encode($grade);
echo $sqlr;
echo $grd;
mysqli_close($conn);
try this code:
foreach($userid as $x => $id) {
$sql = "SELECT firstname, lastname FROM mdl_user WHERE id='$id'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$row['grade'] = $grade[$x];
$sqldata[] = $row;
}
} else {
echo "ERROR!";
}
}
I added the Variable $x and added $row['grade'] with the same index on the $gradearray
function set_column_values($arr, $column_name, $column_values) {
$ret_arr = array_map(function($arr_value, $col_value) use ($column_name) {
$arr_value[$column_name] = $col_value;
return $arr_value;
}, $arr, $column_values);
return $ret_arr;
}
$sqldata = set_column_values($sqldata, 'grades', $grade);
$sqlr = json_encode($sqldata);
var_dump($sqlr);
Hope it helps!
I tried to create a class to consolidate the following functions but I don't fully understand the approach, how would I approach the following functions to remove the need to query the DB on each occasion an just call the separate echo blocks?
function get_pages_new() {
$cxn = mysqli_connect('localhost', 'root', '', 'northern') or die(mysqli_error($cxn));
$query = ("SELECT * FROM `pages` ORDER BY `page_id` ASC") or die(mysqli_error($cxn));
$getnews = mysqli_query($cxn, $query);
while ($row = mysqli_fetch_assoc($getnews)) {
$page_id = $row['page_id'];
$page_title = $row['page_title'];
$admin = $row['admin_only'];
echo "<li>$page_title</li>";
}
};
function get_pages_edit() {
$cxn = mysqli_connect('localhost', 'root', '', 'northern') or die(mysqli_error($cxn));
$query = ("SELECT * FROM `pages` ORDER BY `page_id` ASC") or die(mysqli_error($cxn));
$getnews = mysqli_query($cxn, $query);
while ($row = mysqli_fetch_assoc($getnews)) {
$page_id = $row['page_id'];
$page_title = $row['page_title'];
$admin = $row['admin_only'];
echo "<li>$page_title</li> ";
}
};
function get_pages_delete() {
$cxn = mysqli_connect('localhost', 'root', '', 'northern') or die(mysqli_error($cxn));
$query = ("SELECT * FROM `pages` ORDER BY `page_id` ASC") or die(mysqli_error($cxn));
$getnews = mysqli_query($cxn, $query);
while ($row = mysqli_fetch_assoc($getnews)) {
$page_id = $row['page_id'];
$page_title = $row['page_title'];
$admin = $row['admin_only'];
echo "<li>$page_title</li>";
}
};
Thanks
Pass in a parameter that contains the link:
function get_pages($link) {
$cxn = mysqli_connect('localhost', 'root', '', 'northern') or die(mysqli_error($cxn));
$query = ("SELECT * FROM `pages` ORDER BY `page_id` ASC") or die(mysqli_error($cxn));
$getnews = mysqli_query($cxn, $query);
while ($row = mysqli_fetch_assoc($getnews)) {
$page_id = $row['page_id'];
$page_title = $row['page_title'];
$admin = $row['admin_only'];
echo "<li><a href='".$link."?page_id=".$page_id."'>".$page_title."</li></a>";
}
};
Where $link is add_page.php, edit_page.php or remove_page.php. Unless I've misread your code and each function is running a seperate query, this should work :)
$Create a method for that instead of a class:
function extractIdTitleAdminFromEntry($entry) {
return [
'page_id' => $entry['page_id'],
'page_title' => $entry['page_title'],
'admin_only' => $entry['admin_only'],
];
}
Now you can do this inside your while loops:
list($page_id, $page_title, $admin_only) = extractIdTitleAdminFromEntry($row);
You can even modify it such that the list of properties is dynamic:
function extractIdTitleAdminFromEntry($entry, $properties) {
$values = [$key];
foreach ($properties as $key) {
$values[$key] = isset($entry[$key] ? $entry[$key] : null;
}
return $values;
}
list($page_id, $page_title, $admin_only) = extractIdTitleAdminFromEntry(
$row,
['page_id', 'page_title', 'admin_only']
);
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.