PHP/MySQL poll - no repeat voting based on IP - php

I have a php/mysql poll that I'm trying to modify.
It sets a unique cookie if you've voted and blocks you from voting twice on the same poll if the cookie is set. If it set then you can only see the results.
What I would like to do is block the user from voting more than once if their IP is in the database as well (I know sessions would be better but not possible for my situation).
I've managed to grab the IP and store it in the db but I can't figure out the logic to tell the poll if it's in the database or not.
Can someone point me in the right direction?
The cookie detection is in the constructor and vote methods. The cookie is set at the end of the vote method.
<?php
# don't display errors
ini_set('display_errors',0);
error_reporting(E_ALL|E_STRICT);
class webPoll {
# makes some things more readable later
const POLL = true;
const VOTES = false;
# number of pixels for 1% on display bars
public $scale = 2;
public $question = '';
public $answers = array();
private $header = '<form class="webPoll" method="post" action="%src%">
<input type="hidden" name="QID" value="%qid%"/>
<h4>%question%</h4>
<fieldset><ul>';
private $center = '';
private $footer = "\n</ul></fieldset>%button%\n%totalvotes%\n</form>\n";
private $button = '<p class="buttons"><button type="submit" class="vote">Vote!</button></p>';
private $totalvotes = '';
private $md5 = '';
private $id = '';
/**
* ---
* Takes an array containing the question and list of answers as an
* argument. Creates the HTML for either the poll or the results depending
* on if the user has already voted
*/
public function __construct($params) {
$this->id = array_shift($params);
$this->question = array_shift($params);
$this->answers = $params;
$this->md5 = md5($this->id);
$this->header = str_replace('%src%', $_SERVER['SCRIPT_NAME'], $this->header);
$this->header = str_replace('%qid%', $this->md5, $this->header);
$this->header = str_replace('%question%', $this->question, $this->header);
# seperate cookie for each individual poll (has the user voted yet?)
# if cookie is set then show results(VOTES), if not then let user vote(POLL)
isset($_COOKIE[$this->md5]) ? $this->poll(self::VOTES) : $this->poll(self::POLL);
}
private function poll($show_poll) {
$replace_btn = $show_poll ? $this->button : '';
$get_results = webPoll::getData($this->md5);
$total_votes = array_sum($get_results);
$replace_votes = $show_poll ? $this->totalvotes : '<small>Total Votes: '.$total_votes.'</small>';
$this->footer = str_replace('%button%', $replace_btn, $this->footer);
$this->footer = str_replace('%totalvotes%', $replace_votes, $this->footer);
# static function doesn't have access to instance variable
if(!$show_poll) {
$results = webPoll::getData($this->md5);
$votes = array_sum($results);
}
for( $x=0; $x<count($this->answers); $x++ ) {
$this->center .= $show_poll ? $this->pollLine($x) : $this->voteLine($this->answers[$x],$results[$x],$votes);
}
echo $this->header, $this->center, $this->footer;
}
private function pollLine($x) {
isset($this->answers[$x+1]) ? $class = 'bordered' : $class = '';
return "
<li class='$class'>
<label class='poll_active'>
<input type='radio' name='AID' value='$x' />
{$this->answers[$x]}
</label>
</li>
";
}
private function voteLine($answer,$result,$votes) {
$result = isset($result) ? $result : 0;
$percent = round(($result/$votes)*100);
$width = $percent * $this->scale;
return "
<li>
<div class='result' style='width:{$width}px;'> </div>{$percent}%
<label class='poll_results'>
$answer
</label>
</li>
";
}
/**
* processes incoming votes. votes are identified in the database by a combination
* of the question's MD5 hash, and the answer # ( an int 0 or greater ).
*/
static function vote() {
if(!isset($_POST['QID']) || !isset($_POST['AID']) || isset($_COOKIE[$_POST['QID']])) {
# leave vote method if any of the above are true
return;
}
$dbh = new PDO('mysql:host=????;dbname=????', '????', '');
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
try {
# add vote info to 'tally' table
$sth = $dbh->prepare("INSERT INTO tally (QID,AID,votes,created_at) values (?, ?, 1, NOW())");
$ex = array($_POST['QID'],$_POST['AID']);
$sth->execute($ex);
# add ip info to 'ips' table
$sth2 = $dbh->prepare("INSERT INTO ips (ips,QID,AID) values (?,?,?)");
$ex2 = array($_SERVER['REMOTE_ADDR'],$_POST['QID'],$_POST['AID']);
$sth2->execute($ex2);
}
catch(PDOException $e) {
# 23000 error code means the key already exists, so UPDATE!
if($e->getCode() == 23000) {
try {
# update number of votes for answers in 'tally' table
$sth = $dbh->prepare("UPDATE tally SET votes = votes+1 WHERE QID=? AND AID=?");
$sth->execute(array($_POST['QID'],$_POST['AID']));
# add ip info to 'ips' table
$sth2 = $dbh->prepare("INSERT INTO ips (ips,QID,AID) values (?,?,?)");
$ex2 = array($_SERVER['REMOTE_ADDR'],$_POST['QID'],$_POST['AID']);
$sth2->execute($ex2);
}
catch(PDOException $e) {
webPoll::db_error($e->getMessage());
}
}
else {
webPoll::db_error($e->getMessage());
}
}
# entry in $_COOKIE to signify the user has voted, if he has
if($sth->rowCount() == 1) {
setcookie($_POST['QID'], 1, time()+60*60*24*365, '/', '', FALSE, TRUE);
$_COOKIE[$_POST['QID']] = 1;
}
}
static function getData($question_id) {
try {
$dbh = new PDO('mysql:host=????;dbname=????', '????', '');
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$STH = $dbh->prepare('SELECT AID, votes FROM tally WHERE QID = ?');
$STH->execute(array($question_id));
}
catch(PDOException $e) {
# Error getting data, just send empty data set
return array(0);
}
while($row = $STH->fetch()) {
$results[$row['AID']] = $row['votes'];
}
return $results;
}
/*
* You can do something with the error message if you like. Email yourself
* so you know something happened, or make an entry in a log
*/
static function db_error($error) {
echo "A database error has occurred. $error";
exit;
}
}
?>
And here's how the poll is implemented:
<?php
ini_set('display_errors',1);
error_reporting(E_ALL|E_STRICT);
include('webPoll-hiddenMD5.class.php');
webPoll::vote();
?>
<html>
<head>
<title>Poll Test</title>
<link rel="stylesheet" href="poll.css" type="text/css" />
<!--[if IE]>
<style> body { behavior: url("res/hover.htc"); } </style>
<![endif]-->
</head>
<body>
<?php
$a1 = new webPoll(array(
'March 16, 2012 What subjects would you like to learn more about?',
'What subjects would you like to learn more about?',
'HTML & CSS',
'Javascript',
'JS Frameworks (Jquery, etc)',
'Ruby/Ruby on Rails',
'PHP',
'mySQL'));
?>
</body>
</html>

Looks as if all your logic is in the constructor, simply do a query against the ip table for the users ip and qid and see if the number of results is greater then 0. If so then just change the last line of the constructor isset($_COOKIE[$this->md5] || count($res)>0 ) ? $this->poll(self::VOTES) : $this->poll(self::POLL);

Related

Data not being saved in my database

I hope you are doing great. I'm having a problem where I cannot insert data into my database. There are multiple reasons to why that happens so don't consider it a duplicate question please. I checked my code. For one table it saves the data but for this table. It displays that the same page was not found and no data is saved on the local database. I hope you can help me guys. Thanks in advance. :)
Here are some useful pieces of code:
<?php
include 'Header.php';
?>
<style>
#first {
//margin-right: 100%;
//clear: both;
}
#first > img {
display: inline-block;
//float: left;
}
#first > p {
//float: left;
display: inline-block;
//margin-left: 60px;
//margin-bottom: 120px;
}
</style>
<!-- Post content here -->
<!-- Then cmments below -->
<h1>Comments</h1>
<!--<?php ?>
if (isset($_GET['id'])) {
$id = $_GET['id'];
} elseif (isset($_POST['id'])) {
$id = $_POST['id'];
} else {
echo '<p class="error"> Error has occured</p>';
include 'footer.html';
exit();
}
$db = new Database();
$dbc = $db->getConnection();
$display = 10; //number of records per page
$pages;
if(isset($_GET['p']) ) //already calculated
{
$pages=$_GET['p'];
}
else
{
//use select count() to find the number of users on the DB
$q = "select count(comment_id) from comments";
$r = mysqli_query($dbc, $q);
$row = mysqli_fetch_array($r, MYSQLI_NUM);
$records=$row[0];
if($records > $display ) //calculate the number of pages we will need
$pages=ceil($records/$display);
else
$pages = 1;
}
//now determine where in the database to start
if(isset($_GET['s']) ) //already calculated
$start=$_GET['s'];
else
$start = 0;
//use LIMIT to specify a range of records to select
// for example LIMIT 11,10 will select the 10 records starting from record 11
$q = "select * from users order by $orderby LIMIT $start, $display";
$r = mysqli_query($dbc, $q);
/*if ($r)
{*/
$result = mysql_query("SELECT * FROM comments WHERE video_id= '" + + "'");
//0 should be the current post's id
while($row = mysql_fetch_object($result))
{
?>
<div class="comment">
By: <!--<?php /* echo $row->author; //Or similar in your table ?>
<p>
<?php echo $row->body; ?>
</p>
</div>
<?php
/*} */
?>*/-->
<h1>Leave a comment:</h1>
<form action="Comment.php" method="post">
<!-- Here the shit they must fill out -->
<input type="text" name="comment" value="" />
<input type="hidden" name="submitted" value="TRUE" />
<input type="submit" name="submit" value="Insert"/>
</form>';
<?php
if (isset($_POST['submitted'])) {
$comment = '';
$errors = array();
if (empty($_POST['comment']))
$errors[] = 'You should enter a comment to be saved';
else
$comment = trim($_POST['comment']);
if (empty($errors)) {
include 'Comments_1.php';
$comment_2 = new Comments();
$errors = $comment_2->isValid();
$comment_2->Comment = trim($_POST['comment']);
$comment_2->UserName = hamed871;
$comment_2->Video_Id = 1;
if ($comment_2->save()) {
echo '<div class="div_1"><div id="div_2">' .
'<h1>Thank you</h1><p> your comment has been'
. ' posted successfully</p></div></div>';
}
}
//First check if everything is filled in
/* if(/*some statements *//* )
{
//Do a mysql_real_escape_string() to all fields
//Then insert comment
mysql_query("INSERT INTO comments VALUES ($author,$postid,$body,$etc)");
}
else
{
die("Fill out everything please. Mkay.");
}
?>
id (auto incremented)
name
email
text
datetime
approved--> */
}
?>
<!--echo '--><div id="first">
<img src="http://www.extremetech.com/wp-content/uploads/2013/11/emp-blast.jpg?type=square" height="42" width="42"/>
<p>hamed1</p>
</div><!--';-->
<dl>
<dt>comment1</dt>
<dd>reply1</dd>
<dd>reply2</dd>
</dl>
<!--//}
/*else
{
}*/
?>-->
<?php
include 'Footer.php';
?>
My Comment class:
<?php
include_once "DBConn.php";
class Comments extends DBConn {
private $tableName = 'Comments';
//attributes to represent table columns
public $comment_Id = 0;
public $Comment;
public $UserName;
public $Video_Id;
public $Date_Time;
public function save() {
if ($this->getDBConnection()) {
//escape any special characters
$this->Comment = mysqli_real_escape_string($this->dbc, $this->Comment);
$this->UserName = mysqli_real_escape_string($this->dbc, $this->UserName);
$this->Video_Id = mysqli_real_escape_string($this->dbc, $this->Video_Id);
if ($this->comment_Id == null) {
$q = 'INSERT INTO comments(Comment, User_Id, Video_Id, Date_Time) values' .
"('" . $this->Comment . "','" . $this->User_Id . "','" . $this->Video_Id . "',NOW()')";
} else {
$q = "update Comments set Comment='" . $this->Comment . "', Date_Time='" . NOW() ."'";
}
// $q = "call SaveUser2($this->userId,'$this->firstName','$this->lastName','$this->email','$this->password')";
$r = mysqli_query($this->dbc, $q);
if (!$r) {
$this->displayError($q);
return false;
}
return true;
} else {
echo '<p class="error">Could not connect to database</p>';
return false;
}
return true;
}
//end of function
public function get($video_id) {
if ($this->getDBConnection()) {
$q = "SELECT Comment, Date_Time, UserName FROM Comments WHERE Video='" . $userName."' order by time_stamp";
$r = mysqli_query($this->dbc, $q);
if ($r) {
$row = mysqli_fetch_array($r);
$this->Comment = mysqli_real_escape_string($this->dbc, $this->Comment);
return true;
}
else
$this->displayError($q);
}
else
echo '<p class="error">Could not connect to database</p>';
return false;
}
public function isValid() {
//declare array to hold any errors messages
$errors = array();
if (empty($this->Comment))
$errors[] = 'You should enter a comment to be saved';
return $errors;
}
}
?>
Output show when I click insert button:
Not Found
The requested URL /IndividualProject/Comment.php was not found on this server.
Apache/2.4.17 (Win64) PHP/5.6.16 Server at localhost Port 80
I encountered this kind of issue when working on a staging site because webhosting may have different kinds of restrictions and strict. Now what I did is changing the filename for example:
Class name should match the filename coz it's case sensitive.
Comment.php
class Comment extends DBConn {
function __construct () {
parent::__construct ();
}
//code here..
}

Ajax auto refresh - PHP variables not passing correctly into auto refresh function

I'm using Eliza Witkowska's Ajax Auto Refresh code: http://blog.codebusters.pl/en/entry/ajax-auto-refresh-volume-ii
I've altered the code so I can pass variables from the url. It all works great except for one line of code. The line of code is part of a database query that checks for new records. When I try to pass my variables into the query the auto refresh stops working (all other functionality continues to work). If I use static values it works fine.
static values (this works)
$result = $this->db->query('SELECT counting FROM chats WHERE id=1 AND AgentID=3 AND UserID=25');
with variables (this doesn't work)
$result = $this->db->query('SELECT counting FROM chats WHERE id=1 AND AgentID='.$AgentID.' AND UserID='.$UserID.'');
There are no problems passing variables into another function in the same script. So I'm stuck and have been for a few days. Any help with be appreciated.
db.php
class db{
/**
* db
*
* #var $ public $db;
*/
public $db;
function __construct(){
$this->db_connect('###SERVER###','###USERNAME###','###PASSWORD###','###DATABASE###'); //my database information
}
function db_connect($host,$user,$pass,$database){
$this->db = new mysqli($host, $user, $pass, $database);
if($this->db->connect_errno > 0){
die('Unable to connect to database [' . $this->db->connect_error . ']');
}
}
//////////////////////////////
//This is the function that is having an issue when I pass it variables
//////////////////////////////
function check_changes(){
global $UserID; //Declaring my variable
global $AgentID; //Declaring my variable
$result = $this->db->query('SELECT counting FROM chats WHERE id=1 AND AgentID='.$AgentID.' AND UserID='.$UserID.'');
if($result = $result->fetch_object()){
return $result->counting;
}
return 0;
}
//////////////////////////////
//This function has no problem, even when I pass it variables
//////////////////////////////
function get_news(){
global $UserID;
global $AgentID;
if($result = $this->db->query('SELECT * FROM chats WHERE id<>1 AND AgentID='.$AgentID.' AND UserID='.$UserID.' ORDER BY add_date ASC LIMIT 50')){
$return = '';
while($r = $result->fetch_object()){
if ($r->ChatType==1) { //ChatType is a field in the table that distinguishes Agent texts from User Texts
$return .= ''.htmlspecialchars($r->title).'';
} else {
$return .= '<div align="right">'.htmlspecialchars($r->title).'</div>';
}
}
return $return;
}
}
}
Here are the other files:
index.php
<?php
$AgentID = $_REQUEST["AgentID"]; //Grabing AgentID from the URL
$UserID = $_REQUEST["UserID"]; //Grabing UserID from the URL
require('common.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Admin</title>
<script src="jquery-1.10.2.min.js"></script>
<script>
/* AJAX request to checker */
function check(){
$.ajax({
type: 'POST',
url: 'checker.php?AgentID=<? echo $AgentID; ?>&UserID=<? echo $UserID; ?>', //This line has been updated by passing parameters
dataType: 'json',
data: {
counter:$('#message-list').data('counter')
}
}).done(function( response ) {
/* update counter */
$('#message-list').data('counter',response.current);
/* check if with response we got a new update */
if(response.update==true){
$('#message-list').html(response.news);
var audio = new Audio('img/solemn.mp3');
audio.play();
}
});
}
//Every 2 sec check if there is new update
setInterval(check,2000);
</script>
<style>
body {
margin:0px;
padding:0px;
vertical-align:top;
}
</style>
</head>
<body>
<?php /* Our message container. data-counter should contain initial value of counter from database */ ?>
<br>
<div id="message-list" data-counter="<?php echo (int)$db->check_changes();?>">
<?php echo $db->get_news();?>
</div>
</body>
</html>
checker.php
<?php require('common.php');
//get current counter
$data['current'] = (int)$db->check_changes();
//set initial value of update to false
$data['update'] = false;
//check if it's ajax call with POST containing current (for user) counter;
//and check if that counter is diffrent from the one in database
if(isset($_POST) && !empty($_POST['counter']) && (int)$_POST['counter']!=$data['current']){
$AgentID = $_REQUEST["AgentID"]; //passing my variable to db.php
$UserID = $_REQUEST["UserID"]; //passing my variable to db.php
$data['news'] = $db->get_news();
$data['update'] = true;
}
//just echo as JSON
echo json_encode($data);
/* End of file checker.php */
?>
common.php
<?php
require_once ('db.php'); //get our database class
$db = new db();
/* end of file common.php */
?>
I think the problem was that the variables were not available at the time of including the database connection in checker.php ~ declare the variables and then include the db connection.
Also, I'd suggest that instead of using the global expression to define the variables within your db class methods that you pass them as parameters instead. I hope the following might be of use - it's not tested though. There are, or should be, concerns with this method of using variables within sql - it is vulnerable to the dreaded sql injection ~ better would be to use prepared statements within the db class and bind the $agentID and $UserID with the bind_param() method.
<?php
/* common.php */
$dbhost = 'xxx';
$dbuser = 'xxx';
$dbpwd = 'xxx';
$dbname = 'xxx';
require_once 'db.php';
$db = new db( $dbhost, $dbuser, $dbpwd, $dbname );
?>
<?php
/* database class: db.php */
class db{
private $db;
public function __construct( $dbhost, $dbuser, $dbpwd, $dbname ){
$this->db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
if( $this->db->connect_errno > 0 ) exit('Unable to connect to database [' . $this->db->connect_error . ']');
}
public function check_changes( $AgentID=false, $UserID=false ){
if( $AgentID && $UserID ){
$result = $this->db->query('SELECT counting FROM chats WHERE id=1 AND AgentID='.$AgentID.' AND UserID='.$UserID.'');
if($result = $result->fetch_object()){
return $result->counting;
}
}
return 0;
}
public function get_news( $AgentID, $UserID ){
$return = '';
if( $AgentID && $UserID ){
if( $result = $this->db->query('SELECT * FROM chats WHERE id<>1 AND AgentID='.$AgentID.' AND UserID='.$UserID.' ORDER BY add_date ASC LIMIT 50' ) ){
while( $r = $result->fetch_object() ){
if ($r->ChatType==1) {
$return .= ''.htmlspecialchars($r->title).'';
} else {
$return .= '<div align="right">'.htmlspecialchars($r->title).'</div>';
}
}
}
return $return;
}
}
}
?>
<?php
/* Checker.php */
$AgentID = isset( $_REQUEST["AgentID"] ) ? $_REQUEST["AgentID"] : false;
$UserID = isset( $_REQUEST["UserID"] ) ? $_REQUEST["UserID"] : false;
if( $AgentID && $UserID ){
/* Do SOME filtering of user supplied data */
$AgentID=filter_var( $AgentID, FILTER_SANITIZE_NUMBER_INT, array( 'options' => array('default' => 0, 'min_range' => 0 ) ) );
$UserID=filter_var( $UserID, FILTER_SANITIZE_NUMBER_INT, array( 'options' => array('default' => 0, 'min_range' => 0 ) ) );
require 'common.php';
$data['current'] = (int)$db->check_changes( $AgentID, $UserID );
$data['update'] = false;
if( isset($_POST) && !empty($_POST['counter']) && (int)$_POST['counter']!=$data['current'] ){
$data['news'] = $db->get_news( $AgentID, $UserID );
$data['update'] = true;
}
echo json_encode($data);
}
?>
<?php
$AgentID = isset( $_REQUEST["AgentID"] ) ? $_REQUEST["AgentID"] : false;
$UserID = isset( $_REQUEST["UserID"] ) ? $_REQUEST["UserID"] : false;
$AgentID=filter_var( $AgentID, FILTER_SANITIZE_NUMBER_INT, array( 'options' => array('default' => 0, 'min_range' => 0 ) ) );
$UserID=filter_var( $UserID, FILTER_SANITIZE_NUMBER_INT, array( 'options' => array('default' => 0, 'min_range' => 0 ) ) );
require 'common.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Admin</title>
<script src="jquery-1.10.2.min.js"></script>
<script>
<?php
echo "
var aid={$AgentID};
var uid={$UserID};";
?>
function check(){
$.ajax({
type:'POST',
url:'checker.php?AgentID='+aid+'&UserID='+uid,
dataType:'json',
data:{ counter:$('#message-list').data('counter') }
}).done( function( response ) {
/* update counter */
$('#message-list').data('counter',response.current);
/* check if with response we got a new update */
if(response.update==true){
$('#message-list').html(response.news);
var audio = new Audio('img/solemn.mp3');
audio.play();
}
});
}
setInterval(check,2000);
</script>
<style>
body {
margin:0px;
padding:0px;
vertical-align:top;
}
</style>
</head>
<body>
<br>
<div id="message-list" data-counter="<?php echo (int)$db->check_changes($AgentID, $UserID); ?>">
<?php echo $db->get_news($AgentID, $UserID);?>
</div>
</body>
</html>

displaying server error messages on UI in php

I am very new to php programming. I have written a sign up html file where the user enters his email and password. If the user has already registered, I am redirecting to sign-in screen and if the user is new use, I am persisting in the database. Now if the user enters wrong password, he will again be redirected to sign-in screen but this time I want to show a message on the screen, that the password entered is incorrect. The sign in screen should not display the message when the user navigates directly to the sign in screen.
The code snippet is shown below:
<?php
define('DB_HOST', 'hostname');
define('DB_NAME', 'db_name');
define('DB_USER','username');
define('DB_PASSWORD','password');
$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());
function NewUser() {
$email = $_POST['email'];
$password = $_POST['password'];
$query = "INSERT INTO WebsiteUsers (email,pass) VALUES ('$email','$password')";
$data = mysql_query ($query)or die(mysql_error());
if($data) {
header('Location: reg-success.html');
}
}
function SignUp() {
if(!empty($_POST['email'])){
$emailQuery = mysql_query("SELECT * FROM WebsiteUsers WHERE email = '$_POST[email]'");
if($row = mysql_fetch_array($emailQuery)) {
$query = mysql_query("SELECT * FROM WebsiteUsers WHERE email = '$_POST[email]' AND pass = '$_POST[password]'");
if($row = mysql_fetch_array($query)) {
echo 'validated user. screen that is accessible to a registered user';
}else{
echo 'Redirect to the sign in screen with error message';
}
}else{
NewUser();
}
}
}
if(isset($_POST['submit']))
{
SignUp();
}
?>
Please let me know how to get this implementation using php
Here are a couple of classes that may help you prevent injection hacks plus get you going on how to do what you are trying to do in general. If you create classes for your tasks, it will be easier to re-use what your code elsewhere. I personally like the PDO method to connect and grab info from a DB (you will want to look up "binding" to help further prevent injection attacks), but this will help get the basics down. This is all very rough and you would want to expand out to create some error reporting and more usable features.
<?php
error_reporting(E_ALL);
// Create a simple DB engine
class DBEngine
{
protected $con;
// Create a default database element
public function __construct($host = '',$db = '',$user = '',$pass = '')
{
try {
$this->con = new PDO("mysql:host=$host;dbname=$db",$user,$pass, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING));
}
catch (Exception $e) {
return 0;
}
}
// Simple fetch and return method
public function Fetch($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
if($query->rowCount() > 0) {
$rows = $query->fetchAll();
}
return (isset($rows) && $rows !== 0 && !empty($rows))? $rows: 0;
}
// Simple write to db method
public function Write($_sql)
{
$query = $this->con->prepare($_sql);
$query->execute();
}
}
// Your user controller class
class UserControl
{
public $_error;
protected $db;
// Save the database connection object for use in this class
public function __construct($db)
{
$this->_error = array();
$this->db = $db;
}
// Add user to DB
protected function Add()
{
$email = htmlentities($_POST['email'],ENT_QUOTES);
// Provided you have a php version that supports better encryption methods, use that
// but you should do at least a very basic password encryption.
$password = hash('sha512',$_POST['password']);
// Use our handy DBEngine writer method to write your sql
$this->db->Write("INSERT INTO WebsiteUsers (`email`,`pass`) VALUES ('$email','$password')");
}
// Fetch user from DB
protected function Fetch($_email = '')
{
$_email = htmlentities($_email,ENT_QUOTES);
$password = hash('sha512',$_POST['password']);
// Use our handy DBEngine fetcher method to check your db
$_user = $this->db->Fetch("SELECT * FROM WebsiteUsers WHERE email = '$_email' and password = '$password'");
// Return true if not 0
return ($_user !== 0)? 1:0;
}
// Simple fetch user or set user method
public function execute()
{
// Check that email is a valid format
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
// Save the true/false to error reporting
$this->_error['user']['in_db'] = $this->Fetch($_POST['email']);
// Asign short variable
$_check = $this->_error['user']['in_db'];
if($_check !== 1) {
// Add user if not in system
$this->Add();
// You'll want to expand your add feature to include error reporting
// This is just returning that it made it to this point
$this->_error['user']['add_db'] = 1;
}
else {
// Run some sort of login script
}
// Good email address
$this->_error['email']['validate'] = 1;
}
else
// Bad email address
$this->_error['email']['validate'] = 0;
}
}
// $_POST['submit'] = true;
// $_POST['email'] = 'jenkybad<script>email';
// $_POST['password'] = 'mypassword';
if(isset($_POST['submit'])) {
// Set up a db connection
$db = new DBEngine('hostname','dbname','dbuser','dbpass');
// Create instance of your user control
$_user = new UserControl($db);
// Execute instance
$_user->execute();
// Check for basic erroring
print_r($_user->_error);
} ?>

Functions not able to find variable?

I have the following variable $user_id being set by
//Check if user is logged in
session_start();
if (!isset ($_SESSION['user_id']))
{
header("location:login.php");
}
elseif(isset ($_SESSION['user_id']))
{
$user_id = $_SESSION['user_id'];
}
and then within the same function file I have the following:
function course_menu()
{
$sqlSubscription = "SELECT * FROM subscriptions WHERE `user_id` = '".$user_id."'";
$subscriptionResult = mysql_query($sqlSubscription);
while ($rows = mysql_fetch_assoc($subscriptionResult))
{
$user_id = $rows['user_id'];
$course_id = $rows['course_id'];
$course_title = $rows['course_title'];
if ($data_id == $rows['course_id'])
{
echo
'<li>
',$course_title,'
</li>';
}
else
{
echo
'<li>',$course_title,' </li>';
}
}
}
The problem is I keep getting undefined variable user_id every time I try to run the function. I can echo $user_id on another page lets say index.php by using require_once function.php and then echo $user_id, but for some reason the function itself can't access it?
I think it might be because it's outside its scope - but if so I'm not entirely sure what to do about it.
My question is, how can I get the function to be able to use the variable $user_id?
EDIT
So I've started doing
$user_id = $_SESSION['user_id'];
global $conn;
$sqlSubscription = "SELECT * FROM subscriptions WHERE `user_id` = '".$user_id."'";
$subscriptionResult = $conn->query($sqlSubscription);
while ($rows = mysqli_fetch_assoc($subscriptionResult))
{
$user_id = $rows['user_id'];
$course_id = $rows['course_id'];
$course_title = $rows['course_title'];
if ($data_id == $rows['course_id'])
{
echo
'<li>
',$course_title,'
</li>';
}
else
{
echo
'<li>',$course_title,' </li>';
}
}
which seems to work fine, but it's a bit tedious to add a new connection each time with a function or set the $user_id manually. Is there any way around this as I have several functions that require a connection to the db to pull data. Is there a better way to structure this type of stuff? I'm not very familiar with OOP but I can try it out if I can get some direction, here's another function that I use (and there are at least another 5-6 that require db connections)
function render_dashboard()
{
$user_id = $_SESSION['user_id'];
global $conn;
//Following brings up the number of subscription days left on the user dashboard
$sqlDate = "SELECT * FROM subscriptions WHERE `user_id` = '".$user_id."'" ;
$date = $conn->query($sqlDate);
while ($daterows = mysqli_fetch_assoc($date))
{
$course_registered = $daterows['course_title'];
$date_time = $daterows['end_date'];
$calculate_remaining = ((strtotime("$date_time")) - time())/86400;
$round_remaining = round("$calculate_remaining", 0, PHP_ROUND_HALF_UP);
// Here we assign the right term to the amount of time remaining I.E DAY/DAYS/EXPIRED
if($round_remaining > 1)
{
$remaining = $course_registered." ".$round_remaining." "."Days Remaining";
$subscriptionStatus = 2;
echo '<p>',$remaining,'</p>';
}
elseif ($round_remaining == 1)
{
$remaining = $course_registered." ".$round_remaining." "."Day Remaining";
$subscriptionStatus = 1;
echo '<p>',$remaining,'</p>';
}
elseif ($round_remaining <= 0)
{
$remaining = $course_registered." "."Expired"." ".$date_time;
$subscriptionStatus = 0;
echo '<p>',$remaining,'</p>';
}
}
//Check for most recent viewed video
$sqlVideo = "SELECT `last_video` FROM users WHERE `user_id` = '".$user_id."'" ;
$videoResult = $conn->query($sqlVideo);
if ($videoRows = mysqli_fetch_assoc($videoResult))
{
$last_video = $videoRows['last_video'];
$videoLink = "SELECT `chapter_id` FROM chapters WHERE `chapter_title` = '".$last_video."'";
if ($chapteridResult = mysql_fetch_assoc(mysql_query($videoLink)));
{
$chapter_id = $chapteridResult['chapter_id'];
}
$videoLink = "SELECT `course_id` FROM chapters WHERE `chapter_title` = '".$last_video."'";
if ($courseResult = mysql_fetch_assoc(mysql_query($videoLink)));
{
$course_id = $courseResult['course_id'];
}
}
}
The function course_menu() will not recognize your $user_id, Since it is outside its scope.
Make use of global keyword to solve this issue.
function course_menu()
{
global $user_id;
// your remaining code .........
The solution to getting around it without using global is to either DEFINE and pass it through ie - define ('var', '$var') then function x($var) or dependency injection as stated here How can I use "Dependency Injection" in simple php functions, and should I bother?

PHP Redirect Depending on users Column data in MySQL

I have created a login page with Facebook login API. And i have stored the users data (name, gender and etc) into MySQL database (except the column "gorg" in my table) when they are login.
Then, I'll redirect the users to "newgg.php" which is have two links "Giver" and
"Gatherer". So, users can choose either one of them.
My sample code:
<?php
session_start();
error_reporting(E_ALL);
include('src/sql_handler.php');
include('src/facebook_handler_core.php');
$new_fb = new facebook_handler_core;
$new_fb->run();
if (isset($_SESSION['gorg']) == "Gatherer") {
header('Location: map.php');
}
?>
My goal is to redirect them depending on the button they push for there FIRST time visiting the page, heres the button code
<form method="post" action="<?php echo $PHP_SELF;?>">
<input type="submit" class="button orange" name="Giver" value="Giver">
</form>
<form method="post" action="<?php echo $PHP_SELF;?>">
<input type="submit" class="button orange" name="Gatherer" value="Gatherer">
</form>
and now last but not least, IF they have already previously chosen their type of user it needs to just redirect them depending on what the 'gorg' column reads in the users table.
any ideas to why my codes not working properly?
just in case you need them, here are the sql_handlers
<?php
class MySQL_Con {
private $host = 'localhost',
$user = 'NUNURBSINESS',
$pass = 'ASKMEANDMAYBE',
$db = 'teknolog_fruitforest',
$_CON;
function MySQL_Con() {
$this->_CON = mysql_connect($this->host, $this->user, $this->pass);
if(!$this->_CON)
die(mysql_error());
else {
$select_db = mysql_select_db($this->db);
if(!$select_db)
die('Error Connecting To Database'.mysql_error());
}
}
function End_Con() {
mysql_close($this->_CON);
}
}
?>
and now the facebook_handler_core.php
<?php
class facebook_handler_core extends MySQL_Con {
public $session,$_INFO = array(),$U_INFO = array();
public function run() {
require('src/facebook.php');
$set_fb = new Facebook(array(
'appId' => 'MYAPPID',
'secret' => 'CANTTELLYOU',
'cookie' => true));
$this->session = $set_fb->getUser();
if($this->session != 0) {
$this->_INFO = $set_fb->api('/me');
if(!empty($this->_INFO))
$this->fb_session_handler();
}
}
function fb_session_handler() {
$SQL_CON = new MySQL_Con;
$SQL_CON->MySQL_Con();
$query = mysql_query("SELECT * FROM users WHERE oauth_provider = 'facebook' AND email = '" .mysql_real_escape_string($this->_INFO['email'])."'") or die(mysql_error());
if(mysql_num_rows($query) > 0) {
$this->U_INFO = mysql_fetch_array($query) or die(mysql_error());
} else {
$photolink = 'http://graph.facebook.com/'.$this->session.'/picture?type=square';
$query = mysql_query("INSERT INTO users(oauth_uid, oauth_provider, username, first_name, last_name, email, pic_square, gorg, gender)VALUES('".mysql_real_escape_string($this->session)."','facebook', '".mysql_real_escape_string($this->_INFO['name'])."', '".mysql_real_escape_string($this->_INFO['first_name'])."','".mysql_real_escape_string($this->_INFO['last_name'])."','".mysql_real_escape_string($this->_INFO['email'])."','".mysql_real_escape_string($photolink)."','null','".mysql_real_escape_string($this->_INFO['gender'])."')") or die(mysql_error());
$query = mysql_query("SELECT * FROM users WHERE email='".mysql_real_escape_string($this->_INFO['email'])."'") or die(mysql_error());
$this->U_INFO = mysql_fetch_array($query) or die(mysql_error());
}
$SQL_CON->End_Con();
$gorg = $this->U_INFO['gorg'];
if($gorg != null) {
$_SESSION['gorg'] = $gorg;
}
$_SESSION['email'] = $this->U_INFO['email'];
$_SESSION['image'] = $this->U_INFO['pic_square'];
$_SESSION['gender'] = $this->U_INFO['gender'];
if($gorg != null) {
if($gorg == 'Giver') {
//redirect to Giver
header('Location: picktreetype.php');
}
if($gorg == "Gatherer") {
//redirect to Gatherer
}
}
return true;
}
function update_user($param) {
$SQL_CON = new MySQL_Con;
$SQL_CON->MySQL_Con();
if($param == 'Giver')
$query = mysql_query("UPDATE users SET gorg='".mysql_real_escape_string($param)."', FF_Points='100' WHERE email='".mysql_real_escape_string($_SESSION['email'])."'") or die(mysql_error());
if($param == 'Gatherer')
$query = mysql_query("UPDATE users SET gorg='".mysql_real_escape_string($param)."', FF_Points='30' WHERE email='".mysql_real_escape_string($_SESSION['email'])."'") or die(mysql_error());
$SQL_CON->End_Con();
if(!$query)
return false;
else
return true;
}
}
?>
Thanks in advance, i just cant get enough out of this site when it comes to gaining help and proper guidance i really appreciate all the help anyone has ever given me in the past.
The problem is you're doing
isset($_SESSION['gorg']) == "Gatherer"
as isset() returns a boolean result which, using ==, will match any non-explicitly-false value. You would have had direct evidence of the problem if you would have used === (identity comparison operator).
So, in your case, "Gatherer" is evaluated as non-FALSE, aka TRUE.
Every time.
You shouldn't use this kind of comparison; instead try:
isset($_SESSION['gorg']) && $_SESSION['gorg'] == "Gatherer"
if you wish to keep checking whether gorg is set before doing any other evaluation.

Categories