I have created joomla pagination for my own component and its working fine for joomla 2.5 and i have use same for joomla 3.0 the data is displaying and also the pagination is also displaying correctly but the issue is when i click on any pagination no. for going next or prev page its not working form remains on same page.
Here is code i have used for creating pagination.
model.php
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.modellist');
class eventsModelEvents extends JModelLegacy {
var $_total = null;
var $_pagination = null;
function __construct()
{
parent::__construct();
$mainframe = JFactory::getApplication();
// Get pagination request variables
$limit = $mainframe->getUserStateFromRequest('global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int');
$limitstart = JRequest::getVar('limitstart', 0, '', 'int');
// In case limit has been changed, adjust it
$limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0);
$this->setState('limit', $limit);
$this->setState('limitstart', $limitstart);
}
function getPagination()
{
// Load the content if it doesn't already exist
if (empty($this->_pagination)) {
jimport('joomla.html.pagination');
$this->_pagination = new JPagination($this->getTotal(), $this->getState('limitstart'), $this->getState('limit') );
}
return $this->_pagination;
}
function getTotal()
{
// Load the content if it doesn't already exist
if (empty($this->_total)) {
$query = $this->_buildQuery();
$this->_total = $this->_getListCount($query);
}
return $this->_total;
}
function getData()
{
// if data hasn't already been obtained, load it
if (empty($this->_data)) {
$query = $this->_buildQuery();
$this->_data = $this->_getList($query, $this->getState('limitstart'), $this->getState('limit'));
}
return $this->_data;
}
function _buildQuery()
{
// Create a new query object.
$db = JFactory::getDBO();
$query = $db->getQuery(true);
// Select some fields
$query->select('*');
// From the hello table
$query->from('#__events');
$query->order('date DESC');
return $query;
}
function getEvents(){
$db = $this->getDBO();
$db->setQuery('SELECT * from #__events');
$events = $db->loadObjectList();
if ($events === null)
JError::raiseError(500, 'Error reading db');
return $events;
}
function getEvent($id){
$query = ' SELECT * FROM #__events '.
' WHERE id = '.$id;
$db = $this->getDBO();
$db->setQuery($query);
$event = $db->loadObject();
if ($event === null)
JError::raiseError(500, 'Event with ID: '.$id.' not found.');
else
return $event;
}
function saveEvent($event){
$db = $this->getDBO();
$uploaded_path = JPATH_COMPONENT. "/images/";
if($_FILES["event_image"]["tmp_name"]){
if ($_FILES["event_image"]["error"] > 0){
return $_FILES["event_image"]["error"] . "<br>";
} else {
move_uploaded_file($_FILES["event_image"]["tmp_name"],$uploaded_path . $_FILES["event_image"]["name"]);
$event['event_image'] = $_FILES["event_image"]["name"];
}
} else {
$event['event_image'] = $event['event_stored_image'];
}
$event['event_date'] = date('Y-m-d H:i:s', strtotime($event['event_date']));
foreach($event as $key => $value){
$event[$key] = mysql_real_escape_string($value);
}
if(($event['event_name'] != NULL ) && ($event['event_image'] != NULL) && ($event['event_date'] != NULL) && ($event['event_description'] != NULL)){
if(isset($event['event_id'])){
$query = "UPDATE #__events SET name = '".$event['event_name']."',status = '".$event['event_status']."',image = '".$event['event_image']."',date = '".$event['event_date']."',description = '".$event['event_description']."',reservation = '".$event['event_reservation']."' WHERE id =" . $event['event_id'];
} else {
$query = "INSERT INTO #__events (name,status,image,date,description,reservation) VALUES ('".$event['event_name']."','".$event['event_status']."','".$event['event_image']."','".$event['event_date']."','".$event['event_description']."', '".$event['event_reservation']."')";
}
$db->setQuery($query);
if (!$db->query()){
$errorMessage = $this->getDBO()->getErrorMsg();
JError::raiseError(500, 'Error inserting event: '.$errorMessage);
}
} else {
return "Please Fill All fields.";
}
}
function deleteEvents($arrayIDs)
{
$query = "DELETE FROM #__events WHERE id IN (".implode(',', $arrayIDs).")";
$db = $this->getDBO();
$db->setQuery($query);
if (!$db->query()){
$errorMessage = $this->getDBO()->getErrorMsg();
JError::raiseError(500, 'Error deleting events: '.$errorMessage);
}
}
function publishEvents($arrayIDs)
{
$query = "UPDATE #__events SET status = '1' WHERE id IN (".implode(',', $arrayIDs).")";
$db = $this->getDBO();
$db->setQuery($query);
if (!$db->query()){
$errorMessage = $this->getDBO()->getErrorMsg();
JError::raiseError(500, 'Error publishing events: '.$errorMessage);
}
}
function unpublishEvents($arrayIDs)
{
$query = "UPDATE #__events SET status = '0' WHERE id IN (".implode(',', $arrayIDs).")";
$db = $this->getDBO();
$db->setQuery($query);
if (!$db->query()){
$errorMessage = $this->getDBO()->getErrorMsg();
JError::raiseError(500, 'Error publishing events: '.$errorMessage);
}
}
}
view.html.php
jimport( 'joomla.application.component.view');
class eventsViewEvents extends JViewLegacy {
protected $categories;
protected $items;
protected $pagination;
protected $state;
function display($tpl = null)
{
$this->categories = $this->get('CategoryOrders');
$this->state = $this->get('State');
$this->addToolBar();
// Get data from the model
$events = $this->get('Data');
$pagination =$this->get('Pagination');
// push data into the template
$this->events = $events;
$this->assignRef('pagination', $pagination);
parent::display($tpl);
}
function add($tpl = null){
$this->addToolBar();
parent::display($tpl);
}
protected function addToolbar()
{
require_once JPATH_COMPONENT . '/helpers/events.php';
$canDo = EventsHelper::getActions($this->state->get('filter.category_id'));
$user = JFactory::getUser();
JToolBarHelper::title('Event Manager', 'generic.png');
JToolBarHelper::addNew('add');
if (count($user->getAuthorisedCategories('com_events', 'core.create')) > 0)
{
//JToolBarHelper::addNew('add');
}
if (($canDo->get('core.edit')))
{
JToolBarHelper::editList('edit');
}
if ($canDo->get('core.edit.state'))
{
if ($this->state->get('filter.state') != 2)
{
JToolBarHelper::divider();
JToolBarHelper::publish('publish', 'JTOOLBAR_PUBLISH', true);
JToolBarHelper::unpublish('unpublish', 'JTOOLBAR_UNPUBLISH', true);
}
}
if ($this->state->get('filter.state') == -2 && $canDo->get('core.delete'))
{
JToolBarHelper::deleteList('', 'remove', 'JTOOLBAR_EMPTY_TRASH');
JToolBarHelper::divider();
}
elseif ($canDo->get('core.edit.state'))
{
JToolBarHelper::trash('remove');
JToolBarHelper::divider();
}
}
function displayEdit($eventId,$tpl = NULL)
{
JToolBarHelper::title('Event'.': [<small>Edit</small>]');
JToolBarHelper::save();
JToolBarHelper::cancel();
$model = $this->getModel();
$event = $model->getEvent($eventId);
$this->event = $event;
parent::display($tpl);
}
function displayAdd($tpl = NULL){
JToolBarHelper::title('Event'.': [<small>Add</small>]');
JToolBarHelper::save();
JToolBarHelper::cancel();
parent::display($tpl);
}
}
default.php
<td colspan="9"><?php echo $this->pagination->getListFooter(); ?></td>
Can any help me what is wrong or what i am missing
This might be because the required Javascript frameworks aren't available. To ensure if this is the case, you can check your javascript console.
If that is the case, in your view extending JViewLegacy, before the line:
$this->pagination = $this->get('Pagination');
Insert below line:
JHtml::_('behavior.framework');
Also, make sure your template is not removing the required frameworks.
unset($doc->_scripts[JURI::root(true) . '/media/system/js/core.js']);
Comment out this line if you see it in your template index.php
Hope this helps :)
Extend class JModelList instead of JModelLegacy, that should sorry it out.
Related
So I've been stuck on this for quite a while, surprisingly the update and delete functions work just fine, however I cannot make the CREATE function work properly. Please have a look at it and tell me what I'm doing wrong
<-------------- Entire model for admin panel-------------->>>>>>>> Connection to DB is working fine---------->>>>>>>>>>>
<?php
include_once "Model.php";
class ModelPages extends Model {
public function get($key) {
$sql = "SELECT * from pages where page_key = '$key'";
$row = '';
$page = Null;
foreach ($this->pdo->query($sql) as $row) {
$page = $row;
}
// echo "<pre>";
// var_dump($page);
// exit;
return $page;
}
public function getAll() {
$statement = $this->pdo->prepare("SELECT * from pages Where Id > 3");
$result = $statement->execute();
$pages = array();
if($result) {
$pages = $statement->fetchAll(PDO::FETCH_ASSOC);
}
return $pages;
}
public function updatePage($params=array()) {
if (!is_array($params)) {
return 'Params should be an array';
}
if (isset($params['table'])) {
$tableName = $params['table'];
} else {
$tableName = 'pages';
}
$pageId = isset($params['page_key']) ? $params['page_key'] : null;
$pageTitle = isset($params['page_title']) ? $params['page_title'] : null;
$pageBody = isset($params['page_body']) ? $params['page_body'] : null;
if ($pageId == null) {
return 'No page id provided';
}
$sql = "UPDATE " . $tableName . " SET
title = :title,
body = :body
WHERE page_key = :page_key";
$statement = $this->pdo->prepare($sql);
$statement->bindParam(':title', $pageTitle, PDO::PARAM_STR);
$statement->bindParam(':body', $pageBody, PDO::PARAM_STR);
$statement->bindParam(':page_key', $pageId, PDO::PARAM_INT);
$result = $statement->execute();
return $result;
}
public function deletePage($pageId) {
// build sql
$sql = "DELETE FROM pages WHERE id = " . intval($pageId);
$statement = $this->pdo->prepare($sql);
$result = $statement->execute();
return $result;
}
public function createPage($params=array()){
if (!is_array($params)) {
return 'Params should be an array';
}
if (isset($params['table'])) {
$tableName = $params['table'];
} else {
$tableName = 'pages';
}
$page_key = isset($params['page_key']) ? $params['page_key'] : 'page_key';
$pageTitle = isset($params['page_title']) ? $params['page_title'] : 'page_title';
$pageBody = isset($params['page_body']) ? $params['page_body'] : 'page_body';
$sql = "INSERT INTO " . $tablename ." SET page_key=:page_key, title=:title, body=:body ";
// prepare query for execution
$statement = $this->pdo->prepare($sql);
// bind the parameters
$statement->bindParam(':page_key', $_POST['page_key']);
$statement->bindParam(':title', $_POST['title']);
$statement->bindParam(':body', $_POST['body']);
// specify when this record was inserted to the database
// Execute the query
$result = $statement->execute();
return $result;
}
}
<?php
include 'controllers/controller.php';
include 'models/Model.php';
include 'models/ModelPages.php';
<------------------------ADMIN CONTROller----------------------->>>>>>>>>>>>
class Admin extends Controller {
function __construct() {
// create an instance of ModelPages
$ModelPages = new ModelPages();
if(isset($_POST['page_key'])) {
// TODO: update DB
$tableData['page_body'] = $_POST['body'];
$tableData['table'] = 'pages';
$tableData['page_title'] = $_POST['title'];
$tableData['page_key'] = $_POST['page_key'];
$response = $ModelPages->updatePage($tableData);
if ($response == TRUE) {
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?page=admin&success=true");
}
}
if(isset($_GET['page_key'])) {
// by default we assume that the key_page exists in db
$error = false;
$page = $ModelPages->get($_REQUEST['page_key']);
// if page key does not exist set error to true
if($page === null) {
$error = true;
}
// prepare data for the template
$data = $page;
$data["error"] = $error;
// display
echo $this->render2(array(), 'header.php');
echo $this->render2(array(), 'navbar_admin.php');
echo $this->render2($data, 'admin_update_page.php');
echo $this->render2(array(), 'footer.php');
} else {
// case: delete_page
if(isset($_GET['delete_page'])) {
$response = $ModelPages->deletePage($_GET['delete_page']);
if($response == TRUE) {
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?page=admin&deleted=true");
}
}
}
//Get table name and make connection
if(isset($_POST['submit'])) {
$page_key = $_POST['page_key'];
$page_title = $_POST['title'];
$page_body = $_POST['body'];
$response = $ModelPages->createPage();
if($response=TRUE){
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?page=admin&created=true");
}
}
}
// load all pages from DB
$pages = $ModelPages -> getAll();
// display
echo $this->render2(array(), 'header_admin.php');
echo $this->render2(array(), 'navbar_admin.php');
echo $this->render2(array("pages"=> $pages), 'admin_view.php');
echo $this->render2(array(), 'footer.php');
}
}
?>
Since you have if(isset($_POST['page_key']) on the top:
class Admin extends Controller {
function __construct() {
// create an instance of ModelPages
$ModelPages = new ModelPages();
if(isset($_POST['page_key'])) {
...
if ($response == TRUE) {
header("http://188.166.96.184/workspace/marem/AAAAA/index.php?
}
and it is used to call $response = $ModelPages->updatePage($tableData);
your code never reach the part with good values at the bottom:
if(!isset($_POST['page_key'])) {
...
$response = $ModelPages->createPage($tableData);
So my simple but not the best suggestion is use extra parameter when POST like action. so you can check:
if(isset($_POST['action']) && $_POST['action']=='update') {
...
} elseif (isset($_POST['action']) && $_POST['action']=='create') {
...
} etc...
hope this will help you for now :-)
$sql = "INSERT INTO " . $tablename ." SET page_key=:page_key, title=:title, body=:body ";
$tablename is not in scope when the statement above is executed. And you've got no error handling in the code.
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
I'm creating a class in which MySQL queries will be generated automatically , but I've some problem ...
here is my Database class...
<?php
class Database {
var $host="localhost";
var $username="";
Var $password="";
var $database="";
var $fr_query;
var $row= array() ;
public function connect()
{
$conn= mysql_connect($this->host,$this->username,$this->password);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
}
public function db()
{
$conn_db = mysql_select_db($this->database);
if(! $conn_db )
{
echo 'Could Not Connect the Database';
}
}
public function run_query($sql)
{
$run = mysql_query($sql);
if(!$run)
{
throw new Exception("!!!!!Invalid query!!!!!!!");
}
$newId = mysql_insert_id();
if($newId)
{
return $newId;
}
return true;
}
public function fetchRow($fr)
{
if($fr)
{
$run = mysql_query($fr);
if($run)
{
return mysql_fetch_assoc($run);
}
}
return null;
}
function fetchAll($fr_query)
{
if($fr_query)
{
$run = mysql_query($fr_query);
if($run)
{
$data=array();
while($row=mysql_fetch_assoc($run))
{
$data[]=$row;
}
return $data;
}
}
return null;
}
}
$n = new Database();
$n->connect();
$n->db();
?>
and this is my test.php
<?php
include("database.php");
class Model_Abstract
{
protected $_data = array();
protected $_tableName = null;
protected $_primaryKey = null;
public function getTableName()
{
return $this->_tableName;
}
public function getPrimaryKey()
{
return $this->_primaryKey;
}
public function __set($key, $value = NULL)
{
$key = trim($key);
if(!$key)
{
throw new Exception('"$key" should not be empty.');
}
$this->_data[$key] = $value;
return $this;
}
public function __get($key)
{
$key = trim($key);
if(!$key)
{
throw new Exception('"$key" should not be empty.');
}
if(array_key_exists($key, $this->_data))
{
return $this->_data[$key];
}
return NULL;
}
public function insert()
{
print_r($this->_data);
$keyString = "`".implode("`,`", array_keys($this->_data))."`";
$valueString = "'".implode("','", array_keys($this->_data))."'";
echo $query = "INSERT INTO `{$this->getTableName()}` ({$keyString}) VALUES ({$valueString})";
$this->adpater()->run_query($query);
echo 'Inserted';
}
public function setData($data)
{
if(!is_array($data))
{
throw new Exception('"$data" should not be empty.');
}
$this->_data = $data;
return $this;
}
public function load($id, $key = null)
{
if(!is_int($id) && $id)
{
throw new Exception('"$id" should not be blank.');
}
if($id)
{
echo $query = "SELECT * FROM `{$this->getTableName()}` WHERE `{$this->getPrimaryKey()}` = '{$id}'";
$data[] = $this->adpater()->fetchRow($query);
$tabelName = $this->getTableName();
foreach($data as &$_data)
{
print_r($_data);
$object = new $tabelName();
$object->setData($_data);
$_data = $object;
}
print_r($data);
return $this;
/*
$query = "SELECT * FROM `{$this->getTableName()}` WHERE `{$this->getPrimaryKey()}` = '{$id}'";
$this->_data = $this->adpater()->fetchRow($query);
return $this; */
}
}
public function loadAll()
{
$query = "SELECT * FROM `{$this->getTableName()}`";
$data[] = $this->adpater()->fetchAll($query);
return $data;
}
public function delete($id, $key = null)
{
if(!is_int($id) && $id)
{
throw new Exception('"$id" should not be blank.');
}
if($id)
{
echo $query = "DELETE FROM `{$this->getTableName()}` WHERE `{$this->getPrimaryKey()}` = '{$id}'";
$data[] = $this->adpater()->run_query($query);
$tabelName = $this->getTableName();
$msg = 'Deleted Successfully....';
return $msg;
}
}
public function update()
{
print_r($this->_data);
$keyString = "`".implode("`,`", array_keys($this->_data))."`";
$valueString = "'".implode("','", array_keys($this->_data))."'";
echo $query = "UPDATE`{$this->getTableName()}` SET ({$keyString}) = ({$valueString}) WHERE `{$this->getPrimaryKey()}` = '{$id}'";
$this->adpater()->run_query($query);
echo 'Updated';
}
public function adpater()
{
return new Database();
}
}
class Product extends Model_Abstract
{
protected $_tableName = 'product';
protected $_primaryKey = 'product_id';
}
$product = new Product();
echo $product->name;
$product->insert();
print_r($product);
$product = new Product();
$product->name = 'Nokia Lumia';
$product->description = 'Windows';
$product->price = '15000';
$product->quantity = '12';
$product->sku = 'x2';
$product->status = '2';
$product->created_date = '0000-00-00 00:00:00';
$product->updated_date = ' ';
?>
So in here my problem is in Insert query, the values are same the column_name ...
I'm having Problem in loadAll();
the browser says "Catchable fatal error: Object of class Product could not be converted to string in"
$keyString = "`".implode("`,`", array_keys($this->_data))."`";
$valueString = "'".implode("','", array_keys($this->_data))."'";
Same lines, same value. Perhaps you meant
$keyString = "`".implode("`,`", array_keys($this->_data))."`";
$valueString = "'".implode("','", $this->_data) ."'";
Which would take the array keys for $keyString and the array values for $valueString.
Depreciation warning
mysql_* are deprecated functions. Use mysqli_* or PDO
Warning
This class does not protect you against SQL injections.
I'm writing a class and handful of functions to connect to the database and retrieve the information from the tables. I went through previous posts having similar titles, but most of them have written using mysql functions and I am using mysqli functions.
I want somebody who can go through this simple script and let me know where I am making my mistake.
This is my class.connect.php:
<?php
class mySQL{
var $host;
var $username;
var $password;
var $database;
public $dbc;
public function connect($set_host, $set_username, $set_password, $set_database)
{
$this->host = $set_host;
$this->username = $set_username;
$this->password = $set_password;
$this->database = $set_database;
$this->dbc = mysqli_connect($this->host, $this->username, $this->password, $this->database) or die('Error connecting to DB');
}
public function query($sql)
{
return mysqli_query($this->dbc, $sql) or die('Error querying the Database');
}
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql));
return $array;
}
public function close()
{
return mysqli_close($this->dbc);
}
}
?>
This is my index.php:
<?php
require_once ("class.connect.php");
$connection = new mySQL();
$connection->connect('localhost', 'myDB', 'joker', 'names_list');
$myquery = "SELECT * FROM list";
$query = $connection->query($myquery);
while($array = $connection->fetch($query))
{
echo $array['first_name'] . '<br />';
echo $array['last_name'] . '<br />';
}
$connection->close();
?>
I am getting the error saying that Error querying the Database.
Few problems :-
you don't die without provide a proper mysql error (and is good practice to exit gracefully)
fetch method is only FETCH the first row
mysqli have OO method, why you still using procedural function?
The problem is either this:
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql));
return $array;
}
or this:
while($array = $connection->fetch($query))
Because you are using the result from the query to query again. Basically, you are doing:
$r = mysqli_query($this->dbc, $sql);
$array = mysqli_fetch_array(mysqli_query($this->dbc, $r));
And you are getting an error, because $r is not a query string. When it's converted to a string, it's a "1" (from your other comment).
Try changing the function to (changed name of variable so you can see the difference):
public function fetch($result)
{
return mysqli_fetch_array($result);
}
or just call the function directly.
If you don't do your own db abstraction for learning php and mysql, you can use Medoo (http://medoo.in/).
It's a free and tiny db framework, that could save a huge work and time.
Obviously an error occurs on SELECT * FROM list you can use mysqli_error to find the error:
return mysqli_query($this->dbc, $sql) or die('Error:'.mysqli_error($this->dbc));
This will display the exact error message and will help you solve your problem.
Try to check this
https://pramodjn2.wordpress.com/
$database = new db();
$query = $database->select(‘user’);
$st = $database->result($query);
print_r($st);
class db {
public $server = ‘localhost';
public $user = ‘root';
public $passwd = ‘*****';
public $db_name = ‘DATABASE NAME';
public $dbCon;
public function __construct(){
$this->dbCon = mysqli_connect($this->server, $this->user, $this->passwd, $this->db_name);
}
public function __destruct(){
mysqli_close($this->dbCon);
}
/* insert function table name, array value
$values = array(‘first_name’ => ‘pramod’,’last_name’=> ‘jain’);
*/
public function insert($table,$values)
{
$sql = “INSERT INTO $table SET “;
$c=0;
if(!empty($values)){
foreach($values as $key=>$val){
if($c==0){
$sql .= “$key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= “, $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$c++;
}
}else{
return false;
}
$this->dbCon->query($sql) or die(mysqli_error());
return mysqli_insert_id($this->dbCon);
}
/* update function table name, array value
$values = array(‘first_name’ => ‘pramod’,’last_name’=> ‘jain’);
$condition = array(‘id’ =>5,’first_name’ => ‘pramod!’);
*/
public function update($table,$values,$condition)
{
$sql=”update $table SET “;
$c=0;
if(!empty($values)){
foreach($values as $key=>$val){
if($c==0){
$sql .= “$key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= “, $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$c++;
}
}
$k=0;
if(!empty($condition)){
foreach($condition as $key=>$val){
if($k==0){
$sql .= ” WHERE $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= ” AND $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$k++;
}
}else{
return false;
}
$result = $this->dbCon->query($sql) or die(mysqli_error());
return $result;
}
/* delete function table name, array value
$where = array(‘id’ =>5,’first_name’ => ‘pramod’);
*/
public function delete($table,$where)
{
$sql = “DELETE FROM $table “;
$k=0;
if(!empty($where)){
foreach($where as $key=>$val){
if($k==0){
$sql .= ” where $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= ” AND $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$k++;
}
}else{
return false;
}
$del = $result = $this->dbCon->query($sql) or die(mysqli_error());
if($del){
return true;
}else{
return false;
}
}
/* select function
$rows = array(‘id’,’first_name’,’last_name’);
$where = array(‘id’ =>5,’first_name’ => ‘pramod!’);
$order = array(‘id’ => ‘DESC’);
$limit = array(20,10);
*/
public function select($table, $rows = ‘*’, $where = null, $order = null, $limit = null)
{
if($rows != ‘*’){
$rows = implode(“,”,$rows);
}
$sql = ‘SELECT ‘.$rows.’ FROM ‘.$table;
if($where != null){
$k=0;
foreach($where as $key=>$val){
if($k==0){
$sql .= ” where $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}else{
$sql .= ” AND $key='”.htmlentities($val, ENT_QUOTES).”‘”;
}
$k++;
}
}
if($order != null){
foreach($order as $key=>$val){
$sql .= ” ORDER BY $key “.htmlentities($val, ENT_QUOTES).””;
}
}
if($limit != null){
$limit = implode(“,”,$limit);
$sql .= ” LIMIT $limit”;
}
$result = $this->dbCon->query($sql);
return $result;
}
public function query($sql){
$result = $this->dbCon->query($sql);
return $result;
}
public function result($result){
$row = $result->fetch_array();
$result->close();
return $row;
}
public function row($result){
$row = $result->fetch_row();
$result->close();
return $row;
}
public function numrow($result){
$row = $result->num_rows;
$result->close();
return $row;
}
}
The mysqli_fetch_array function in your fetch method requires two parameters which are the SQL result and the kind of array you intend to return. In my case i use MYSQLI_ASSOC.
That is it should appear like this:
public function fetch($sql)
{
$array = mysqli_fetch_array($this->query($sql), MYSQLI_ASSOC);
return $array;
}
**classmysql.inc.php**
<?php
class dbclass {
var $CONN;
function dbclass() { //constructor
$conn = mysql_connect(SERVER_NAME,USER_NAME,PASSWORD);
//$conn = mysql_connect(localhost,root,"","");
if(!$conn)
{ $this->error("Connection attempt failed"); }
if(!mysql_select_db(DB_NAME,$conn))
{ $this->error("Database Selection failed"); }
$this->CONN = $conn;
return true;
}
//_____________close connection____________//
function close(){
$conn = $this->CONN ;
$close = mysql_close($conn);
if(!$close){
$this->error("Close Connection Failed"); }
return true;
}
function error($text) {
$no = mysql_errno();
$msg = mysql_error();
echo "<hr><font face=verdana size=2>";
echo "<b>Custom Message :</b> $text<br><br>";
echo "<b>Error Number :</b> $no<br><br>";
echo "<b>Error Message :</b> $msg<br><br>";
echo "<hr></font>";
exit;
}
//_____________select records___________________//
function select ($sql=""){
if(empty($sql)) { return false; }
if(!eregi("^select",$sql)){
echo "Wrong Query<hr>$sql<p>";
return false; }
if(empty($this->CONN)) { return false; }
$conn = $this->CONN;
$results = #mysql_query($sql,$conn);
if((!$results) or empty($results)) { return false; }
$count = 0;
$data = array();
while ( $row = mysql_fetch_array($results)) {
$data[$count] = $row;
$count++; }
mysql_free_result($results);
return $data;
}
//________insert record__________________//
function insert ($sql=""){
if(empty($sql)) { return false; }
if(!eregi("^insert",$sql)){ return false; }
if(empty($this->CONN)){ return false; }
$conn = $this->CONN;
$results = #mysql_query($sql,$conn);
if(!$results){
$this->error("Insert Operation Failed..<hr>$sql<hr>");
return false; }
$id = mysql_insert_id();
return $id;
}
//___________edit and modify record___________________//
function edit($sql="") {
if(empty($sql)) { return false; }
if(!eregi("^update",$sql)){ return false; }
if(empty($this->CONN)){ return false; }
$conn = $this->CONN;
$results = #mysql_query($sql,$conn);
$rows = 0;
$rows = #mysql_affected_rows();
return $rows;
}
//____________generalize for all queries___________//
function sql_query($sql="") {
if(empty($sql)) { return false; }
if(empty($this->CONN)) { return false; }
$conn = $this->CONN;
$results = mysql_query($sql,$conn) or $this->error("Something wrong in query<hr>$sql<hr>");
if(!$results){
$this->error("Query went bad ! <hr>$sql<hr>");
return false; }
if(!eregi("^select",$sql)){return true; }
else {
$count = 0;
$data = array();
while ( $row = mysql_fetch_array($results))
{ $data[$count] = $row;
$count++; }
mysql_free_result($results);
return $data;
}
}
function extraqueries($sql="") {
if(empty($sql)) { return false; }
if(empty($this->CONN)) { return false; }
$conn = $this->CONN;
$results = mysql_query($sql,$conn) or $this->error("Something wrong in query<hr>$sql<hr>");
if(!$results){
$this->error("Query went bad ! <hr>$sql<hr>");
return false; }
else {
$count = 0;
$data = array();
while ( $row = mysql_fetch_array($results))
{ $data[$count] = $row;
$count++; }
mysql_free_result($results);
return $data;
}
}
}
?>
**config.inc.php**
<?php
ini_set("memory_limit","70000M");
ini_set('max_execution_time', 900);
ob_start();
session_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
############################################
# Database Server
############################################
if($_SERVER['HTTP_HOST']=="localhost")
{
define("DB_NAME","DB_NAME");
define("SERVER_NAME","SERVER_NAME");
define("USER_NAME","USER_NAME");
define("PASSWORD","PASSWORD");
}
else
{
define("DB_NAME","DB_NAME");
define("SERVER_NAME","SERVER_NAME");
define("USER_NAME","USER_NAME");
define("PASSWORD","PASSWORD");
}
#############################################
# File paths
#############################################
// For the Database file path
include("system/classmysql.inc.php");
//For the inc folders
define("INC","inc/");
//For the Function File of the pages folders
define("FUNC","func/");
//For the path of the system folder
define("SYSTEM","system/");
$table_prefix = 'dep_';
################################################################
# Database Class
################################################################
$obj_db = new dbclass();
?>
**Function Page**
<?php
// IF admin is not logged in
if(!isset($_SESSION['session_id']))
{
header("location:index.php");
}
$backpage = 'page.php?type=staff&';
if(isset($_REQUEST['endbtn']) && trim($_REQUEST['endbtn']) == "Back")
{
header("location:".$backpage);
die();
}
// INSERT into database.
if(isset($_REQUEST['submit']) && trim($_REQUEST['submit']) == "Submit")
{
$pass = addslashes(trim($_REQUEST['password']));
$password = encrypt($pass, "deppro");
$username = addslashes(trim($_REQUEST['username']));
$sql = "select * from ".$table_prefix."users where `UserName` ='".$username."'";
$result = $obj_db->select($sql);
if(count($result) == 0)
{
$insert="INSERT INTO ".$table_prefix."users (`UserName`)VALUES ('".$username."')";
$sql=$obj_db->insert($insert);
$newuserid = mysql_insert_id($obj_db->CONN);
}
header("location:".$backpage."msg=send&alert=2");
die();
}
// DELETE record from database
if(isset($_REQUEST['action']) && trim($_REQUEST['action'])==3)
{
if(isset($_REQUEST['id']) && trim($_REQUEST['id']!=""))
{
$id = site_Decryption($_REQUEST['id']);
$sql_del = "Delete from ".$table_prefix."users where StaffID ='$id'";
$del = $obj_db->sql_query($sql_del);
header("location:".$backpage."msg=delete&alert=2");
die();
}
}
// UPDATE the record
$action=1;
if((isset($_REQUEST['action']) && trim($_REQUEST['action'])==2) && (!(isset($_REQUEST['submit']) && trim($_REQUEST['submit']) == "Submit")))
{
if(isset($_REQUEST['id']) && trim($_REQUEST['id']!=""))
{
$id = site_Decryption($_REQUEST['id']);
//$id = $_SESSION['depadmin_id'];
$sql = "select * from ".$table_prefix."users where StaffID ='$id'";
$result = $obj_db->select($sql);
if($result)
{
foreach($result as $row)
{
$title = stripslashes($row['StaffTitle']);
$action=2;
}
}
if(isset($_REQUEST['submit']) && trim($_REQUEST['submit']) == "Update")
{
$title = addslashes(trim($_REQUEST['title']));
$sql_upd ="UPDATE ".$table_prefix."users SET `StaffTitle` = '$title' WHERE StaffID ='$id'";
$result = $obj_db->sql_query($sql_upd);
$action=1;
header("location:".$backpage."msg=edited&alert=2");
die();
}
}
}
if(isset($_REQUEST['vid']) && trim($_REQUEST['vid']!=""))
{
$id = site_Decryption($_REQUEST['vid']);
$sql = "select * from ".$table_prefix."users where StaffID ='$id'";
$result = $obj_db->select($sql);
if($result)
{
foreach($result as $row)
{
$username = stripslashes($row['UserName']);
}
}
}
?>
<td class="center"><span class="editbutton"> </span> <span class="deletebutton"> </span> <a class="lightbox" title="View" href="cpropertyview.php?script=view&vid=<?php echo site_Encryption($sql[$j]['PropertyID']); ?>&lightbox[width]=55p&lightbox[height]=60p"><span class="viewbutton"> </span></a></td>
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]