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.
Related
<? require ("tracker.php");
?>
<center>
<?php
include 'dbc.php';
?>
<title>J~Net Level Up</title>
<?php session_start();
$id = $_SESSION['user_id'];
// Connects to your Database
mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db("messages") or die(mysql_error());
$data = mysql_query("UPDATE `users` SET `balance` = `balance` - 1000 WHERE `users`.`id` =$id")
or die(mysql_error());
echo "<table border cellpadding=3>";
while($info = mysql_fetch_array( $data ))
{
echo "<tr>";
echo "<th>User:</th> <td>".$info['user_name'] . "</td> ";
echo "<th>Balance:</th> <td>".$info['balance'] . " </td></tr>";
}
echo "</table>";
// echo "Balance Is ".$_SESSION['balance'];
echo $row['user_name'] . " " . $row['balance'];
?>
<META HTTP-EQUIV=REFRESH CONTENT="0; URL=010101levup.php">
as you can see in above code it doesnt check if balance is available before it executes and balance goes into minus, is there a simple way it can have a if statement to make sure balance is available first before it executes the sql statement?
please help with this minor glitch what i need is a pro to edit the above code not tell me what lines needs to be added as before when this happens its untested and when i test it it fails so i need it to make sure balance is in there and if yes it goes to that refresh line (at bottom of code block),
and if there is insufficient funds it should return an error and not goto last line of code.
Please help if you can i can supply any sql you may need for this to test your end if required!
Add some extra logic to the where clause:
$update = 1000;
UPDATE users
SET balance = balance - $update
WHERE (users.id = $id) AND
(balance >= $update)
The update will still run, but only actually change the record if the balance is high enough to begin with.
Thanks in advance!
I have a simple mysql and php blog that I built based on a tutorial I found online. What I would like to be able to do, but have no idea how to go about it, is this:
I would like a picture (avatar) to be displayed with each comment on each post. The picture that is chosen would be based off of the name in the Posted By: area of the comment. So for instance: Let's say me, the admin, leaves a comment on the thread. My name is automatically pulled in via a '$_SESSION' variable so I don't have to worry about entering that each time. When the comment is displayed on the blog thread page, it shows Commented on By: Admin. This name is stored in the db and pulled in with the a php echo statement.
So what I want this avatar code to be able to do is
1) look at the area where the Commented on By: text is
2) read the text
3) see that it says Admin and display the admin.png image next to it. If it sees anything other than Admin in the Commented on By: area, then it will display something like guest.png
Here is a snippet of code I found in my stackoverflow and google searches. It works but it pulls in the guest image 6 times, then the actual admin.png image, and then the guest image 3 more times. And it displays this way on EACH comment on EACH thread! And when I add a new thread and a new comment to that thread, it adds the guest image again at the end of the multiple images being displayed on each comment. Did I set it up wrong?
<?
$sql = "SELECT comment_user FROM comments";
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) != 0) {
$counter = $starting + 1;
$pathImg = "images/";
while ($row = mysql_fetch_array($result)) {
//calculate url image
$pathFile = $pathImg . $row['comment_user'] . ".png";
if (!file_exists($pathFile)) {
$pathFile = $pathImg . "guest.png";
}
?>
<img src="<?=$pathFile?>" alt="<?=$row['comment_user']?>">
</p>
<?
$counter++;
}
}
?>
This displays out as (Guest Image)(Guest Image)(Guest Image)(Guest Image)(Guest Image)(Guest Image)(Admin Image)(Guest Image)(Guest Image)(Guest Image).
Any help on throwing something together would be great! Trying to keep it simple to!
EDIT:
This is how the comments are displayed, along with the code from FlyingGuy's answer.
<?php
foreach ($post['comments'] as $comment){
$commentCount = 0 ;
$sql = "SELECT comment_user FROM comments";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$commentCount++ ;
$pathImg = "images/";
$pathFile = $pathImg . $row['comment_user'] . ".png";
if (!file_exists($pathFile)) {
$pathFile = $pathImg . "guest.png";
}
echo "<img src=\"". $pathFile ."\" alt=\"". $row['comment_user'] ."\"\><br>";
}
?>
<h4>By <?php echo $comment['user']; ?> on <?php echo $comment['date']; ?></h4>
<p><?php echo $comment['body']; ?></p>
<hr />
<?php
}
?>
This is how the functions look for displaying and adding comments:
function get_comments($pid){
$pid = (int)$pid;
$sql = "SELECT `comment_body` AS `body`, `comment_user` AS `user`, DATE_FORMAT(`comment_date`, '%m/%d/%Y') AS`date` FROM `comments` WHERE `post_id` = {$pid}";
$comments = mysql_query($sql);
$return = array();
while (($row = mysql_fetch_assoc($comments)) !== false){
$return[] = $row;
}
return $return;
}
// adds a comment
function add_comment($pid, $user, $body){
if (valid_pid($pid) === false){
return false;
}
$pid = (int)$pid;
$user = mysql_real_escape_string(htmlentities($user));
$body = mysql_real_escape_string(nl2br(htmlentities($body)));
mysql_query("INSERT INTO `comments` (`post_id`, `comment_user`, `comment_body`, `comment_date`) VALUES ({$pid}, '{$user}', '{$body}', NOW())");
return true;
}
?>
Look what you are trying to do is select the image that matches the name of the user in the current row of your result set. So you will set your image file variable as appropriate for each row and you are sending that to the browser.
For starters and can see the probability of case issues here. Are all user names forced to lower case and all image names forced to lower case? If this is on a linux box that is a land mine on windows not so much, but this should be taken into account.
It will set an image name for each row of your queries result set so it will look like:
[image] [comments]
[image] [comments]
[image] [comments]
if you have three rows in your result set.'
Personally I avoid all of the turning php on and off all over the place. Concat a single string and then simply echo it out for each row. So I would code it like so:
<?
$commentCount = 0 ;
$sql = "SELECT comment_user FROM comments";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$commentCount++ ;
$pathFile = $pathImg . $row['comment_user'] . ".png";
if (!file_exists($pathFile)) {
$pathFile = $pathImg . "guest.png";
}
echo "<img src=\"". $pathFile ."\" alt=\"". $row['comment_user'] ."\"\><br>";
}
So I have eliminated a lot of things from your code example like counters etc. You don't really need to check and see if there are rows since the while loop simply will not execute of there are no rows so you will simply have a question of comment with no subordinate comments and it will only send the image link if there are comments.
No if it were me doing this I would create an avatar file name is the user table and store the path to those as part of the system configuration which would be part of the global set of variables that are always present. Your query would then join in the users table and the image name or guest image would be in your result set. A bit more complex but much cleaner and it simplifies your code.
One of the reasons I don;t like dynamic typing. $row was being mutated to an array of ALL the rows..
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 am doing a project where I want a person to enter the name of any artist/band into a text box where it will seach my mysql database for the event information and display the results/content on another page. The code below is within my index.php where it should get the information from search.php (below also). I've looked all over and I'm not sure why it's not working and I can't figure out what to do. Help would be great! (I really need to pass this class!) :)
(index.php)
<form name="search" action="search.php" method="get">
<div align="center"><input type="text" name="q" />
<p><input type="submit" name="Submit" value="Search" /></p>
</form>
(search.php)
<?php
//Get the search variable from URL
$var=#&_GET['q'];
$trimmed=trim($var); //trim whitespace from the stored variable
//rows to return
$limit=10;
//check for an empty string and display a message.
if($trimmed=="")
{
echo"<p>Please enter a name.</p>";
exit;
}
//check for a search parameter
if(!isset($var))
{
echo"<p>We don't seem to have a search parameter!</p>";
exit;
}
//connect to database
mysql_connect("localhost","root","password");
//specify database
mysql_select_db("itour") or die("Unable to select database");
//Build SQL Query
$query = "select * from events where artist_name like \"%trimmed%\" order by date";
$numresults=mysql_query($query);
$numrows=mysql_num_rows(numresults);
//If no results, offer a google search as an alternative
if ($numrows==0)
{
echo"<h3>Results</h3>";
echo"<p>Sorry, your search: "" .$trimmed . "" returned zero results</p>";
//google
echo"<p><a href=\"http://www.google.com/search?q=".$trimmed . "\" target=\"_blank\" title=\"Look up ".$trimmed ." on Google\">
Click here</a> to try the search on google</p>";
}
//next determine if s has been passed to script, if not use 0
if(empty($s)) {
$s=0;
}
//get results
$query .=" limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
//display what was searched for
echo"<p>You searched for: "" .$var . ""</p>";
//begin to show results set
echo "Results";
$count = 1 + $s;
//able to display the results returned
while ($row=mysql_fetch_array($result)) {
$title = $row["artist_name"];
echo"$count.) $title";
$count++;
}
$currPage = (($s/$limit) + 1;
echo"<br />";
//links to other results
if ($s>=1){
//bypass PREV link if s is 0
$prevs=($s-$limit);
print" <a href=\"$PHP_SELF?s=$prevs&q=$var\"><<
Prev 10</a> ";
}
//calculate number of pages needing links
$pages = intval($numrows/$limit);
//$pages now contains int of pages needed unless there is a remainder from diviison
if($numrows%$limit){
//has remainder so add one page
$pages++;
}
//check to see if last page
if (!((($s+$limit)/$limit)==$pages) && $pages!=1){
//not last page so give NEXT link
$news = $s+$limit;
echo " Next 10 >>";
}
$a = $s +($limit);
if($a > $numrows){$a = $numrows;}
$b = $s + 1;
echo "<p>Showing results $b to $a of $numrows</p>";
?>
Your where clause is goofy...try changing it to:
WHERE artist_name like '%$trimmed%'
just putting trimmed will be interpreted literally as the string "trimmed". However, using the variable $trimmed in your double-quoted string will give the actual variable's value.
$query = "select * from events where artist_name like '%$trimmed%' order by date";
In order to use the variable $trimmed in a query, escape it first. Otherwise, your script will be vulnerable to SQL injection attacks, and attackers will be able to run almost any query against your database. This problem is exacerbated by the fact that you are connecting to MySQL as root. Never ever do this in a production environment.
Also, to expand a variable in a string, you should include the $ character before the variable name.
$trimmed = trim($var);
$escaped = mysql_real_escape_string($trimmed);
$query = "select * from events where artist_name like \"%$escaped%\" order by date";
Your code still looks all over the place. I think the main reason it wasn't working was the mixing of " and '. You need to escape variables before you use them in your queue. mysql_real_escape_string is the lowest form of escaping you should be using. I'd recommend you have a look at PDO though.
<?php
//Get the search variable from URL
$var = $_GET['q'];
$trimmed = mysql_real_escape_string(trim($var)); //trim whitespace and escape the stored variable
//rows to return
$limit = 10;
//check for an empty string and display a message.
if($trimmed == "") {
echo"<p>Please enter a name.</p>";
exit;
}
//check for a search parameter
if(!isset($var)){
echo"<p>We don't seem to have a search parameter!</p>";
exit;
}
//connect to database
mysql_connect("localhost","root","password");
//specify database
mysql_select_db("itour") or die("Unable to select database");
//Build SQL Query
$query = "SELECT * FROM events WHERE artist_name LIKE %$trimmed% ORDER BY DATE";
$numresults = mysql_query($query);
$numrows = mysql_num_rows(numresults);
//If no results, offer a google search as an alternative
if ($numrows==0){
echo"<h3>Results</h3>";
echo"<p>Sorry, your search: "" .$trimmed . "" returned zero results</p>";
//google
echo"<p><a href=\"http://www.google.com/search?q=".$trimmed . "\" target=\"_blank"\ title=\"Look up ".$trimmed ." on Google\">
Click here</a> to try the search on google</p>";
}
//next determine if s has been passed to script, if not use 0
if(empty($s)) {
$s=0;
}
//get results
$query .=" limit $s,$limit";
$result = mysql_query($query) or die("Couldn't execute query");
//display what was searched for
echo"<p>You searched for: "" .$var . ""</p>";
//begin to show results set
echo "Results";
$count = 1 + $s;
//able to display the results returned
while ($row = mysql_fetch_array($result)) {
$title = $row['artist_name'];
echo $count.' '.$title;
$count++;
}
$currPage = (($s/$limit) + 1;
echo "<br>";
//links to other results
if ($s>=1){
//bypass PREV link if s is 0
$prevs=($s-$limit);
echo ' <a href="'.$PHP_SELF.'?s='.$prevs.'&q='.$var.'"><<';
echo 'Prev 10</a> ';
}
//calculate number of pages needing links
$pages = intval($numrows/$limit);
//$pages now contains int of pages needed unless there is a remainder from diviison
if($numrows%$limit){
//has remainder so add one page
$pages++;
}
//check to see if last page
if (!((($s+$limit)/$limit)==$pages) && $pages!=1){
//not last page so give NEXT link
$news=$s+$limit;
echo ' Next 10 >>';
}
$a = $s +($limit);
if($a > $numrows){$a = $numrows;}
$b = $s + 1;
echo '<p>Showing results '.$b.' to '.$a.' of '.$numrows.'</p>';
?>
You are missing a $ symbol. I think
$var=#&_GET['q'];
should probably be
$var=#$_GET['q'];
unless you really want a reference, in which case it should be this: (the error suppression is not needed at this point if you want a reference, but you should check $var is set before trying to access it)
$var=& $_GET['q'];
I would be tempted to write it a bit more like this.
if (!isset($_GET['q'])) {
echo"<p>We don't seem to have a search parameter!</p>";
exit;
}
$trimmed = trim($_GET['q']);
if($trimmed=="") {
echo"<p>Please enter a name.</p>";
exit;
}
Also as Chad mentioned, an sql injection would be simple since you arent cleaning input before performing DB actions with it.
try adding
foreach($_REQUEST as $param => $value)
{
$_REQUEST[$param]=mysql_real_escape_string($value);
}
This way you escape all the user input so the user cant tamper with the db. Read more about this method and sql injection in the docs here:
http://us2.php.net/mysql_real_escape_string
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.