954,585 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Help with some loops and SQL

I am having a problem with some of this code:

<?php

$q = "SELECT * FROM entries";
$r = mysql_query($q);

if(mysql_num_rows($r)>0):
	while($row = mysql_fetch_assoc($r)):
		$net_vote = $row['votes_up'] - $row['votes_down'];

		$row_id = $row['id'];

?>
<div class='entry'>

	<span class='link'>
		<a href='<?php echo $row['link']; ?>'> <?php echo $row['title']; ?> </a>
	</span>

	<span class='votes_count' id='votes_count<?php echo $row['id']; ?>'><?php echo $net_vote." votes"; ?></span>

	<span class='vote_buttons' id='vote_buttons<?php echo $row['id']; ?>'>
			<?php

				$p = "SELECT * FROM entries";
				$s = mysql_query($p);
				$ip = $_SERVER['REMOTE_ADDR'];

				while($rowp = mysql_fetch_assoc($r)) {

					if ($row['user_ip'] == $ip) {

						noVote();
						break;

					} else {

						$plyList = htmlspecialchars($row_id, ENT_QUOTES);
						checkCookieVote($plyList);
						break;

					}
				}

			?>
	</span>

</div>
<?php
	endwhile;
endif;
?>


What is is supposed to do is check if the users IP in the table 'uservotes' and if it is, see what storyid's are on the rows their IP occurs on, and not display the voting system on the story the user has already voted on (i.e. Their IP got logged when they voted).

First problem is that the first while loop is only displaying the first 3 records from the table 'entries' when it should be displaying all 5.

Secondly, it is showing the voting system beside each story after a refresh of the page.

The SQL tables are as follows:entries:id
title
link
votes_up
votes_down
uservotes:user_ip
story_id

Thanks guys,
Colm

Sanit
Newbie Poster
16 posts since May 2009
Reputation Points: 10
Solved Threads: 0
 

My guess is that the inner query is supposed to be querying the uservotes table, not the entries table. Also, you're using mysql_fetch_assoc on $r instead of $s. Don't use one letter variables, they are hard to follow and keep track of, as is obvious in this case.

ShawnCplus
Code Monkey
Team Colleague
1,583 posts since Apr 2005
Reputation Points: 526
Solved Threads: 268
 

Thanks for the reply.

I realise the mistakes I made in that code were very simple and stupid, but when I fixed them it was working, but not the way I wanted it to.

I re-thought what I needed to do and actually came up with simpler code using no loops which actually works perfectly.

Cheers,
Colm

Sanit
Newbie Poster
16 posts since May 2009
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You