Related
Following code:
function personInfo($person)
{
$zipCode="12345";
if($zipCode!=54321)
{
$zipCode="12345";
$postal="World";
if($zipCode AND $postal < 1)
{
return "Wrong";
}
//Test stops here and do not continue???
}
$person->firstname="Mike";
$person->lastname="Wayne";
$person->address="Universe";
$person->zipCode="12345";
$person->mobile="123456789784512";
$person->password="GogoGO";
$person->socialSecurityNumber="1234567891234567";
return "OK";
}
I am not sure why it stops there since I want to test the code when it fails and when it's OK. I'm still learning so I would be much appreciated for all help!
Rest of the code (database & test) that connects to "function personInfo($person)":
function personInfo($person)
{
$this->db->autocommit(false);
$sql = "Select * from Postal Where ZipCode = '$person->zipCode'";
$result = $this->db->query($sql);
if($this->db->affected_rows!=1)
{
$sql = "Insert Into Postal (ZipCode, Postal) Values ('$person->zipCode','$person->postal')";
$result = $this->db->query($sql);
if($this->db->affected_rows < 1)
{
$this->db->rollback();
return "Wrong";
}
}
$sql .= "Update Person Set Firstname = '$person->firstname', Lastname = '$person->lastname',";
$sql .= " Address = '$person->address', ZipCode = '$person->zipCode',";
$sql .= " Mobile = '$person->mobile', Password ='$person->password'";
$sql .= " Where SocialSecurityNumber = '$person->socialSecurityNumber'";
$result = $this->db->query($sql);
$this->db->commit();
return "OK";
}
class personInfoTest extends PHPUnit_Framework_TestCase {
public function testPersonInfoWrong()
{
//arrange
$zipCode="1234";
$person=$zipCode;
$record=new Record(new DBStub());
// act
$result= $record->personInfo($person);
//assert
$this->assertEquals("Wrong",$result);
}
public function testPersonInfoOK()
{
//arrange
$zipCode="1234";
$person=$zipCode;
$record=new Record(new DBStub());
// act
$result= $record->personInfo($person);
// assert
$this->assertEquals("OK",$result);
$this->assertEquals("1234567891234567",$result->socialSecurityNumber);
$this->assertEquals("Mike",$result->firstname);
$this->assertEquals("Wayne",$result->lastname);
$this->assertEquals("Universe",$result->address);
$this->assertEquals("1234567812345",$result->telefonnr);
$this->assertEquals("GogoGO",$result->password);
$this->assertEquals("12345",$result->zipCode);
$this->assertEquals("World",$result->poststed);
}
}
Guys i want different "select" operation as per my needs, but i just need one helper function for all select operation , How do i get it??
This is my helper class Database.php
<?php
class Database
{
public $server = "localhost";
public $user = "root";
public $password = "";
public $database_name = "employee_application";
public $table_name = "";
public $database_connection = "";
public $class_name = "Database";
public $function_name = "";
//constructor
public function __construct(){
//establishes connection to database
$this->database_connection = new mysqli($this->server, $this->user, $this->password, $this->database_name);
if($this->database_connection->connect_error)
die ("Connection failed".$this->database_connection->connect_error);
}
//destructor
public function __destruct(){
//closes database connection
if(mysqli_close($this->database_connection))
{
$this->database_connection = null;
}
else
echo "couldn't close";
}
public function run_query($sql_query)
{
$this->function_name = "run_query";
try{
if($this->database_connection){
$output = $this->database_connection->query($sql_query);
if($output){
$result["status"] = 1;
$result["array"] = $output;
}
else{
$result["status"] = 0;
$result["message"] = "Syntax error in query";
}
}
else{
throw new Exception ("Database connection error");
}
}
catch (Exception $error){
$result["status"] = 0;
$result["message"] = $error->getMessage();
$this->error_table($this->class_name, $this->function_name, "connection error", date('Y-m-d H:i:s'));
}
return $result;
}
public function get_table($start_from, $per_page){
$this->function_name = "get_table";
$sql_query = "select * from $this->table_name LIMIT $start_from, $per_page";
return $this->run_query($sql_query);
}
}
?>
In the above code get_table function performs basic select operation....
Now i want get_table function to perform all this below operations,
$sql_query = "select e.id, e.employee_name, e.salary, dept.department_name, desi.designation_name, e.department, e.designation
from employees e
LEFT OUTER JOIN designations desi ON e.designation = desi.id
LEFT OUTER JOIN departments dept ON e.department = dept.id
ORDER BY e.employee_name
LIMIT $start_from, $per_page";
$sql_query = "select id, designation_name from designations ORDER BY designation_name";
$sql_query = "select * from departments";
$sql_query = "select * from departments Limit 15,10";
So how to overcome this issue, can anyone help me out?
If you expand your class a bit, you could achieve what you are looking for. Something like this:
<?php
class Database
{
public $sql;
public $bind;
public $statement;
public $table_name;
protected $orderby;
protected $set_limit;
protected $function_name;
protected $sql_where;
protected $i;
protected function reset_class()
{
// reset variables
$this->sql = array();
$this->function_name = false;
$this->table_name = false;
$this->statement = false;
$this->sql_where = false;
$this->bind = array();
$this->orderby = false;
$this->set_limit = false;
}
protected function run_query($statement)
{
echo (isset($statement) && !empty($statement))? $statement:"";
}
public function get_table($start_from = false, $per_page = false)
{
// Compile the sql into a statement
$this->execute();
// Set the function if not already set
$this->function_name = (!isset($this->function_name) || isset($this->function_name) && $this->function_name == false)? "get_table":$this->function_name;
// Set the statement
$this->statement = (!isset($this->statement) || isset($this->statement) && $this->statement == false)? "select * from ".$this->table_name:$this->statement;
// Add on limiting
if($start_from != false && $per_page != false) {
if(is_numeric($start_from) && is_numeric($per_page))
$this->statement .= " LIMIT $start_from, $per_page";
}
// Run your query
$this->run_query($this->statement);
// Reset the variables
$this->reset_class();
return $this;
}
public function select($value = false)
{
$this->sql[] = "select";
$this->function_name = "get_table";
if($value != false) {
$this->sql[] = (!is_array($value))? $value:implode(",",$value);
}
else
$this->sql[] = "*";
return $this;
}
public function from($value = false)
{
$this->sql[] = "from";
$this->sql[] = "$value";
return $this;
}
public function where($values = array(), $not = false, $group = false,$operand = 'and')
{
if(empty($values))
return $this;
$this->sql_where = array();
if(isset($this->sql) && !in_array('where',$this->sql))
$this->sql[] = 'where';
$equals = ($not == false || $not == 0)? "=":"!=";
if(is_array($values) && !empty($values)) {
if(!isset($this->i))
$this->i = 0;
foreach($values as $key => $value) {
$key = trim($key,":");
if(isset($this->bind[":".$key])) {
$auto = str_replace(".","_",$key).$this->i;
// $preop = $operand." ";
}
else {
// $preop = "";
$auto = str_replace(".","_",$key);
}
$this->bind[":".$auto] = $value;
$this->sql_where[] = $key." $equals ".":".$auto;
$this->i++;
}
if($group == false || $group == 0)
$this->sql[] = implode(" $operand ",$this->sql_where);
else
$this->sql[] = "(".implode(" $operand ",$this->sql_where).")";
}
else {
$this->sql[] = $values;
}
if(is_array($this->bind))
asort($this->bind);
return $this;
}
public function limit($value = false,$offset = false)
{
$this->set_limit = "";
if(is_numeric($value)) {
$this->set_limit = $value;
if(is_numeric($offset))
$this->set_limit = $offset.", ".$this->set_limit;
}
return $this;
}
public function order_by($column = array())
{
if(is_array($column) && !empty($column)) {
foreach($column as $colname => $orderby) {
$array[] = $colname." ".str_replace(array("'",'"',"+",";"),"",$orderby);
}
}
else
$array[] = $column;
$this->orderby = implode(", ",$array);
return $this;
}
public function execute()
{
$limit = (isset($this->set_limit) && !empty($this->set_limit))? " LIMIT ".$this->set_limit:"";
$order = (isset($this->orderby) && !empty($this->orderby))? " ORDER BY ".$this->orderby:"";
$this->statement = (is_array($this->sql))? implode(" ", $this->sql).$order.$limit:"";
return $this;
}
public function use_table($table_name = 'employees')
{
$this->table_name = $table_name;
return $this;
}
}
To use:
// Create instance
$query = new Database();
// Big query
$query ->select(array("e.id", "e.employee_name", "e.salary", "dept.department_name", "desi.designation_name", "e.department", "e.designation"))
->from("employees e LEFT OUTER JOIN designations desi ON e.designation = desi.id LEFT OUTER JOIN departments dept ON e.department = dept.id")
->order_by(array("e.employee_name"=>""))
->limit(1,5)->get_table();
// More advanced select
$query ->select(array("id", "designation_name"))
->from("designations")
->order_by(array("designation_name"=>""))
->get_table();
// Simple select
$query ->use_table("departments")
->get_table();
// Simple select with limits
$query ->use_table("departments")
->get_table(10,15);
?>
Gives you:
// Big query
select e.id,e.employee_name,e.salary,dept.department_name,desi.designation_name,e.department,e.designation from employees e LEFT OUTER JOIN designations desi ON e.designation = desi.id LEFT OUTER JOIN departments dept ON e.department = dept.id ORDER BY e.employee_name LIMIT 5, 1
// More advanced select
select id,designation_name from designations ORDER BY designation_name
// Simple select
select * from departments
// Simple select with limits
select * from departments LIMIT 10, 15
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.
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.
I am trying to build a site with news links that can be voted, I have the following code:
case 'vote':
require_once('auth/auth.php');
if(Auth::isUserLoggedIn())
{
require_once('data/article.php');
require_once('includes/helpers.php');
$id = isset($_GET['param'])? $_GET['param'] : 0;
if($id > 0)
{
$article = Article::getById($id);
$article->vote();
$article->calculateRanking();
}
if(!isset($_SESSION)) session_start();
redirectTo($_SESSION['action'], $_SESSION['param']);
}
else
{
Auth::redirectToLogin();
}
break;
The problem right now is how to check so the same user does not vote twice, here is the article file:
<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/config.php');
require_once(SITE_ROOT.'includes/exceptions.php');
require_once(SITE_ROOT.'data/model.php');
require_once(SITE_ROOT.'data/comment.php');
class Article extends Model
{
private $id;
private $user_id;
private $url;
private $title;
private $description;
private $ranking;
private $points;
function __construct($title = ' ', $description = ' ', $url = ' ', $username = ' ', $created = ' ', $modified = '') {
$this->setId(0);
$this->setCreated($created);
$this->setModified($modified);
$this->setUsername($username);
$this->setUrl($url);
$this->setTitle($title);
$this->setDescription($description);
$this->setRanking(0.0);
$this->setPoints(1);
}
function getId(){
return $this->id;
}
private function setId($value){
$this->id = $value;
}
function getUsername(){
return $this->username;
}
function setUsername($value){
$this->username = $value;
}
function getUrl(){
return $this->url;
}
function setUrl($value){
$this->url = $value;
}
function getTitle()
{
return $this->title;
}
function setTitle($value) {
$this->title = $value;
}
function getDescription() {
return $this->description;
}
function setDescription($value)
{
$this->description = $value;
}
function getPoints()
{
return $this->points;
}
function setPoints($value)
{
$this->points = $value;
}
function getRanking()
{
return $this->ranking;
}
function setRanking($value)
{
$this->ranking = $value;
}
function calculateRanking()
{
$created = $this->getCreated();
$diff = $this->getTimeDifference($created, date('F d, Y h:i:s A'));
$time = $diff['days'] * 24;
$time += $diff['hours'];
$time += ($diff['minutes'] / 60);
$time += (($diff['seconds'] / 60)/60);
$base = $time + 2;
$this->ranking = ($this->points - 1) / pow($base, 1.5);
$this->save();
}
function vote()
{
$this->points++;
$this->save();
}
function getUrlDomain()
{
/* We extract the domain from the URL
* using the following regex pattern
*/
$url = $this->getUrl();
$matches = array();
if(preg_match('/http:\/\/(.+?)\//', $url, $matches))
{
return $matches[1];
}
else
{
return $url;
}
}
function getTimeDifference( $start, $end )
{
$uts['start'] = strtotime( $start );
$uts['end'] = strtotime( $end );
if( $uts['start']!==-1 && $uts['end']!==-1 )
{
if( $uts['end'] >= $uts['start'] )
{
$diff = $uts['end'] - $uts['start'];
if( $days=intval((floor($diff/86400))) )
$diff = $diff % 86400;
if( $hours=intval((floor($diff/3600))) )
$diff = $diff % 3600;
if( $minutes=intval((floor($diff/60))) )
$diff = $diff % 60;
$diff = intval( $diff );
return( array('days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
}
else
{
echo( "Ending date/time is earlier than the start date/time");
}
}
else
{
echo( "Invalid date/time data detected");
}
return( false );
}
function getElapsedDateTime()
{
$db = null;
$record = null;
$record = Article::getById($this->id);
$created = $record->getCreated();
$diff = $this->getTimeDifference($created, date('F d, Y h:i:s A'));
//echo 'new date is '.date('F d, Y h:i:s A');
//print_r($diff);
if($diff['days'] > 0 )
{
return sprintf("hace %d dias", $diff['days']);
}
else if($diff['hours'] > 0 )
{
return sprintf("hace %d horas", $diff['hours']);
}
else if($diff['minutes'] > 0 )
{
return sprintf("hace %d minutos", $diff['minutes']);
}
else
{
return sprintf("hace %d segundos", $diff['seconds']);
}
}
function save() {
/*
Here we do either a create or
update operation depending
on the value of the id field.
Zero means create, non-zero
update
*/
if(!get_magic_quotes_gpc())
{
$this->title = addslashes($this->title);
$this->description = addslashes($this->description);
}
try
{
$db = parent::getConnection();
if($this->id == 0 )
{
$query = 'insert into articles (modified, username, url, title, description, points )';
$query .= " values ('$this->getModified()', '$this->username', '$this->url', '$this->title', '$this->description', $this->points)";
}
else if($this->id != 0)
{
$query = "update articles set modified = NOW()".", username = '$this->username', url = '$this->url', title = '".$this->title."', description = '".$this->description."', points = $this->points, ranking = $this->ranking where id = $this->id";
}
$lastid = parent::execSql2($query);
if($this->id == 0 )
$this->id = $lastid;
}
catch(Exception $e){
throw $e;
}
}
function delete()
{
try
{
$db = parent::getConnection();
if($this->id != 0)
{ ;
/*$comments = $this->getAllComments();
foreach($comments as $comment)
{
$comment->delete();
}*/
$this->deleteAllComments();
$query = "delete from articles where id = $this->id";
}
parent::execSql($query);
}
catch(Exception $e){
throw $e;
}
}
static function getAll($conditions = ' ')
{
/* Retrieve all the records from the
* database according subject to
* conditions
*/
$db = null;
$results = null;
$records = array();
$query = "select id, created, modified, username, url, title, description, points, ranking from articles $conditions";
try
{
$db = parent::getConnection();
$results = parent::execSql($query);
while($row = $results->fetch_assoc())
{
$r_id = $row['id'];
$r_created = $row['created'];
$r_modified = $row['modified'];
$r_title = $row['title'];
$r_description = $row['description'];
if(!get_magic_quotes_gpc())
{
$r_title = stripslashes($r_title);
$r_description = stripslashes($r_description);
}
$r_url = $row['url'];
$r_username = $row['username'];
$r_points = $row['points'];
$r_ranking = $row['ranking'];
$article = new Article($r_title, $r_description , $r_url, $r_username, $r_created, $r_modified);
$article->id = $r_id;
$article->points = $r_points;
$article->ranking = $r_ranking;
$records[] = $article;
}
parent::closeConnection($db);
}
catch(Exception $e)
{
throw $e;
}
return $records;
}
static function getById($id)
{/*
* Return one record from the database by its id */
$db = null;
$record = null;
try
{
$db = parent::getConnection();
$query = "select id, username, created, modified, title, url, description, points, ranking from articles where id = $id";
$results = parent::execSQL($query);
if(!$results) {
throw new Exception ('Record not found', EX_RECORD_NOT_FOUND);
}
$row = $results->fetch_assoc();
parent::closeConnection($db);
if(!get_magic_quotes_gpc())
{
$row['title'] = stripslashes($row['title']);
$row['description'] = stripslashes($row['description']);
}
$article = new Article($row['title'], $row['description'], $row['url'], $row['username'], $row['created'], $row['modified']);
$article->id = $row['id'];
$article->points = $row['points'];
$article->ranking = $row['ranking'];
return $article;
}
catch (Exception $e){
throw $e;
}
}
static function getNumberOfComments($id)
{/*
* Return one record from the database by its id */
$db = null;
$record = null;
try
{
$db = parent::getConnection();
$query = "select count(*) as 'total' from comments where article_id = $id";
$results = parent::execSQL($query);
if(!$results) {
throw new Exception ('Comments Count Query Query Failed', EX_QUERY_FAILED);
}
$row = $results->fetch_assoc();
$total = $row['total'];
parent::closeConnection($db);
return $total;
}
catch (Exception $e){
throw $e;
}
}
function deleteAllComments()
{/*
* Return one record from the database by its id */
$db = null;
try
{
$db = parent::getConnection();
$query = "delete from comments where article_id = $this->id";
$results = parent::execSQL($query);
if(!$results) {
throw new Exception ('Deletion Query Failed', EX_QUERY_FAILED);
}
parent::closeConnection($db);
}
catch (Exception $e){
throw $e;
}
}
function getAllComments($conditions = ' ')
{
/* Retrieve all the records from the
* database according subject to
* conditions
*/
$conditions = "where article_id = $this->id";
$comments = Comment::getAll($conditions);
return $comments;
}
static function getTestData($url)
{
$page = file_get_contents($url);
}
}
?>
Any suggestion or comment is appreciated, Thanks.
make another table user_votes for example with structure:
user_id int not null
article_id int not null
primary key (user_id, article_id)
in vote function first try to insert and if insert is successfull then increase $this->points
Have a table that keeps track of a user's vote for an article (something like UserID,ArticleID,VoteTimeStamp). Then you can just do a check in your $article->vote(); method to make sure the currently logged in user doesn't have any votes for that article.
If you want to keep thing fast (so you don't always have to use a join to get vote counts) you could have a trigger (or custom PHP code) that when adding/removing a vote updates the total vote count you currently keep in the article table.
You have these options:
Track the IP of whoever voted, and store it in a database. This is bad beucase many people might share IP and it can be circumvented using means such as proxies.
Another solution is to store a cookie in the browser. This is probably a bit better than the first solution as it lets many people from the same IP vote. It is, however, also easy to circumvent as you can delete your cookies.
The last and only secure method is to require your users to register to vote. This way you pair username and password against the votes and can ensure everyone votes only once, unless they are allowed to have several users.
A last solution might be a combination of the first two solutions, it is still obstructable though.
You could have a table containing a users ID and the article's ID called something like article_votes. So when user x votes for article y a row is inserted with both ID's. This allows you to check if a user has voted for an article.
To count the number of articles you could use a query like this: SELECT COUNT(*) AS votes FROM article_votes WHERE article=[article id]