Repost: Creating a RSS feed with PHP - php

I asked how to do this before but it seems I needed to put more code to really get an answer.
I have a reddit type site, and I am trying to create a rss feed this is the code, but I get a Fatal error: Uncaught exception 'Exception' with message 'Query failed'
Here its the code:
<?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(0);
}
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);
if($base > 0)
{
$this->ranking = ($this->points - 1) / pow($base, 1.5);
}
else
{
$this->ranking = 0;
}
$this->save();
}
function vote($user,$amount=1)
{
if($this->has_voted($user) == false)
{
$this->points += $amount;
$this->save();
$this->log_vote($user);
}
}
function log_vote($user)
{
try
{
$db = parent::getConnection();
$query = "insert into votes (article_id, username) values ($this->id, '$user')";
$results = parent::execSql($query);
}
catch(Exception $e){
throw $e;
}
}
function has_voted($user)
{
try
{
$db = parent::getConnection();
$query = "select id from votes where username = '$user' and article_id = $this->id";
$results = parent::execSQL($query);
if($results->num_rows == 1) {
return true;
}
else
{
return false;
}
parent::closeConnection($db);
}
catch(Exception $e){
throw $e;
}
}
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 )
{
//echo "start is $start, end is $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'));
//$diff = $this->getTimeDifference($created, date_add(date('F d, Y h:i:s A'),new DateInterval("5H")));
//echo 'new date is '.date('F d, Y h:i:s A');
//print_r($diff);
if($diff['days'] > 0 )
{
if($diff['days'] < 2 ) { return sprintf("%d dia", $diff['days']); }
else return sprintf("%d dias", $diff['days']);
}
else if($diff['hours'] > 0 )
{
if($diff['hours'] < 2 ) { return sprintf("%d hora", $diff['hours']); }
else return sprintf("%d horas", $diff['hours']);
}
else if($diff['minutes'] > 0 )
{
if($diff['minutes'] < 2 ) { return sprintf("%d minuto", $diff['minutes']); }
else return sprintf("%d minutos", $diff['minutes']);
}
else
{
if($diff['seconds'] < 2 ) { return sprintf("%d segundo", $diff['seconds']); }
else return sprintf("%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)";
createRSS(); // ++++++ rss +++++++
}
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);
}
}
function createRSS()
{
$articles = Article::getAll("order by created desc limit $offset, $num_items");
$num_articles = count($articles);
// open a file pointer to an RSS file
$fp = fopen ("rss.xml", "w");
if (!$fp) {
// Can't write to a file
return;
}
fwrite ($fp, "<?xml version='1.0' encoding='iso-8859-1' ?>\n");
fwrite ($fp, "<rss version='2.0' xmlns:atom=\"http://www.kiubbo.com/rss.xml\"><channel>\n");
fwrite ($fp, "<title>Kiubbo.com</title>\n");
fwrite ($fp, "<atom:link href='http://www.kiubbo.com/rss.xml' rel='self' type='application/rss+xml' />\n");
fwrite ($fp, "<link>http://www.kiubbo.com/</link>\n");
fwrite ($fp, "<description>Todas las Noticias Fotos y Videos.</description>\n");
fwrite ($fp, "<language>es-mx</language>\n");
fwrite ($fp, "<docs>http://www.kiubbo.com/rss.xml</docs>\n");
fwrite ($fp, "<image>\n");
fwrite ($fp, " <title>Kiubbo.com</title>\n");
fwrite ($fp, " <url>http://www.kiubbo.com/Logot.png</url>\n");
fwrite ($fp, " <link>http://www.kiubbo.com</link>\n");
fwrite ($fp, "</image>\n");
for($index = 0; $index < $num_articles; $index++){
$url = $articles[$index]->getUrl();
$title = $articles[$index]->getTitle(); // ok?
$search = array(
'#<script[^>]*?>.*?</script>#si', // Strip out javascript
'#<[\/\!]*?[^<>]*?>#si', // Strip out HTML tags
'#([\r\n])[\s]+#', // Strip out white space
'#&(quot|#34);#i', // Replace HTML entities
'#&(amp|#38);#i',
'#&(lt|#60);#i',
'#&(gt|#62);#i',
'#&(nbsp|#160);#i',
'#&(iexcl|#161);#i',
'#&(cent|#162);#i',
'#&(pound|#163);#i',
'#&(copy|#169);#i',
'#&(acento|#0027);#i',
'#&#(\d+);#e'); // evaluate as php
$replace = array(
'',
'',
'\1',
'"',
'&',
'<',
'>',
' ',
'chr(161)',
'chr(162)',
'chr(163)',
'chr(169)',
'chr(\1)');
$content = preg_replace($search, $replace, $content);
$title = preg_replace("/&/", 'y', $title);
$content = preg_replace("/&/", 'y', $content);
fwrite ($fp, "<item>\n");
fwrite ($fp, " <title>$title</title>\n");
fwrite ($fp, " <link>$url</link>\n");
fwrite ($fp, "<guid>http://www.kiubbo.com</guid>\n");
fwrite ($fp, "</item>\n");
}
fwrite ($fp, "</channel></rss>\n");
fclose ($fp);
}
?>
Thx
Regards
Carlos

I'm not at a machine with php to test this, but you have queries with variables as follows...
"select id from votes where username = '$user' and article_id = $this->id"
I'm fairly certain that you need to bracket or concatenate when using objects...
"select id from votes where username = '$user' and article_id = ${this->id}"
or
"select id from votes where username = '$user' and article_id = " . $this->id

Related

Fatal error: Call to a member function get() on null in C:\appserv\www\Cocolani\php\req\register.php on line 4

I'm still a beginner programmer , so I hope you give the solution step by step.
I'm trying to make a private server for a flash game and i have a problem that I don't know how can I solve it at all .
I wanna connect the game with the database , and when someone tries to make an account (register) in the game , the account data supposed to be saved in the database ( like: username,password,mask color,birth date,register date,etc...) but it doesn't happen
The file which is responsible about this step is called " register.php" and
I keep getting this error :
Fatal error: Call to a member function get() on null in C:\appserv\www\Cocolani\php\req\register.php on line 4
the problem is in this line :
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
and this is "register.php" :
<?php
include_once("db.php");
include_once("settings.php");
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
$FROM_EMAIL = $obj->getEmailFrom();
function generateTribeCurrency($ID, $db) {
// $db = new database();
// get init purse amount
$db->setQuery("SELECT init_purse_amount FROM `cc_def_settings`");
$row = $db->loadResult();
$init_purse_amount = $row->init_purse_amount;
// load tribe info
$db->setQuery("SELECT * FROM `cc_tribes`");
$tribeinfo = $db->loadResults();
$newstr = array();
foreach ($tribeinfo as $i) {
if ($ID == $i->ID) array_push($newstr, $init_purse_amount); else array_push($newstr, 0);
}
$newstr = implode(",", $newstr);
return $newstr;
}
$hackchk = false;
foreach($_POST as $POST) {
$POST = mysqli_real_escape_string($POST);
}
function remove_bad_symbols($s) {
return preg_replace(
array(0=>'#/#', 1=>'#\\\#', 2=>'#;#', 3=>'#{#', 4=>'#}#', 5=>'#<#', 6=>'#>#', 7=>'###', 8=>'#\'#', 9=>'# #', 10=>'#"#') // patterns
, '' // replacements
, $s);
}
$username = isset($_POST['username']) ? remove_bad_symbols($_POST['username']) : "";
$password = isset($_POST['password']) ? $_POST['password'] : "";
$email = isset($_POST['email']) ? $_POST['email'] : "";
$birthdate = isset($_POST['birthdate']) ? $_POST['birthdate'] : "";
$firstname = isset($_POST['firstname']) ? $_POST['firstname'] : "";
$lastname = isset($_POST['lastname']) ? $_POST['lastname'] : "";
$sex = isset($_POST['sex']) ? $_POST['sex'] : "";
$tribeid = isset($_POST['clan']) ? $_POST['clan'] : "";
$mask = isset($_POST['mask']) ? $_POST['mask'] : "";
$mask_color = isset($_POST['maskcl']) ? $_POST['maskcl'] : "";
$lang_id = isset($_POST['lang_id']) ? $_POST['lang_id'] : 0;
$error = '';
$purse = generateTribeCurrency((int) $tribeid, $db);
// get language suffix
if ($lang_id != 0) {
$db->setQuery("SELECT * FROM `cc_extra_langs` WHERE id='{$lang_id}'");
$res = $db->loadResult();
$lang = "_".$res->lang;
} else $lang = "";
$db->setQuery("SELECT one_email_per_registration FROM `cc_def_settings`");
$res = $db->loadResult();
$one_registration_per_email = ($res->one_email_per_registration == 1);
$email_check_ok = true;
if ($one_registration_per_email == true) {
$sql = "SELECT COUNT(*) AS counter FROM `cc_user` WHERE email='{$email}'";
// for several registrations per one email address -- no check
$db->setQuery($sql);
$res1 = $db->loadResult();
$email_check_ok = $res1->counter == "0";
}
// first check there is no username with this name already registered.
$db->setQuery("SELECT COUNT(*) AS counter FROM `cc_user` WHERE username='".$username."'");
$res = $db->loadResult();
if ($username && $email && $sex && $birthdate) {
if ($email_check_ok) {
if ($res->counter == "0") {
// check that there are no registrations from this same IP in the last 2 hours
$db->setQuery("SELECT COUNT(*) as counter FROM `cc_userreginfo` WHERE IP='".$_SERVER['REMOTE_ADDR']."' AND (DATE_SUB(CURDATE(), INTERVAL 2 HOUR)<register_date)");
$regcheck = $db->loadResult();
if (($regcheck != null && (int)($regcheck->counter) == 0) || $hackchk == false) {
// get number of already registered number of registrations with this email address
$query = $db->setQuery("SELECT count(*) as registered_num_emails FROM `cc_user` WHERE email='{$email}'");
$row = $db->loadResult();
$already_registered_num_emails = $row->registered_num_emails;
// get max number of accounts per email from settings table
$query = $db->setQuery("SELECT max_num_account_per_email from `cc_def_settings`");
$row = $db->loadResult();
$max_num_account_per_email = $row->max_num_account_per_email;
if ($already_registered_num_emails < $max_num_account_per_email) {
$uniqid = uniqid();
$newreq = "INSERT INTO `cc_user` (`ID`,`username`, `password`, `email`, `birth_date`, `first_name`, `last_name`, `sex`, `about`, `mask`, `mask_colors`, `clothing`, `tribe_ID` , `money`, `happyness`, `rank_ID`, `status_ID`, `lang_id`, `register_date`, uniqid, permission_id) VALUES ";
$newreq .= "(NULL, '{$username}', '{$password}', '{$email}', '{$birthdate}', '{$firstname}' , '{$lastname}', '{$sex}', '', '{$mask}', '{$mask_color}', '', '{$tribeid}', '{$purse}', 50, 0, 3, '{$lang_id}', NOW(), '{$uniqid}', 4)";
$db->setQuery($newreq);
$res = $db->runQuery();
if ($res) {
// add registration info into the userreginfo table as well.
$iid = $db->mysqlInsertID();
$db->setQuery("INSERT INTO `cc_userreginfo` (`ID`, `user_id`, `register_IP`, `register_date`, `last_update`) VALUES (NULL, ".$iid.",'".$_SERVER['REMOTE_ADDR']."', NOW(), NOW())");
$res2 = $db->runQuery();
$counter = ($regcheck != null) ? $regcheck->counter : 0;
echo 'response=true&reg='.$counter;
// ----------------------------------
// send confirmation email
// ----------------------------------
$cur_lang = ($lang != "") ? substr($lang, 1)."/" : "";
$msg = $obj->getTranslation(-13, $lang, "email_templates", "id", "content");
$msg = str_replace("%FIRST_NAME%", $firstname, $msg);
$msg = str_replace("%LAST_NAME%", $lastname, $msg);
$msg = str_replace("'", "'", $msg);
$msg = str_replace("%CONFIRM%", 'confirm', $msg);
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf8' . "\r\n";
$headers .= 'From: '.$FROM_EMAIL."\r\n";
//mail($email, $obj->getTranslation(-13, $lang, "email_templates", "id", "subject"), $msg, $headers);
include "../../admin/php_mailer/class.phpmailer.php";
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = $msg;
$body = eregi_replace("[\]",'',$body);
$mail->SetFrom($FROM_EMAIL);
$mail->AddAddress($email);
$mail->Subject = $obj->getTranslation(-13, $lang, "email_templates", "id", "subject");
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
if(!$mail->Send()) {
die("Mailer Error: " . $mail->ErrorInfo);
} else {
//echo "Message sent!";
}
// ----------------------------------
} else {
echo 'response=false';
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='MAX_NUM_REGISTRATION_REACHED'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='REGISTER_LATER'");
$res = $db->loadResult();
echo 'errorhide='.urlencode($res->{"name".$lang});
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='USERNAME_IN_USE'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
} else {
//if ($one_registration_per_email == true)
$sql = "SELECT * FROM `cc_translations` WHERE caption='DUPLICATED_EMAIL'"; //else $sql = "SELECT * FROM `cc_translations` WHERE caption='DUPLICATED_REGISTRATION'";
// get warning message from db
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
} else {
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='REGFORM_PROBLEM'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
}
?>
note : "register.php" requires two files so maybe the error is in one of them
settings.php :
<?php
$db_server = "localhost";
$db_user = "root";
$db_password = "qazqazqaz1";
$db_name = "coco";
$connect = mysqli_connect("$db_server","$db_user","$db_password","$db_name");
?>
db.php:
<?php
class database {
var $_debug = 0;
var $_sql = '';
var $_error = '';
var $_prefix = '';
var $_numrows = 0;
var $_DBhost = 'localhost';
var $_DBuser = "root";
var $_DBpass = "qazqazqaz1";
var $_DBname = "cocol";
var $url_root = "localhost/cocolani";
public function __construct($dbname = 'cocolani_battle', $dbuser = 'root', $dbpsw = 'pass1234', $dbhost = 'localhost', $urlroot = 'localhost/cocolani') {
$this->_DBname = 'cocolani_battle';
$this->_DBuser = 'root';
$this->_DBpass = 'pass1234';
$this->url_root = 'localhost/cocolani';
$this->_DBhost = 'localhost';
$this->_connection = mysqli_connect($this->_DBhost, $this->_DBuser, $this->_DBpass) or die("Couldn't connect to MySQL");
mysqli_select_db($this->_connection, $this->_DBname) or die("Select DB Error: ".mysqli_error());
}
public function __destruct() {
mysqli_close($this->_connection);
}
function debug($debug_level) {
$this->_debug = intval($debug_level);
}
function setQuery($sql) {
/* queries are given in the form of #__table need to replace that with the prefix */
$this->_sql = str_replace('#__', $this->_prefix.'_', $sql);
}
function getQuery() {
return "<pre>" . htmlspecialchars( $this->_sql) . "</pre>";
}
function prepareStatement($sql) {
$this->sql = mysqli_prepare($this->_connection, $sql);
return $this->sql;
}
function runQuery($num_rows=0) {
mysqli_select_db($this->_connection, $this->_DBname) or die("Select DB Error: ".mysqli_error());
$this->_numrows = 0;
$result = mysqli_query($this->_connection, $this->_sql);
if ($this->_debug > 1) echo "<pre>" . htmlspecialchars( $this->_sql) . "</pre>";
if (!$result) {
$this->_error = mysqli_error($this->_connection);
if ($this->_debug) {
echo 'Error: ' . $this->getQuery() . $this->_error;
}
return false;
}
if ($num_rows) {
$this->_numrows = mysqli_num_rows($result);
}
return $result;
}
/* Retrieve Mysql insert id */
function mysqlInsertID() {
$insert_id = mysqli_insert_id();
return $insert_id;
}
/* Escapes special characters while inserting to db */
function db_input($string) {
if (is_array($string)) {
$retArray = array();
foreach($string as $key => $value) {
$value = (get_magic_quotes_gpc() ? stripslashes($value) : $value);
$retArray[$key] = mysqli_real_escape_string($value);
}
return $retArray;
} else {
$string = (get_magic_quotes_gpc() ? stripslashes($string) : $string);
return mysqli_real_escape_string($string);
}
}
function getError() {
return $this->_error;
}
/* Load results into csv formatted string */
function loadCsv() {
if (!($res = $this->runQuery())) {
return null;
}
$csv_string = '';
while ($row = mysqli_fetch_row($res)) {
$line = '';
foreach( $row as $value ) {
if ( ( !isset( $value ) ) || ( $value == "" ) ) {
$value = ",";
} else {
$value = $value. ",";
$value = str_replace( '"' , '""' , $value );
}
$line .= $value;
}
$line = substr($line, 0, -1);
$csv_string .= trim( $line ) . "\n";
}
$csv_string = str_replace( "\r" , "" , $csv_string );
//$csv_string .= implode(",", $row) . "\n";
mysqli_free_result($res);
return $csv_string;
}
/* Load multiple results */
function loadResults($key='' ) {
if (!($res = $this->runQuery())) {
return null;
}
$array = array();
while ($row = mysqli_fetch_object($res)) {
if ($key) {
$array[strtolower($row->$key)] = $row;
} else {
$array[] = $row;
}
}
mysqli_free_result($res);
return $array;
}
function loadResult() {
if (!($res = $this->runQuery())) {
if ($this->_debug) echo 'Error: ' . $this->_error;
return null;
}
$row = mysqli_fetch_object($res);
mysqli_free_result($res);
return $row;
}
/* Load a result field into an array */
function loadArray() {
if (!($res = $this->runQuery())) {
return null;
}
$array = array();
while ($row = mysql_fetch_row($res)) {
$array[] = $row[0];
}
mysqli_free_result($res);
return $array;
}
/* Load a row into an associative an array */
function loadAssoc() {
if (!($res = $this->runQuery())) {
return null;
}
$row = mysqli_fetch_assoc($res);
mysqli_free_result($res);
return $row;
}
/* Return one field */
function loadField() {
if (!($res = $this->runQuery())) {
return null;
}
while ($row = mysql_fetch_row($res)) {
$field = $row[0];
}
mysqli_free_result($res);
return $field;
}
?>
I tried to solve it myself but I lost hope , so please tell me the accurate solution in steps .
thanks.
The error is referring to $obj->get. Basically you're executing the get method on a null variable, meaning it doesn't exist. After looking through all the code you have there, you aren't declaring $obj at any point.
I think you might need to check how you're passing in your settings to your Database object. For example:
$db = new database($db_server, ... , ...);
Updated:
You're hardcoding your connection anyway, just don't pass anything to the DB object.
Change this:
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
To this:
$db = new database();

Fatal error: Call to a member function get() on null in C:\wamp\www\Cocolani\php\req\checkusername.php on line 4

I get an error in my file "checkusername.php".
The error I get is:
( ! ) Fatal error: Call to a member function get() on null in
C:\wamp\www\Cocolani\php\req\checkusername.php on line 4
There is a "checkusername.php" file :
<?php
include_once("../../includes/db.php");
include_once("settings.php");
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
$username = isset($_POST['username']) ? mysqli_real_escape_string($_POST['username']) : "";
$password = isset($_POST['password']) ? mysqli_real_escape_string($_POST['password']) : "";
$email = isset($_POST['email']) ? mysqli_real_escape_string($_POST['email']) : '';
$birthdate = isset($_POST['birthdate']) ? mysqli_real_escape_string($_POST['birthdate']) : "";
$firstname = isset($_POST['firstname']) ? mysqli_real_escape_string($_POST['firstname']) : "";
$lastname = isset($_POST['lastname']) ? mysqli_real_escape_string($_POST['lastname']) : "";
$sex = isset($_POST['sex']) ? mysqli_real_escape_string($_POST['sex']) : "";
$tribeid = isset($_POST['clan']) ? mysqli_real_escape_string($_POST['clan']) : "";
$mask = isset($_POST['mask']) ? mysqli_real_escape_string($_POST['mask']) : "";
$mask_color = isset($_POST['maskcl']) ? mysqli_real_escape_string($_POST['maskcl']) : "";
$lang_id = isset($_POST['lang_id']) ? addslashes($_POST['lang_id']) : 0;
$error = '';
// get language suffix
if ($lang_id != 0) {
$db->setQuery("SELECT * FROM `cc_extra_langs` WHERE id='{$lang_id}'");
$res = $db->loadResult();
$lang = "_".$res->lang;
} else $lang = "";
$reg_ok = true;
$db->setQuery("SELECT one_email_per_registration FROM `cc_def_settings`");
$res = $db->loadResult();
$one_registration_per_email = ($res->one_email_per_registration == 1);
$email_check_ok = true;
if ($one_registration_per_email == true) {
$sql = "SELECT COUNT(*) AS counter FROM `cc_user` WHERE email='{$email}'"; // for several registrations per one email address -- no check
$db->setQuery($sql);
$res1 = $db->loadResult();
$email_check_ok = $res1->counter == "0";
}
if ($email_check_ok == false) {
$sql = "SELECT * FROM `cc_translations` WHERE caption='DUPLICATED_EMAIL'";
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
/*if ($reg_ok && $email != '') {
// get number of already registered number of registrations with this email address
$sql = "SELECT count(*) as registered_num_emails FROM `cc_user` WHERE email='{$email}'";
$query = $db->setQuery($sql);
$row = mysql_fetch_object($query);
$registered_num_emails = $row->registered_num_emails;
$sql = "SELECT max_num_account_per_email from `cc_def_settings`";
$query = $db->setQuery($sql);
$row = mysql_fetch_object($query);
// it's possible to create new registration using this email address
if ($registered_num_emails >= $row->max_num_account_per_email) {
$sql = "SELECT * FROM `cc_translations` WHERE caption='MAX_NUM_REGISTRATION_REACHED'";
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
}*/
////////
// echo 'error=111';
// $reg_ok = false;
////////
if ($reg_ok) {
// check for swear words
$db->setQuery("SELECT COUNT(*) as counter from `cc_swear_words` where INSTR('".$username."', `name`)");
$res2 = $db->loadResult();
if ((int)($res2->counter) > 0) { // swear word founded!
$sql = "SELECT * FROM `cc_translations` WHERE caption='USERNAME_NOT_PERMITTED'";
$db->setQuery($sql);
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
}
if ($reg_ok) {
// first check there is no username with this name already registered.
$db->setQuery("SELECT COUNT(*) AS counter FROM `cc_user` WHERE username='".$username."'");
$res = $db->loadResult();
if ((int)($res->counter) > 0) { // swear word founded!
// get warning message from db
$db->setQuery("SELECT * FROM `cc_translations` WHERE caption='USERNAME_IN_USE'");
$res = $db->loadResult();
echo 'error='.urlencode($res->{"name".$lang});
$reg_ok = false;
}
}
if ($reg_ok) echo 'result=true';
?>
The problem on line 4 which is :
$db = new database($obj->get("db_name"), $obj->get("db_server"), $obj->get("db_user"), $obj->get("db_password"), $obj->get("url_root"));
There is a "settings.php" :
<?php
$db_server = "localhost";
$db_user = "root";
$db_password = "pass1234";
$db_name = "cocolani_battle";
$appsecret = "80f730a73ac60417c36c341bc975f6f1";
$connect = mysqli_connect("$db_server","$db_user","$db_password","$db_name");
?>
and there is a "db.php" :
<?php
/*
Usage
$db = new database($dbname);
for selects:
$db->setQuery("SELECT * FROM `table`")
$resultArray = $db->loadResults();
$db->setQuery("SELECT * FROM `table` WHERE `primary_id` = '1'");
$resultObject = $db->loadResult();
for inserts:
$db->setQuery("INSERT INTO `table` (`id`, `example`) VALUES ('1', 'abc')");
if (!$db->runQuery()) {
echo $db->getError();
}
*/
class database {
var $_debug = 0;
var $_sql = '';
var $_error = '';
var $_prefix = '';
var $_numrows = 0;
var $_DBhost = 'localhost';
var $_DBuser = "root";
var $_DBpass = "pass1234";
var $_DBname = "cocolani_battle";
var $url_root = "localhost/cocolani";
public function __construct($dbname = 'cocolani_battle', $dbuser = 'root', $dbpsw = 'pass1234', $dbhost = 'localhost', $urlroot = 'localhost/cocolani') {
$this->_DBname = 'cocolani_battle';
$this->_DBuser = 'root';
$this->_DBpass = 'pass1234';
$this->url_root = 'localhost/cocolani';
$this->_DBhost = 'localhost';
$this->_connection = mysqli_connect($this->_DBhost, $this->_DBuser, $this->_DBpass) or die("Couldn't connect to MySQL");
mysqli_select_db($this->_connection, $this->_DBname) or die("Select DB Error: ".mysqli_error());
}
public function __destruct() {
mysqli_close($this->_connection);
}
function debug($debug_level) {
$this->_debug = intval($debug_level);
}
function setQuery($sql) {
/* queries are given in the form of #__table need to replace that with the prefix */
$this->_sql = str_replace('#__', $this->_prefix.'_', $sql);
}
function getQuery() {
return "<pre>" . htmlspecialchars( $this->_sql) . "</pre>";
}
function prepareStatement($sql) {
$this->sql = mysqli_prepare($this->_connection, $sql);
return $this->sql;
}
function runQuery($num_rows=0) {
mysqli_select_db($this->_connection, $this->_DBname) or die("Select DB Error: ".mysqli_error());
$this->_numrows = 0;
$result = mysqli_query($this->_connection, $this->_sql);
if ($this->_debug > 1) echo "<pre>" . htmlspecialchars( $this->_sql) . "</pre>";
if (!$result) {
$this->_error = mysqli_error($this->_connection);
if ($this->_debug) {
echo 'Error: ' . $this->getQuery() . $this->_error;
}
return false;
}
if ($num_rows) {
$this->_numrows = mysqli_num_rows($result);
}
return $result;
}
/* Retrieve Mysql insert id */
function mysqlInsertID() {
$insert_id = mysqli_insert_id();
return $insert_id;
}
/* Escapes special characters while inserting to db */
function db_input($string) {
if (is_array($string)) {
$retArray = array();
foreach($string as $key => $value) {
$value = (get_magic_quotes_gpc() ? stripslashes($value) : $value);
$retArray[$key] = mysqli_real_escape_string($value);
}
return $retArray;
} else {
$string = (get_magic_quotes_gpc() ? stripslashes($string) : $string);
return mysqli_real_escape_string($string);
}
}
function getError() {
return $this->_error;
}
/* Load results into csv formatted string */
function loadCsv() {
if (!($res = $this->runQuery())) {
return null;
}
$csv_string = '';
while ($row = mysqli_fetch_row($res)) {
$line = '';
foreach( $row as $value ) {
if ( ( !isset( $value ) ) || ( $value == "" ) ) {
$value = ",";
} else {
$value = $value. ",";
$value = str_replace( '"' , '""' , $value );
}
$line .= $value;
}
$line = substr($line, 0, -1);
$csv_string .= trim( $line ) . "\n";
}
$csv_string = str_replace( "\r" , "" , $csv_string );
//$csv_string .= implode(",", $row) . "\n";
mysqli_free_result($res);
return $csv_string;
}
/* Load multiple results */
function loadResults($key='' ) {
if (!($res = $this->runQuery())) {
return null;
}
$array = array();
while ($row = mysqli_fetch_object($res)) {
if ($key) {
$array[strtolower($row->$key)] = $row;
} else {
$array[] = $row;
}
}
mysqli_free_result($res);
return $array;
}
function loadResult() {
if (!($res = $this->runQuery())) {
if ($this->_debug) echo 'Error: ' . $this->_error;
return null;
}
$row = mysqli_fetch_object($res);
mysqli_free_result($res);
return $row;
}
/* Load a result field into an array */
function loadArray() {
if (!($res = $this->runQuery())) {
return null;
}
$array = array();
while ($row = mysql_fetch_row($res)) {
$array[] = $row[0];
}
mysqli_free_result($res);
return $array;
}
/* Load a row into an associative an array */
function loadAssoc() {
if (!($res = $this->runQuery())) {
return null;
}
$row = mysqli_fetch_assoc($res);
mysqli_free_result($res);
return $row;
}
/* Return one field */
function loadField() {
if (!($res = $this->runQuery())) {
return null;
}
while ($row = mysql_fetch_row($res)) {
$field = $row[0];
}
mysqli_free_result($res);
return $field;
}
}
/*if ($_SERVER["SERVER_ADDR"] == '127.0.0.1') {
$url_root = "http://cocolani.localhost";
} else {
$url_root = "http://dev.cocolani.com";
}*/
?>
How can I fix this error?
As I mentioned in my comment, you can either use the variables you defined in your settings.php:
$db = new database($db_name, $db_server, $db_user, $db_password, $db_urlroot); // You didn't define $db_urlroot anywhere, but you can define it
OR hard-code it into your class. You're not using the variables you pass in anyway, so there's no need to ask for them.
public function __construct() {

How to write helper class for different select operation?

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

Instantiating class and passing action

I'm working through a PHP starter book I just got along with code. I am stuck on this one example and I have no idea what's going on. Can someone help explain what is going on?
This class seems to get instantiated and the default case is to list the posts recorded to a database:
<?php
require_once('../includes/admin.php');
$admin_posts = new Posts;
When the class gets called, the default case loads options to pass the id and action to the php file above, then it will parse and call another method. In my case, i'm trying to delete a post, but I keep getting an error that says object not found.
<?php
session_start();
require_once('database.php');
class Adminpanel{
public function __construct(){
$inactive = 600;
if (isset($_SESSION["kickstart_login"])) {
$sessionTTL = time() - $_SESSION["timeout"];
if ($sessionTTL > $inactive) {
session_unset();
session_destroy();
header("Location: http://".$_SERVER['SERVER_NAME']."/login.php?status=inactive");
}
}
$_SESSION["timeout"] = time();
$login = $_SESSION['kickstart_login'];
if(empty($login)){
session_unset();
session_destroy();
header('Location: http://'.$_SERVER['SERVER_NAME'].'/login.php?status=loggedout');
}else{
$this->ksdb = new Database;
$this->base = (object) '';
$this->base->url = 'http://'.$_SERVER['SERVER_NAME'];
}
}
}
class Posts extends Adminpanel{
public function __construct(){
parent::__construct();
if(!empty($_GET['action'])){
switch ($_GET['action']){
case 'create':
$this->addPost();
break;
default:
$this->listPosts();
break;
case 'save':
$this->savePost();
break;
case 'edit':
echo "string";
$this->editPosts();
break;
case 'delete':
$this->deletePost();
break;
}
}else{
$this->listPosts();
}
}
public function listPosts(){
$posts = $return = array();
$query = $this->ksdb->db->prepare("SELECT * FROM posts");
try {
$query->execute();
for($i=0; $row = $query->fetch(); $i++){
$return[$i] = array();
foreach($row as $key => $rowitem){
$return[$i][$key] = $rowitem;
}
}
}catch (PDOException $e) {
echo $e->getMessage();
}
$posts = $return;
require_once('templates/manageposts.php');
}
public function editPosts(){
echo "string";
}
public function addPost(){
require_once('templates/newpost.php');
}
public function savePost(){
$status= '';
$array = $format = $return = array();
if(!empty($_POST['post'])){
$post = $_POST['post'];
}
if(!empty($post['content'])){
$array['content'] = $post['content'];
$format[] = ':content';
}
if(!empty($post['title'])){
$array['title'] = $post['title'];
$format[] = ':title';
}
$cols = $values = '';
$i=0;
foreach($array as $col => $data){
if($i==0){
$cols .= $col;
$values .= $format[$i];
}else{
$cols .= ','.$col;
$values .= ','.$format[$i];
}
$i++;
}
try {
$query = $this->ksdb->db->prepare("INSERT INTO posts(".$cols.") VALUES (".$values.")");
for($c=0;$c<$i;$c++){
$query->bindParam($format[$c], ${'var'.$c});
}
$z=0;
foreach($array as $col => $data){
${'var' . $z} = $data;
$z++;
}
$result = $query->execute();
$add = $query->rowCount();
}catch (PDOException $e) {
echo $e->getMessage();
}
$query->closeCursor();
$this->db = null;
if(!empty($add) && $add > 0){
$status = array('success' => 'Your post has been saved successfully.');
$key = 'success';
}else{
$status = array('error' => 'There has been an error saving your post. Please try again later.');
$key = 'error';
}
header("Location: ".$this->base->url."/posts.php?status=".$key);
}
public function deletePost(){
echo "string";
// if(!empty($_GET['id']) && is_numeric($_GET['id'])){
// $query = "DELETE FROM `posts` WHERE id = ".$_GET['id'];
// $result = $this->db->query($query);
// $delete = $result->rowCount();
// $this->db = null;
// if(!empty($delete) && $delete > 0){
// header("Location: ".$this->base->url."/posts.php?delete=success");
// }else{
// header("Location: ".$this->base->url."/posts.php?delete=error");
// }
// }
}
}
class Comments extends Adminpanel{
public function __construct(){
parent::__construct();
if(!empty($_GET['action']) && $_GET['action'] == 'delete'){
$this->deleteComment();
}else{
$this->listComments();
}
}
public function listComments(){
$comments = $return = array();
$query = $this->ksdb->db->prepare("SELECT * FROM comments");
try {
$query->execute();
for($i=0; $row = $query->fetch(); $i++){
$return[$i] = array();
foreach($row as $key => $rowitem){
$return[$i][$key] = $rowitem;
}
}
}catch (PDOException $e) {
echo $e->getMessage();
}
$comments = $return;
require_once('templates/managecomments.php');
}
public function deleteComment(){
if(!empty($_GET['id']) && is_numeric($_GET['id'])){
$query = "DELETE FROM `comments` WHERE id = ".$_GET['id'];
$result = $this->db->query($query);
$delete = $result->rowCount();
$this->db = null;
if(!empty($delete) && $delete > 0){
header("Location: ".$this->base->url."/comments.php?delete=success");
}else{
header("Location: ".$this->base->url."/comments.php?delete=error");
}
}
}
}
$admin = new Adminpanel();

How can I implement a voting system on my site limiting votes to a single vote?

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]

Categories