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
Related
I have a problem here with break and loops things in php.I have an input type, if I give the id 2 for ex, if there is 2 in db then only "You liked this url already" should be appear.This works. If I give then id 3 it says "Data added".Good for now.But if I enter again id 3 it says:
Data added!You liked this url already
and a new value of 3 is posting in the db.How to avoid this? Here is my function:
<form method="post">
Url id: <input type="text" name="urlid" id="urlid">
<input type="submit" name="givelikes" value="Give Likes">
<br />
<br />
</form>
<?php
if(isset($_POST['givelikes'])){
$urlid = $_POST['urlid'];
$con = mysqli_connect('localhost','root','root', 'db');
$user = $_SESSION['sess_user'];
$query=mysqli_query($con,"SELECT likes FROM users WHERE user='".$user."'");
$row = mysqli_fetch_array($query);
$array = explode(" ", $row['likes']);
foreach ($array as $value) {
echo $value;
echo $urlid;
if($value == $urlid){
echo "You liked this url already";
break;
}
else{
$array = $row['likes'];
$array .= " ";
$array .= "$urlid";
$query = ("Update users set likes = '".$array."' where user = '".$user."'");
if(mysqli_query($con,$query)){
echo "Data added!";
}
else{
echo "ERROR: Could not able to execute sql: " . mysqli_error($con);
}
}
}
}
?>
Currently you're looping through all "likes" and comparing them. So the sequence of steps is like this:
Enter 2
No likes yet, so the data is added
Enter 2
Loop over likes, find 2, data was already added
Enter 3
Loop over likes, find 2, not match so data is added
Enter 3
Loop over likes, find 2, not match so data is added
Continue looping, find 3, data was already added
Correcting this is going to involve changing your design a bit. Right now you have one de-normalized record with a string of space-delimited "likes". Normalize your data. Have one record per "like". And instead of constantly updating a single record, insert new records.
Then when you want to see if a "like" already exists, you can use a WHERE clause. Something like this:
SELECT * FROM users WHERE user=? AND like=?
(Note: This is using query parameters as a prepared statement. This is highly recommended. Your current code is wide open to SQL injection.)
If any record is found at all, then the item was "already liked" and you can output the message. If no record was found, INSERT a new one for that "like".
No need for a loop.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
mysql_fetch_array() expects parameter 1 to be resource, boolean given in select
Okay, so I have my page "List Customers" which then links to "List Jobs" adding on ?custID= into the URL, then on List jobs I have used $_GET["custID"] so my query uses the custID from the URL. that works fine, lists out my jobs for said customer using their ID.
My problem comes up now, I need the links on this page to give my third page the techID as well. But the techID is in jobDetails, so my query cannot give them the techID as it is querying my job section.
This is my "ListJobs.php" page, which upon choosing a customer in the page before it, loads this page with the url ListJobs.php?custID=001 (001 being an example, it will give the number depending on your choice of customer).
<?php
// Get data from the database depending on the value of the id in the URL
mysql_select_db($database_con_sim5, $con_sim5);
$query_Recordset1 = "SELECT * FROM job WHERE custID=" . $_GET["custID"] ;
$Rs1 = mysql_query($query_Recordset1);
// Loop the recordset $rs
while($row = mysql_fetch_array($Rs1)) {
$strName1 = $row['jobID'] . " " . $row['jobDesc'] . " " . $row['computerName'];
$strLink = "<a href = 'jobDetails.php?jobID=".$row['jobID']."'>".$strName1."</a>";
// Write the data of the person
echo "<li>" . $strLink . " </li>";
}
// Close the database connection
mysql_close();
?>
Then on pressing one of the links, link to jobDetails.php?jobID= with the job number.
I am able to show all the details in Job Detail with this, but I also need my Tech Name to appear, Tech Name is not in Job Details, but Tech ID is.
Here is my Job Details page coding :
<?php
// Get data from the database depending on the value of the id in the URL
mysql_select_db($database_con_sim5, $con_sim5);
$query_Recordset1 = "SELECT * FROM jobDetail WHERE jobID=" . $_GET["jobID"] ;
$query_Recordset2 = "SELECT technician.techName FROM technician
WHERE techID=" . $query_Recordset1["techID"] ;
$Rs1 = mysql_query($query_Recordset1);
$Rs2 = mysql_query($query_Recordset2);
while($row1 = mysql_fetch_array($Rs1)) {
while($row2 = mysql_fetch_array($Rs2)) {
echo "<dt><strong>Job Note ID:</strong></dt><dd>".$row1["jobNoteID"]."</dd>";
echo "<dt><strong>Job Notes:</strong></dt><dd>".$row1["jobNotes"]."</dd>";
echo "<dt><strong>Date Completed:</strong></dt><dd>".$row1["dateCompleted"]."</dd>";
echo "<dt><strong>Time Spent:</strong></dt><dd>".$row1["timeSpent"]."</dd>";
echo "<dt><strong>Job ID:</strong></dt><dd>".$row1["jobID"]."</dd>";
echo "<dt><strong>Technician ID:</strong></dt><dd>".$row1["techID"]."</dd>";
echo "<dt><strong>Technician Name:</strong></dt><dd>".$row2["techName"]."</dd>";
}
}
// Close the database connection
mysql_close();
?>
The error I am getting is:
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in D:\xampp\htdocs\Sim5Server\Pages\jobDetails.php on line 129
That line is:
while($row2 = mysql_fetch_array($Rs2)) {
I hope I am making any sense AT ALL.
To sum up, I need my final page to show data from mysql technician using the Primary/index key techID.
Some way to add techID onto either listJobs' links to job details or in job details' second Recordset.
EDIT:
I should probably state this will never be used on the net, I only need it to work for an assignment. in future, thanks to a comment, I will no longer be using mysql_* I am jsut using them as my entire workbook tells us to use it.
Try making this change in your jobDetails.php page
$query_Recordset1 = "SELECT * FROM jobDetail WHERE jobID=". (int) $_GET["jobID"];
$Rs1 = mysql_query($query_Recordset1) or die(mysql_error());
while($row1 = mysql_fetch_array($Rs1)) {
$query_Recordset2 = "SELECT technician.techName FROM technician
WHERE techID=" . $row1["techID"] ;
$Rs2 = mysql_query($query_Recordset2) or die(mysql_error());
while($row2 = mysql_fetch_array($Rs2)) {
For the second query you were using the result resource from executing the first query as techID. Also you will have to query for techName from inside the while loop fetching job details, since only then will you have the techID.
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 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.