I am adding straw polls to a website using this tutorial: http://code.tutsplus.com/articles/creating-a-web-poll-with-php--net-14257
I have modified this code so I can create my own polls by entering the poll title and questions which gets stored in a database table. This table is then queried and the polls are loaded from the database. This is working fine, however, when I am trying to return the number of votes for each question the value is coming back 0 every time. The table 'tally' holds the question id, answer id and number of votes.
When I try to insert data into this tally table from the webPoll class, both the QID and AID rows are blank, only the votes value increments each time.
My database is MySQL, the tutorial I followed was to insert data into an SQLite DB, I think this might be the problem but I can't seem to find a solution as of yet.
In summary, I need to get the insert statements in the webPoll class inserting QID, AID & votes values as QID and AID are not inserting.
tally
CREATE TABLE tally (
QID varchar(32) NOT NULL,
AID integer NOT NULL,
votes integer NOT NULL,
PRIMARY KEY (QID,AID))
webPoll Class
$mysql_host = "localhost";
$mysql_database = "vote";
$mysql_user = "root";
$mysql_password = "";
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</form>\n";
private $button = '<p class="buttons"><button type="submit" class="vote">Vote!</button></p>';
private $md5 = '';
/**
* ---
* 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->question = array_shift($params);
$this->answers = $params;
$this->md5 = md5($this->question);
$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
isset($_COOKIE[$this->md5]) ? $this->poll(self::VOTES) : $this- >poll(self::POLL);
}
private function poll($show_poll) {
$replace = $show_poll ? $this->button : '';
$this->footer = str_replace('%button%', $replace, $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']])) {
return;
}
try{
$dbh = new PDO('mysql:host=localhost;dbname=vote', 'root', '');
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
} catch(PDOException $e) {
echo "Error: " . $e->getMessage() . "<br/>";
}
try {
$sth = $dbh->prepare("INSERT INTO tally (QID,AID,votes) values ('QID', 'AID', '1')" );
$sth->execute(array($_POST['QID'],$_POST['AID']));
}
catch(PDOException $e) {
# 23000 error code means the key already exists, so UPDATE!
if($e->getCode() == 23000) {
try {
$sth = $dbh->prepare("UPDATE tally SET votes = votes + 1 WHERE QID='$QID' AND AID='$AID'");
$sth->execute(array($_POST['QID'],$_POST['AID']));
}
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);
$_COOKIE[$_POST['QID']] = 1;
}
}
static function getData($question_id) {
try {
$dbh = new PDO('mysql:host=localhost;dbname=vote', 'root', '');
$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
webPoll::db_error($e->getMessage());
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 occured. $error";
exit;
}
}
You are using the prepared statements incorrectly. Inside the values you should have placeholders. The values in the execute are bound to those placeholders.
So:
$sth = $dbh->prepare("INSERT INTO tally (QID,AID,votes) values ('QID', 'AID', '1')" );
Is sending QID, and AID to your DB. If those are integer columns I suspect you'll get 0s in their place.
You should change this to:
$sth = $dbh->prepare("INSERT INTO tally (QID,AID,votes) values (?, ?', '1')" );
Your execute:
$sth->execute(array($_POST['QID'],$_POST['AID']));
Is already set up correctly to pass the two values to the placeholders.
You also need to fix another update further down.
$sth = $dbh->prepare("UPDATE tally SET votes = votes + 1 WHERE QID=? AND AID= ?");
Prepared statements should rarely have variables in them and if they are in there they should have been checked against a whitelist of allowed terms.
You can read more about prepared statements:
http://php.net/manual/en/pdo.prepared-statements.php
https://en.wikipedia.org/wiki/Prepared_statement
Related
Scenario:
I have a SQL Query INSERT INTO dbo.Grades (Name, Capacity, SpringPressure) VALUES ('{PHP}',{PHP}, {PHP})
The data types are correct.
I need to now get the latest IDENTIY which is GradeID.
I have tried the following after consulting MSDN and StackOverflow:
SELECT SCOPE_IDENTITY() which works in SQL Management Studio but does not in my php code. (Which is at the bottom), I have also tried to add GO in between the two 'parts' - if I can call them that - but still to no avail.
The next thing I tried, SELECT ##IDENTITY Still to no avail.
Lastly, I tried PDO::lastInsertId() which did not seem to work.
What I need it for is mapping a temporary ID I assign to the object to a new permanent ID I get back from the database to refer to when I insert an object that is depended on that newly inserted object.
Expected Results:
Just to return the newly inserted row's IDENTITY.
Current Results:
It returns it but is NULL.
[Object]
0: Object
ID: null
This piece pasted above is the result from print json_encode($newID); as shown below.
Notes,
This piece of code is running in a file called save_grades.php which is called from a ajax call. The call is working, it is just not working as expected.
As always, I am always willing to learn, please feel free to give advice and or criticize my thinking. Thanks
Code:
for ($i=0; $i < sizeof($grades); $i++) {
$grade = $grades[$i];
$oldID = $grade->GradeID;
$query = "INSERT INTO dbo.Grades (Name, Capacity, SpringPressure) VALUES ('" . $grade->Name . "',". $grade->Capacity .", ".$grade->SpringPressure .")";
try {
$sqlObject->executeNonQuery($query);
$query = "SELECT SCOPE_IDENTITY() AS ID";
$newID = $sqlObject->executeQuery($query);
print json_encode($newID);
} catch(Exception $e) {
print json_encode($e);
}
$gradesDictionary[] = $oldID => $newID;
}
EDIT #1
Here is the code for my custom wrapper. (Working with getting the lastInsertId())
class MSSQLConnection
{
private $connection;
private $statement;
public function __construct(){
$connection = null;
$statement =null;
}
public function createConnection() {
$serverName = "localhost\MSSQL2014";
$database = "{Fill In}";
$userName = "{Fill In}";
$passWord = "{Fill In}";
try {
$this->connection = new PDO( "sqlsrv:server=$serverName;Database=$database", $userName, $passWord);
$this->connection->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch( PDOException $e ) {
die("Connection Failed, please contact system administrator.");
}
if ($this->connection == null) {
die("Connection Failed, please contact system administrator.");
}
}
public function executeQuery($queryString) {
$results = array();
$this->statement = $this->connection->query( $queryString );
while ( $row = $this->statement->fetch( PDO::FETCH_ASSOC ) ){
array_push($results, $row);
}
return $results;
}
public function executeNonQuery($queryString) {
$numRows = $this->connection->exec($queryString);
}
public function getLastInsertedID() {
return $this->connection->lastInsertId();
}
public function closeConnection() {
$this->connection = null;
$this->statement = null;
}
}
This is PDO right ? better drop these custom function wrapper...
$json = array();
for ($i=0; $i < sizeof($grades); $i++) {
//Query DB
$grade = $grades[$i];
$query = "INSERT INTO dbo.Grades (Name, Capacity, SpringPressure)
VALUES (?, ?, ?)";
$stmt = $conn->prepare($query);
$success = $stmt->execute(array($grade->Name,
$grade->Capacity,
$grade->SpringPressure));
//Get Ids
$newId = $conn->lastInsertId();
$oldId = $grade->GradeID;
//build JSON
if($success){
$json[] = array('success'=> True,
'oldId'=>$oldId, 'newId'=>$newId);
}else{
$json[] = array('success'=> False,
'oldId'=>$oldId);
}
}
print json_encode($json);
Try the query in this form
"Select max(GradeID) from dbo.Grades"
I am trying to create a PHP array of random "fruits" from a database.
The database class that I am using:
class Db
{
private static $_instance = null;
private $_pdo;
private function __construct()
{
try {
$this->_pdo = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME .'', DB_USER, DB_PASS);
} catch (PDOException $e) {
die($e->getMessage());
}
}
public static function getInstance()
{
if (!isset(self::$_instance)) {
self::$_instance = new Db();
}
return self::$_instance;
}
public function prepare($sql)
{
return $this->_pdo->prepare($sql);
}
}
The class that is using the database to fetch "fruits" to create an array of a given size of random entries by using 3 seperate queries to calculate and retrieve "x" number of random items form the database.
class FruitBasket
{
private $_fruitArray = array(),
$_inputCode,
$_db;
public function __construct($input = null)
{
$this->_inputCode = $input;
$this->_db = Db::getInstance();
var_dump($this->_db);
}
public function pickFruit($count)
{
$doubleCount = $count * 2;//double the count used in calculation with the random number
$fruitIDs = ''; //the choosen fruits (id's)
$i = 0;
//#1 get total count of fruits table
$sql = "SELECT COUNT(*) FROM `fruits`";
if ($query = $this->_db->prepare($sql)) {
if ($query->execute()) {
$allFruits = $query->fetch(PDO::FETCH_NUM);
} else {
print_r("ERROR QUERY DID NOT EXECUTE #1");
}
} else {
print_r("ERROR CHECK SQL SYNTAX #1");
}
//#2 calculate random number to pull from all of id's
$sql = "SELECT id FROM `fruits` WHERE RAND()* ? < ? ORDER BY RAND() LIMIT 0, ? ";
if ($query = $this->_db->prepare($sql)) {
$query->bindParam(1, $allFruits[0], PDO::PARAM_INT);
$query->bindParam(2, $doubleCount, PDO::PARAM_INT);
$query->bindParam(3, $count, PDO::PARAM_INT);
if ($query->execute()) {
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
if ($i == 0) {
$fruitIDs .= "'" . $row['id'] . "'";
} else {
$fruitIDs .= ", '" . $row['id'] . "'";
}
$i++;
}
} else {
print_r("ERROR QUERY DID NOT EXECUTE #2");
}
} else {
print_r("ERROR CHECK SQL SYNTAX #2");
}
//#3 get the fruits
$sql="SELECT NAME FROM `fruits` WHERE `id` IN( ? )";
if ($query = $this->_db->prepare($sql)) {
$query->bindParam(1, $fruitIDs, PDO::PARAM_STR);
if ($query->execute()) {
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$this->_fruitArray[] = $row['name'];
}
} else {
print_r("ERROR QUERY DID NOT EXECUTE #3");
}
} else {
print_r("ERROR CHECK SQL SYNTAX #3");
}
return $this->_fruitArray;
}
}
The table that I am attempting has a bunch of "fruits" in it, an example of how the table is structured:
==================================
| ID | NAME |
==================================
| 01 | Apple |
==================================
I am attempting to test this all out by using the following:
echo "<pre>";
echo "TESTING FRUIT ARRAY:</br></br>";
$basket = new FruitBasket();
echo"</br></br> PRINT_R: </br></br>";
print_r($basket->pickFruit(10));
echo "</br></br> VARDUMP: </br></br>";
var_dump($basket->pickFruit(10));
The sql query prepares and executes properly, I can do a vardump of the prepares and the binds and they return TRUE. Nothing is returned on the last query however.
In the first query that executes Doing a print statement of $allFruits shows the correct total count from the table.
The second query seems to be working properly,the string $fruitIDs, gets random id's from the table, I can echo this out and confirm that indeed the correct number of ID's are returned.
The problem occurs (I think) with the third query:
Nothing is returned form this query. The prepare statement returns true on a var dump as does the execute, however there is no results!
If I manually take the ID's that are output from query#2 and run it myself in mysql, the correct "fruit" names are returned.
Am I binding the variables incorrectly? I read the pages from the PHP manual but clearly I am doing something wrong.
Please help! :)
Thanks to the links and input provided by Your common sense, using the following:
Reference - frequently asked questions about PDO
and
Can I bind an array to an IN() condition?
I was able to resolve this by changing my query as follows:
//#2 calculate random number to pull from all of id's
$sql = "SELECT id FROM `fruits` WHERE RAND()* ? < ? ORDER BY RAND() LIMIT 0, ? ";
if ($query = $this->_db->prepare($sql)) {
$query->bindParam(1, $allFruits[0], PDO::PARAM_INT);
$query->bindParam(2, $doubleCount, PDO::PARAM_INT);
$query->bindParam(3, $count, PDO::PARAM_INT);
if ($query->execute()) {
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$fruitIDs[] = $row['id'];
}
} else {
print_r("ERROR QUERY DID NOT EXECUTE #2"); }
} else {
print_r("ERROR CHECK SQL SYNTAX #2");
}
//#3 get the fruits
$inQuery = implode(',', array_fill(0, count($fruitIDs), '?'));
$sql="SELECT NAME FROM `fruits` WHERE `id` IN($inQuery)";
if ($query = $this->_db->prepare($sql)) {
if ($query->execute($fruitIDs)) {
while ($row = $query->fetch(PDO::FETCH_NUM)) {
$this->_fruitArray[] = $row[0];
}
} else {
print_r("ERROR QUERY DID NOT EXECUTE #3");
}
} else {
print_r("ERROR CHECK SQL SYNTAX #3");
}
return $this->_fruitArray;
}
I do not fully understand the security benefits or ramifications of binding the parameters or simply including them in the actual execute() but for now the query is performing as intended, so thank you for the input!
So i am trying to make a backup class and this is what I have so far. Issue is the $tbl_data is empty. What am I doing wrong.
The connection to the database is successful.
Without the 'echo $tbl_data', the '$current_table - current table' output is correct but if 'echo $tbl_data' is used, only the first table is shown ( trying to backup two tables to begin with ).
class mBackup{
private $_connection = ""; //db connection var
private $output = ""; //sql output
private $tbl_data = "";
private $tbl_row = "";
private $nfields = "";
private $create_table_query = "";
private $create_table_output = "";
public function __construct($dbhost,$dbname,$dbuser,$dbpassword){
$this->_connection = new mysqli($dbhost,$dbuser,$dbpassword,$dbname);
//possible connection error
if($this->_connection->connect_errno){
echo "Failed to connect to the DB";
}
else{
echo "Connected<br />";
}
}
public function backup_db(){
//get the table names from the DB and store in an array
$result = $this->_connection->query("SHOW TABLES");
//get the TABLE names
while($row = $result->fetch_row())
{
$table_names[] = $row[0];
}
//For each table
foreach($table_names as $current_table)
{
echo $current_table." - current table<br />"; //debug
$tbl_data = "";
$tbl_row = "";
$nfields = "";
$create_table_query = "";
$create_table_output = "";
//SELECT Everything from the table in use
$query = $this->_connection->prepare("SELECT * FROM ?");
$query->bind_param('s', $current_table);
$query->execute();
$query->bind_result($tbl_data);
$query->fetch();
echo $tbl_data."<br/>";
}
}
Try something like:
while ($query->fetch()) {
echo $tbl_data;
}
and see if that gets you anything. From the little that I know, bind_result binds columns in the result set to variables. If your table has 5 columns, you should have bind_result($var1, $var2, $var3, $var4, $var5) but since your number of columns are going to change depending on the table, I don't know if bind_result will give you what you need.
Try closing the prepared statement after every loop
$query->close();
or resetting.
$query->reset()
You can't use ? for the table name. See the second note in http://www.php.net/manual/en/mysqli.prepare.php for the allowed places for markers. So you'll have to construct the query by normal variable interpolateion:
$select = sprintf("SELECT * FROM `%s`", $current_table);
$result = $this->_connection->query($select);
I have a 'users' SQL table structure like this (the ID is randomly generated for certain reasons, it is not auto-incremented):
ID name deleted lastActive
3242 Joe 0 20-6-2012 23:14
2234 Dave 0 20-6-2012 23:13
2342 Simon 1 20-6-2012 23:02
9432 Joe 1 20-6-2012 22:58
In one query (to avoid concurrent queries adding the same name twice), I need to add a new user to the table IF there is not already a record with that name AND deleted = 0. I then need to know the result of the query (if the user was added) so that I can report back saying if the user was added or not. Is this possible using PHP?
I could do this (but as a prepared statement, of course!):
INSERT INTO users (ID, name) VALUES ($id, $name)
WHERE NOT EXISTS (SELECT 1 FROM users WHERE name = $name AND deleted = 0)
But how can I know if the user was added or not?
If you're using mysqli, you can use the mysqli_stmt_affected_rows() function to determine how many rows were inserted.
Similarly, you can use the PDOStatement::rowCount() method to determine how many rows were inserted for PDO.
Both functions will tell you the number of rows that were inserted as a result of the query.
You can know the number of rows affected by your query in mysql using
mysql_affected_rows.
If you are using PDO,
PDOStatement::rowCount.
If MYSQLi, mysqli_affected_rows
Here's a nice insertion method that returns the ID:
/**
* Execute an insert or update in the database.
* #param $table - Table name.
* #param $key_name - Primary key to update. NULL to a insert
* #param $data - Column data array
* #param $call_on_error function name that should called in case of an exception during the
* execution of the statment, the function is expected to take one argument, the exception object
* #return mixed An array containing the key inserted or updated on success, false on failure.
*/
function INSERT($table, $key_name, &$data, $call_on_error = null) {
list($min_cols, $prefix, $suffix, $key_value) = isset($data[$key_name]) ?
array(2, 'UPDATE', " WHERE `$key_name`=:$key_name", $data[$key_name]) :
array(1, 'INSERT', '', null);
if (count($data) < $min_cols) {
return false;
}
$set_clause = '';
foreach ($data as $k => $v) {
if ($k !== $key_name) {
if (($flag_name = strstr($k, "__", true))) {
if (strcmp($k, "{$flag_name}__mask") && isset($data["{$flag_name}__value"]))
$set_clause .= ",`$flag_name`=:{$flag_name}__value | (`$flag_name` & :{$flag_name}__mask)";
} else {
$set_clause .= ",`$k`=:$k";
}
}
}
global $dbo_error_duplicated;
$dbo_error_duplicated = false;
$dbh = DBH();
try {
$sth = $dbh->prepare("$prefix $table SET " . substr($set_clause, 1) . $suffix);
$res = $sth->execute($data);
} catch (PDOException $e) {
$dbo_error_duplicated = $sth->errorCode() === '23000';
echo $e;
if(isset($call_on_error)){
call_user_func($call_on_error, $e);
}
$res = false;
}
if ($res) {
if ($key_value === null && is_numeric($id = $dbh->lastInsertId())) {
$key_value = $id;
}
$res = $key_value === null ? false : array($key_name => $key_value);
}
return $res;
}
And… the DBH config:
/**
* Get Data Base Handler.
* Manual # http://www.php.net/manual/en/pdostatement.fetch.php
* More info # http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/
*
* #return PDO Data Base Handler
*/
function DBH() {
global $DBH;
global $db_config;
if ($DBH === null) {
// throws PDOException on connection error
$DBH = new PDO("mysql:host=$db_config[host];dbname=$db_config[dbname]", $db_config['user'], $db_config['pass'],
array(PDO::ATTR_PERSISTENT => $db_config['persistent'], PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES '$db_config[encoding]'"));
// ask PDO to throw exceptions for any error
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
return $DBH;
}
That uses this .ini file:
[db_config]
persistent = true
host = "localhost"
user = "root"
pass = ""
dbname = "theDbName"
# host = "db.production_host.com"
# user = "prod_root"
# pass = "big4nd5tr0ngp4s5word"
# dbname = "theDbName"
encoding = "UTF8"
Im trying to convert this script, in my Zend program.
http://github.com/jackmoore/colorrating/raw/master/rating/rating.php
<?php
class rating{
public $average = 0;
public $votes;
public $status;
public $table;
private $path;
function __construct($table){
try{
$pathinfo = pathinfo(__FILE__);
$this->path = realpath($pathinfo['dirname']) . "/database/ratings.sqlite";
$dbh = new PDO("sqlite:$this->path");
$this->table = $dbh->quote($table);
// check if table needs to be created
$table_check = $dbh->query("SELECT * FROM $this->table WHERE id='1'");
if(!$table_check){
// create database table
$dbh->query("CREATE TABLE $this->table (id INTEGER PRIMARY KEY, rating FLOAT(3,2), ip VARCHAR(15))");
$dbh->query("INSERT INTO $this->table (rating, ip) VALUES (0, 'master')");
} else {
$this->average = $table_check->fetchColumn(1);
}
$this->votes = ($dbh->query("SELECT COUNT(*) FROM $this->table")->fetchColumn()-1);
}catch( PDOException $exception ){
die($exception->getMessage());
}
$dbh = NULL;
}
function set_score($score, $ip){
try{
$dbh = new PDO("sqlite:$this->path");
$voted = $dbh->query("SELECT id FROM $this->table WHERE ip='$ip'");
if(sizeof($voted->fetchAll())==0){
$dbh->query("INSERT INTO $this->table (rating, ip) VALUES ($score, '$ip')");
$this->votes++;
//cache average in the master row
$statement = $dbh->query("SELECT rating FROM $this->table");
$total = $quantity = 0;
$row = $statement->fetch(); //skip the master row
while($row = $statement->fetch()){
$total = $total + $row[0];
$quantity++;
}
$this->average = round((($total*20)/$quantity),0);
$statement = $dbh->query("UPDATE $this->table SET rating = $this->average WHERE id=1");
$this->status = '(thanks!)';
} else {
$this->status = '(already scored)';
}
}catch( PDOException $exception ){
die($exception->getMessage());
}
$dbh = NULL;
}
}
function rating_form($table){
$ip = $_SERVER["REMOTE_ADDR"];
if(!isset($table) && isset($_GET['table'])){
$table = $_GET['table'];
}
$rating = new rating($table);
$status = "<div class='score'>
<a class='score1' href='?score=1&table=$table&user=$ip'>1</a>
<a class='score2' href='?score=2&table=$table&user=$ip'>2</a>
<a class='score3' href='?score=3&table=$table&user=$ip'>3</a>
<a class='score4' href='?score=4&table=$table&user=$ip'>4</a>
<a class='score5' href='?score=5&table=$table&user=$ip'>5</a>
</div>
";
if(isset($_GET['score'])){
$score = $_GET['score'];
if(is_numeric($score) && $score <=5 && $score >=1 && ($table==$_GET['table']) && isset($_GET["user"]) && $ip==$_GET["user"]){
$rating->set_score($score, $ip);
$status = $rating->status;
}
}
if(!isset($_GET['update'])){ echo "<div class='rating_wrapper'>"; }
?>
<div class="sp_rating">
<div class="rating">Rating:</div>
<div class="base"><div class="average" style="width:<?php echo $rating->average; ?>%"><?php echo $rating->average; ?></div></div>
<div class="votes"><?php echo $rating->votes; ?> votes</div>
<div class="status">
<?php echo $status; ?>
</div>
</div>
<?php
if(!isset($_GET['update'])){ echo "</div>"; }
}
if(isset($_GET['update'])&&isset($_GET['table'])){
rating_form($_GET['table']);
}
How can I change this to Mysql?
Im using $dbh = Zend_Registry::get ( "db" ); normally to get my sql access.
Thanks everyone, hopefully there isnt too many changes invloved
If the db object in the registry is one of Zend_Db then:
$dbh->quote() becomes $db->quote() (the easy one)
$dbh->query() statements that manipulate data could translate to $dbh->query() (again, easy). However, it would be better to update the code to use $db->insert($table, $data) - or use Zend_Db_Table objects with $table->insert($data).
$dbh->query() statments that return data can become $db->fetchAll($sql) statements, but you need to update the code to expect Zend_Db Row and Rowset objects.
I'd suggest reading the Zend_Db
documentation to understand the what functions map to the different PDO functions.
If you just need this to work with MySQL change the DSN string to your MySQL connection. Something like:
$dbh = new PDO("mysql:dbname=testdb;host=127.0.0.1", $user, $pass);
See the PDO documentation for details.
If the db object in the registry a PDO instance just grab that object and use it, instead of creating a new PDO object.