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.
Related
I am designing an event feed from a calender I made. I'm using the same data from the database but to match specific dates and times.
I only want 4 events to show at once (why I specified length < 4)
Where the database value 'showFeed' is true, it only displays those rows.
and I want it to show by date time, I have odd id's for each value in the database, which might make them out of order.
My current code:
$sql = "SELECT `title`, `time`, `start`, `showFeed` FROM calender WHERE length('column') > '0'";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
echo "<div class=\"eventfeed\">";
echo "<ul>";
foreach ($result as $row){
$show = $row['showFeed'];
if ($show == 1 && length.$result < 4){
echo "<li>";
echo $row['title']. "<br />";
echo $row['start'].' '.$row['time'];
echo "</li>";
}
else {
return false;
}
}
echo "</ul>";
echo "</div>";
$dbh = null;
echo json_encode($return);
?>
I'm getting results and no errors from the database, but I'm only seeing one return on $results.
I honestly, do not have a clue where else to go from here. I'm lost.
For 1+.2.+3. modify your query to SELECT title, time, start, showFeed FROM calender WHERE length('column') > '0' and showFeed=1 and time<current_timestamp ORDER BY time DESC LIMIT 0,3 and remove your if (...) statement.
I don't know if this is your actual code, but you should determine the length of an array by doing $result.length instead of the other way around.
Also, you can limit the number of results in your query using 'LIMIT 4' at the end of your query. That way MySQL only returns 4 results and you don't have to worry about that in your code, just print everything.
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.
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
I've been searching for a week now on how to accomplish this but none of the tutorials have worked - I typically get a message "resource id 18."
I'm creating a bank simulation game.
End goal: I want a variable "$player_balance" to be the sum of all account balances owned by that player so that it can be displayed at the bottom of the table under account balances.
Here is my code, thanks for any help or direction that you can provide.
function displayMyAccounts(){
global $database, $session;
$q = "SELECT game_account_number,game_account_owner,game_account_name,game_account_balance FROM ".TBL_ACCOUNTS." WHERE game_account_owner='".$session->username."'";
$result = $database->query($q);
/* Error occurred, return given name by default */
$num_rows = mysql_numrows($result);
if(!$result || ($num_rows < 0)){
echo "Error displaying info";
return;
}
if($num_rows == 0){
echo "Database table empty";
return;
}
/* Display table contents */
echo "<table align=\"left\" border=\"1\" cellspacing=\"0\" cellpadding=\"3\" width=\"100%\">\n";
echo "<tr><td><b>Account Number</b></td><td><b>Account Name</b></td><td><b>Balance</b></td></tr>\n";
for($i=0; $i<$num_rows; $i++){
$anumber = mysql_result($result,$i,"game_account_number");
$aowner = mysql_result($result,$i,"game_account_owner");
$aname = mysql_result($result,$i,"game_account_name");
$abalance = mysql_result($result,$i,"game_account_balance");
setlocale(LC_MONETARY, 'en_US');
$abalance2 = money_format('%(#10n', $abalance);
echo "<tr><td>$anumber</td><td>$aname</td><td>$abalance2</td></tr>\n";
}
echo "<tr><td></td><td></td><td>$player_balance</td></tr>\n";
echo "</table><br>\n";
}
displayMyAccounts();
The above code is what appears on each player's "account page." I want the sum of their accounts to appear on the last row. Thanks for any help, I'll continue searching and trying in the meantime.
Here is the output based on the above:
Account Number Account Name Balance
1000083690 Maverick $ 50,000.00
1000083696 WellsFargo $ 50,000.00
1000083697 Wachovia $ 50,000.00
Don't use mysql_result(). It's slow and inefficient, and what you're doing is better done with mysql_fetch_assoc():
$player_balance = 0;
// Also, ditch the for loop. This is the typical convention for retrieving results.
while ($row = mysql_fetch_assoc($result)) {
$abalance1 = money_format('%(#10n', $row['game_account_balance']);
echo "<tr><td>{$row['game_account_number']}</td><td>{$row['game_account_name']}</td><td>$abalance1</td></tr>\n";
// Now add to the balance
$player_balance = $player_balance + $row['game_account_balance'];
}
// And output your balance
$abalance_sum = money_format('%(#10n', $player_balance);
echo "<tr><td></td><td></td><td>$abalance_sum</td></tr>\n";
resource error means
YOU DO NOT HAVE THE TABLE OR THE PERMISSION, OR YOU ARE TRY TO ACCESS A COLUMN WHICH DOES NOT EXIST
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