5 star rating script I have is made based on this tutorial http://php.about.com/od/finishedphp1/ss/rating_script.htm
I have changed it a bit based on comments on the mentioned site,but script still has some issues.
When i rate something script refreshes the site and adds the needed parameters in query string but the rest of the script is not triggered by it.
Echo "Rate ";
Echo "1 | ";
Echo "2 | ";
Echo "3 | ";
Echo "4 | ";
Echo "5";
this thing is pretty much skipped.
$mode = $_GET['mode'];
$voted = $_GET['voted'];
$id = $_GET['id'];
if ($mode=='vote')
{
if(isset($_COOKIE['146829gigapuding']))
{
Echo "Sorry You have already ranked that site";
}
else
{
$month = 2592000 + time();
setcookie('146829gigapuding',Voted,$month);
mysql_query ("UPDATE searchengine SET rating = rating+$voted, votes = votes+1 WHERE id = $id");
Echo "Your vote has been cast";
}
}
The sql connection,query and bunch of other code is there but there were no problems with it,i tried moving the code order but nothing.
Another thing that worries me is there a way to remove the ?mode=vote... parameters afther vote is cast.
tnx in advance.
As I see here
".$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']."?mode=vote&voted=1&id=".$data[id]."
you have ? (question mark) twice, which makes your url invalid. Try changing it to
".$_SERVER['PHP_SELF'].'?'.$_SERVER['QUERY_STRING']."&mode=vote&voted=1&id=".$data[id]."
and see what will happen :)
p.s.: the change is ? to & before mode
Related
I am developing on an HTML page a "go to next record" button.
Well, it goes to the next record once and then stops. Nothing happens when clicking on the "Prior Issue" button after the initial click. Since I increment the issue number, the cursor should move to the next record. I am only working on the "Prior Issue" button currently.
HTML syntax:
<a href="index.php?content=main_window&id=1" title="Show More Recent Issue" >< Next (Newer) Issue</a>             <a href="index.php?main_window&id=-1 title ="Show Older Issue" >Prior (Older)) Issue ></a>
The variable "id" is past to:
// Get Cycle Direction "1" stands for newer issue, "0" No Direction set, "-1" stands for older issue
if (!isset($_REQUEST['id']))
{$cycle_direction=0;
} else {
$cycle_direction = trim($_REQUEST['id']);
}
Which then gets past to: (only working on the "case -1" at this time.
switch(trim($cycle_direction))
{
case -1:
// display an older issue
echo "Decrement<br>";
$current_record_number=$current_record_number +1;
echo $current_record_number;
mysqli_data_seek($result, 0);
mysqli_data_seek($result, $current_record_number);
$row=mysqli_fetch_row($result);
printf ("%s \n",$row[0]);
$issuenum=$row[0];
break;
case 0:
// display current issue
//echo "No Selection";
break;
case 1:
// display newer issue
//echo "Increase";
$issuenum=2165;
break;
}
Do it right way. All what you need is url with next/prev record's ids.
$current_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
// in case you are using MySQL
$query = "SELECT
prev_id, next_id
FROM
(SELECT
id AS prev_id
FROM
issues
WHERE
id < $current_id
LIMIT 1) a,
(SELECT
id AS next_id
FROM
issues
WHERE
id > $current_id
LIMIT 1) b";
// fetch query data
$prev_id = ...
$next_id = ...
// SHOW CURRENT ISSUE
echo '<a href="index.php?content=main_window&id='.$next_id.'" title="Show More Recent Issue" >< Next (Newer) Issue</a> - <a href="index.php?main_window&id=$prev_id title ="Show Older Issue" >Prior (Older)) Issue ></a>';
In case you get your data from any other db, the logic is the same. Just select previous and next ids, and provide urls using $prev_id and $next_id.
Another solution using MAX/MIN trick.
$query = "SELECT
(SELECT MAX(id) FROM issues WHERE id < t.id) as prev_id,
(SELECT MIN(id) FROM issues WHERE id > t.id) as next_id
FROM issues t WHERE t.id = $current_id";
"Beta" version now working. I stripped the code down to the very bare essentials and added many echo statements to observe how the program responded. The short answer, PHP does not have a memory between each web-page so the values of the variables are "lost". While I was dimly aware of this, it did not become obvious for a while.
The solution was to develop a several $_SESSION variables to hold the array and to monitor the location of the cursor.
<?php
// Start the session
session_start();
include ("establish_array.php");
?>
The code below constitutes "establish_array.php" to establish the array in: "$_SESSION['result']".
<?php
require_once 'php_data/login_data.php';
$conn = new mysqli($hn, $un, $pw, $db);
if ($conn->connect_error) die($conn->connect_error.' Sorry, could not connect to the sfmags database server');
$query = "Select IssueIDNUM FROM tblIssueList ORDER by IssueDate DESC, IssueIDNUM ";
$_SESSION['result'] =$conn->query($query);
if (!$_SESSION['result']) die($conn->error);
$_SESSION['rowcount'] = mysqli_num_rows($_SESSION['result']);
?>
The code below is embedded in a case (switch) statement to move the magazine issue to the next older magazine when the pseudo "next" HTML key is pressed. The function "return_row_number();" returns the current row number, +1 is added to the row number and "mysqli_data_seek" is used to move to the next (older) record (issue).
$issuenum = $_SESSION['issuenum'];
$_SESSION['cursor_location'] = return_row_number();
echo "Cursor Location :" . $_SESSION['cursor_location'] . "<br>";
$_SESSION['cursor_location'] = $_SESSION['cursor_location'] + 1;
mysqli_data_seek($result, 0);
mysqli_data_seek($result,$_SESSION['cursor_location']);
$row=mysqli_fetch_row($result);
$issuenum=$row[0];
$_SESSION['issuenum'] = $issuenum;
echo "Issue Number: $issuenum <br>";
Thanks to: misunderstood, Unheiiig, and Alexander Ravikovich for providing useful advice and clues.
Update
This is what I got from your comment:
function return_row_number() {
// Loop through the Array; Get Row Number for the current issue global $result,$issuenum, $rowcount;
$count =0;
mysqli_data_seek($result, 0);
while($row=mysqli_fetch_array($result, MYSQL_ASSOC)) {
++$count;
if($issuenum == $row['IssueIDNUM']) {
return $count -1; break;
}
}
}
Now the mystery value is $issuenum.
And there is a terminology problem. This is not "Looping through an Array" it is querying the database and and looping through the query results.
This is a rather inefficient method of finding the next record. But before correcting that, you need to explain where the value for $issuenum is coming from.
It would also help to know more about the database table especially:
How many issue records?
What is the numbering scheme?
How often does a new issue get added?
end of update
With this line of code you will always get a value of 1
$current_record_number=$current_record_number +1;
because $current_record_number = 0.
You should add the current issue to the href where xx=current record #.
I changed "id" to "cycle"
added content= to Next href.
<a href="index.php?content=main_window&cycle=1&rec=xx"
title="Show More Recent Issue" > < Next (Newer) Issue</a>
           
<a href="index.php?content=main_window&cycle=-1&rec=xx
title ="Show Older Issue" >Prior (Older)) Issue ></a>
Then add this to your PHP:
$current_record_number = intval($_GET['rec']);
And change:
$cycle_direction = trim($_REQUEST['id']);
To:
$cycle_direction= intval($_GET['cycle']);
Instead of trim and isset you should just use intval()
$cycle_direction = intval($_REQUEST['id']);
Also instead of $current_record_number=$current_record_number +1;
You could use: $current_record_number += $cycle_direction
and eliminate the switch.
Unconventional approach
Let's say issues have values from 1 to 10.
$next[-1] = array(0,10,1,2,3,4,5,6,7,8,9,1);
$next[1] = array(0,2,3,4,5,6,7,8,9,10,1);
$next[0] = array(0,1,2,3,4,5,6,7,8,9,10);
$nextIssue = $next[intval($_REQUEST['id'])];
If issues are numbered 2001 to 2010
$nextIssue = 2000 + $next[intval($_REQUEST['id'])];
No matter how many issues you have there is no need to use a database.
Create the $next array as shown above, then save the array.
$fp = fopen('next.ser','w');
fwrite($fp,serialize($next));
fclose($fp);
When you need the $next array in an app use:
$next= unserialize(file_get_contents('next.ser'));
I am very very disappointed this time. I wasted my whole day and I couldn't help me out. Here is the problem:
I need accept or delete the pending jobs. If I accept, only then it will publish on my site. Please look at the image.
Here I am trying this code to handle this matter. Firstly if anyone post a new job, I pass a hidden value=0 according to the job.
<input type="hidden" name="pending" value=0/>
Then I store it in my database.
INSERT INTO job (Pending) VALUES ('$_POST[pending]');
Then I go to the image(above) page to accept or delete.
echo "<a href='accept.php?accept=1'>ACCEPT</a> Or ";
echo "<a href='accept.php?accept=0'>DELETE</a>";
After accepting Pending column will be replaced from 0 to 1 and thus it will be published. Or deleting time, the job will be simply be deleted from database.
$accept=$_GET['accept'];
if($accept==1){
mysql_query("UPDATE job SET Pending='$accept'
WHERE ID='5'");
}
else{
mysql_query("DELETE FROM job WHERE ID='5'");
}
In the 'job' table, I use a primary auto increment column named ID. I put 5 for ID. So this code will work only for the pending job which ID is 5. So my problem is here. How can I alternate this 5 with a dynamic variable?
FOR MORE ASSISTANCE HERE IS the CODE OF 'PENDING JOBS' PAGE;
$result1 = mysql_query("SELECT * FROM job ORDER BY ID DESC");
while($row1 = mysql_fetch_array($result1))
{
$id=$row1['ID'];
$cat=$row1['Category'];
$title=$row1['Title'];
$type=$row1['Type'];
$desp=$row1['Description'];
$salary=$row1['Salary'];
$day=$row1['Day'];
$month=$row1['Month'];
$year=$row1['Year'];
$info=$row1['Contact'];
$pending=$row1['Pending'];
$now = time();
$last_date = strtotime("$year-$month-$day");
$datediff = $last_date - $now;
$day_left=ceil($datediff/(60*60*24));
if($day_left>=0&&$pending==0){
echo "<div class=cat>Job field: $cat<br/></div>";
echo "<div class=yel2>";
echo "This is a <b>$type time</b> job and we are looking for <b>$title</b>. $desp<br/>";
if ($salary!=0) echo "Salary: $salary<br/>";
echo "Contact info: $info<br/>Last date: $day-$month-$year";
if($day_left==0)
echo "<br/><span class=ash><i>Today is the last day to apply</i><br/>";
else
echo "<br/><span class=ash><i>$day_left day(s) left</i></span><br/>";
echo "<span class=acc><a href='accept.php?accept=1'>ACCEPT</a><span> Or ";
echo "<span class=del><a href='accept.php?accept=0'>DELETE</a></span>";
Just pass the id along with the accept url.
echo "<span class=acc><a href='accept.php?id=$id&accept=1'>ACCEPT</a><span> Or ";
You can grab the id inside the accept.php script using
$post_id = $_GET['id'];
The code would require little change
$accept = intval($_GET['accept']); // safe against sql-injections
$post_id = intval($_GET['id']);
if($accept==1){
mysql_query("UPDATE job SET Pending='$accept'
WHERE ID='$post_id'");
}
else{
mysql_query("DELETE FROM job WHERE ID='$post_id'");
}
i get this error line on this php file . can someone locate where is the error ?
-------------You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1----------
i have this page for votes to users but if i vote in one user this vote goes to all users . how can i make this code when voting this vote goes only to its user .
--
// Connects to your Database
mysql_connect("localhost", "dbusername", "dbpassword") or die(mysql_error());
mysql_select_db("mydatabase") or die(mysql_error());
//We only run this code if the user has just clicked a voting link
if ( $mode=="vote")
{
//If the user has already voted on the particular thing, we do not allow them to vote again
//$cookie = "Mysite$id";
if(isset($_COOKIE[$cookie]))
{
Echo "Sorry You have already ranked that site <p>";
}
//Otherwise, we set a cooking telling us they have now voted
else
{
$month = 2592000 + time();
setcookie('Mysite'.$id, 'Voted', $month);
//Then we update the voting information by adding 1 to the total votes and adding their vote (1,2,3,etc) to the total rating
mysql_query ("UPDATE userads SET total = total+$voted, votes = votes+1 WHERE id = $id");
}
}
if ( $mode2=="vote")
{
//If the user has already voted on the particular thing, we do not allow them to vote again
//$cookie = "Mysite$id";
if(isset($_COOKIE[$cookie]))
{
Echo "Sorry You have already ranked that site <p>";
}
//Otherwise, we set a cooking telling us they have now voted
else
{
$month = 2592000 + time();
setcookie('Mysite'.$id, 'Voted', $month);
//Then we update the voting information by adding 1 to the total votes and adding their vote (1,2,3,etc) to the total rating
mysql_query ("UPDATE userads SET total = total+$voted, nvotes = nvotes+1 WHERE id = $id");
}
}
//Puts SQL Data into an array
$data = mysql_query("SELECT * FROM userads WHERE id = $id ") or die(mysql_error());
//Now we loop through all the data
while($ratings = mysql_fetch_array( $data ))
?>
<link href="style.css" type="text/css" rel="stylesheet" />
{
<?php
echo '<div id="voting_14" class="voting voting_template_votess-up-down">';
echo "<strong class='positive_votes'>";
$current = $ratings[votes];
echo "<span>+" . round($current,0) . "</span>";
echo " <input class='vote_positive' type='submit'>";
echo '</strong>';
echo "<strong class='negative_votes'>";
$current2 = $ratings[nvotes];
echo " <input class='vote_negative' type='submit'>";
echo "<span>-". round($current2,0) ."</span>";
echo '</strong>';
echo '</div>';
}
---the end
i have sql table userads with : id , name , username , total, votes , nvotes.
Correct your code to following,
setcookie('Mysite'.$id, 'Voted', $month); // ERROR 1
and
while($ratings = mysql_fetch_array( $data ))
{ // ERROR 2
?>
I copy pasted your code in a file and ran:
php -l your_script.php
Yields:
Parse error: syntax error, unexpected '}' in your_script.php on line 78
So, that last bracket } at the very end is causing a parse error. Either that or you didn't post the matching if/while/etc. in your post and the problem is elsewhere.
You have a syntax error. Probably your configuration doesn't display errors and you get a blank screen.
You are missing quotes here:
setcookie(Mysite.$id, Voted, $month);
It should be:
setcookie('Mysite'.$id, 'Voted', $month);
Apparently something is wrong with your query. You can check your SQL query with a simple:
$sql = "SELECT * FROM userads WHERE id = $id ";
echo $sql;
My first guess is, that $id is not set properly.
I found this script on about.com which I'm trying to learn from on how to create a rating system but the script for some reason wont count a vote when the link is clicked and just reloads the page.
I was wondering how can I fix this problem? And what part of the code do I need to change and where?
Here is the full script below.
<?php
// Connects to your Database
mysql_connect("localhost", "root", "", "sitename") or die(mysql_error());
mysql_select_db("sitename") or die(mysql_error());
//We only run this code if the user has just clicked a voting link
if ( $mode=="vote") {
//If the user has already voted on the particular thing, we do not allow them to vote again $cookie = "Mysite$id";
if(isset($_COOKIE[$cookie])) {
echo "Sorry You have already ranked that site <p>";
} else {
//Otherwise, we set a cooking telling us they have now voted
$month = 2592000 + time();
setcookie(Mysite.$id, Voted, $month);
//Then we update the voting information by adding 1 to the total votes and adding their vote (1,2,3,etc) to the total rating
mysql_query ("UPDATE vote SET total = total+$voted, votes = votes+1 WHERE id = $id");
echo "Your vote has been cast <p>";
}
}
//Puts SQL Data into an array
$data = mysql_query("SELECT * FROM vote") or die(mysql_error());
//Now we loop through all the data
while($ratings = mysql_fetch_array( $data )) {
//This outputs the sites name
echo "Name: " .$ratings['name']."<br>";
//This calculates the sites ranking and then outputs it - rounded to 1 decimal
if($ratings['total'] > 0 && $ratings['votes'] > 0) {
$current = $ratings['total'] / $ratings['votes'];
} else {
$current = 0;
}
echo "Current Rating: " . round($current, 1) . "<br>";
//This creates 5 links to vote a 1, 2, 3, 4, or 5 rating for each particular item
echo "Rank Me: ";
echo "Vote 1 | ";
echo "Vote 2 | ";
echo "Vote 3 | ";
echo "Vote 4 | ";
echo "Vote 5<p>";
}
?>
$mode is never set? While it may have worked if register globals was on, it is not on by default any more (and is removed in later versions of PHP)
//We only run this code if the user has just clicked a voting link
if ( $mode=="vote") {
Maybe you mean
if ( $_GET['mode']=="vote") {
The same goes for $id and $voted, which are also never set.
EDIT
I also would like to add, that if I went and changed id to 1';DROP TABLE vote; You would have a whole lot of data lost. Look at SQL Injection
EDIT
If the row in the table doesn't exist, you will need to INSERT it before you can UPDATE it.
I can also see $cookie is never set, looking at the code it should be 'Mysite' . $id. I added quotes for the string, though PHP will treat any unquoted text as string but avoid misunderstanding and errors later, its always a good idea.
Also this script assumes PHP option register_globals is on, you need to make that register_globals = ON in your php.ini
I found this script on about.com which I'm trying to learn from on how to create a rating system but the script gives me a warning that I listed below.
I was wondering how can I fix this problem? And what part of the code do I need to change and where?
Here is the warning below.
Warning: Division by zero on line 43
Here is the script below.
<?php
// Connects to your Database
mysql_connect("localhost", "root", "", "sitename") or die(mysql_error());
mysql_select_db("sitename") or die(mysql_error());
//We only run this code if the user has just clicked a voting link
if ( $mode=="vote")
{
//If the user has already voted on the particular thing, we do not allow them to vote again $cookie = "Mysite$id";
if(isset($_COOKIE[$cookie]))
{
Echo "Sorry You have already ranked that site <p>";
}
//Otherwise, we set a cooking telling us they have now voted
else
{
$month = 2592000 + time();
setcookie(Mysite.$id, Voted, $month);
//Then we update the voting information by adding 1 to the total votes and adding their vote (1,2,3,etc) to the total rating
mysql_query ("UPDATE vote SET total = total+$voted, votes = votes+1 WHERE id = $id");
Echo "Your vote has been cast <p>";
}
}
//Puts SQL Data into an array
$data = mysql_query("SELECT * FROM vote") or die(mysql_error());
//Now we loop through all the data
while($ratings = mysql_fetch_array( $data ))
{
//This outputs the sites name
Echo "Name: " .$ratings['name']."<br>";
//This calculates the sites ranking and then outputs it - rounded to 1 decimal
$current = $ratings[total] / $ratings[votes];
Echo "Current Rating: " . round($current, 1) . "<br>";
//This creates 5 links to vote a 1, 2, 3, 4, or 5 rating for each particular item
Echo "Rank Me: ";
Echo "Vote 1 | ";
Echo "Vote 2 | ";
Echo "Vote 3 | ";
Echo "Vote 4 | ";
Echo "Vote 5<p>";
}
?>
You need to make sure you aren't dividing using a 0. If the values you get for total and votes from MySQL are 0, you should bypass the division and set a fixed value.
//This calculates the sites ranking and then outputs it - rounded to 1 decimal
if($ratings['total'] > 0 && $ratings['votes'] > 0) {
$current = $ratings['total'] / $ratings['votes'];
}
else{
$current = 0;
}
P.S.
Note how I quoted the elements in the $ratings array. You should always do that.
// This is INCORRECT. Causes error notices if you have error reporting on.
// and can have other consequences if you happen to use a `total` constant.
$ratings[total];
// It should be
$ratings['total']
The problem is here
$current = $ratings[total] / $ratings[votes];
If there are no votes, you are dividing a number by zero. And that is bad :)
Add some verification that $ratings[votes] is set and it is not 0.