Alright, I’m trying to make it so that someone can vote for a “server” every 24 hours, but currently, I’m stuck here:
function vote1() {
$pull = $_SERVER['REMOTE_ADDR'];
$votersIp = "select votersIp from voters";
$usersIp = $_SERVER['REMOTE_ADDR'];
$fetch = mysql_query("SELECT * FROM voters WHERE votersIp = '".$_SERVER['REMOTE_ADDR']."'");
while($rude = mysql_fetch_array($fetch)){
if($rude[votersIp] != $pull) {
$zoot="INSERT INTO voters (votersIp, lastVoted) VALUES ('$usersIp', '0')";
mysql_query($zoot) or die ( mysql_error() );
echo 'Voters IP not in database'; //debugging
}
if($rude[votersIp] = $pull) {
echo 'found ip'; //debugging
}
}
So, if you can’t tell, I’m trying to make it so that everytime someone votes, it adds their IP address to the database. I know I’m doing something very basic wrong here, but I’m still learning.
I would appreciate it if you could post the fix, but also explain what I’m doing wrong, and any suggestions would be great as well.
Thank you!
There are several problems in your code.
A close bracket
}is missing, either for thewhileor for thefunctionWe don’t need to loop through all the voters table to find out if an IP is in the database or not. We can simply use a
WHEREclause in the SQL command, like this:SELECT votersIp FROM voters WHERE votersIp = $userIpThere are a lot of unnecessary variables with strange names.
As a security measure, anything we will use as a part of a SQL command should be escaped, to avoid being vulnerable to some types of attacks.
When array indexes are strings, they should be between quotes. So,
$rude[votersIp]is wrong, while$rude['votersIp']is correct. (Without quotes, PHP interprets it as a constant, instead of a string.)The
$rude[votersIp] = $pullstatement is a variable assignment. You should use the correct operator==to compare values:$rude[votersIp] == $pullBad indentation makes the code harder to be understood for us, human readers. Good indentation is better.
The
whileloop is done upon the results of the query which searchs for a specific IP. This means the first condition of theifinside it will NEVER be true (a different IP), so never theINSERTwill run.Here is an improved version:
Suggestion: you should read and study a good book about programming for beginners. As I can’t recommend a specific book for you, I suggest you ask for a book recommendation. A good book to learn how to program, for beginners.