I have this PHP contact form which disallows a submission from an existing IP. I am trying to add the feature to submit one entry per IP, per day.
I have a column in my db table called Date which is datestamping every row. I know I need to create my if statement with 2 conditions... I am just not sure how to check the DB before submitting a new entry. Any help is appreciated. Thanks.
CODE SNIPPET:
$ip = gethostbyname($_SERVER['REMOTE_ADDR']);
mysql_select_db($database, $connection);
$QUERY = "SELECT COUNT(IP) AS `count` FROM `contest` WHERE IP = '$ip'";
$RESULT = mysql_query($QUERY) or die(mysql_error());
// Read the firs row
$row = mysql_fetch_assoc($RESULT);
// Check how many rows MySQL counted
if($row['count'] > 0) {
header ('Location: valueexists.html');
}
else {
//save the data on the DB
mysql_select_db($database, $connection);
$insert_query = sprintf("INSERT INTO contest (Name, Email_Address, Phone, Company_Name, Company_Address, Date, ip) VALUES (%s, %s, %s, %s, %s, NOW(), %s)",
Your structure is correct, to make a query with two conditions, simply add a AND to it:
$query = "SELECT COUNT(ip) AS count FROM contest WHERE ip = '$ip' AND DATE(date) = CURDATE()";
This will count all rows in the contest table with that IP and which have been submitted on that specific date. Note that I took "date" as your fieldname as I'm unaware of your table structure, so adapt it to the one you created.
Edit
I just noticed you are using NOW() to store your datetime in your database, so I changed my query to make use of the DATE() function. This extracts the date part of the date or datetime expression of the value as can be seen here.
Hope this helps!
You are going to want to do something similar to:
$count = mysql_num_rows(mysql_query("SELECT * FROM contest WHERE IP ='".$IP."'"));
if($count > 0) {
$error = '<div class="error_message">Sorry, username already taken.</div>';
}
Simply put, you are just querying the database to see if an IP exists, mind you this should probably be wrapped in a if(isset($_POST['add_user'])) { } to detect if the form was indeed submitted by this form ID alone.
you can use strtotime('midnight') to get the timestamp of the start of today. When you include this in the query you make sure that mysql only returns entries from today:
$query = "SELECT COUNT(ip) AS count FROM contest WHERE ip = '$ip' AND DATE > " . strtotime('midnight');
Related
Here is My Code. Its all working fine. But Some Times it inserting Duplicate Data. Why? I mean i placed the code so that same quize_no and phone combination should not submitted. But Some time its Inserting the Same quize_no and phone combination. Why is this Happening?
$sql = mysqli_query($con,"SELECT * FROM user_mm WHERE phone='$phone'");
while($row = mysqli_fetch_array($sql)) {
$name = $row['name'];
}
date_default_timezone_set("Asia/Dhaka");
$date = date('Y-m-d');
$time = date('h:i:s a', time());
$result = mysqli_query($con,"SELECT id FROM score_mm WHERE phone='$phone' AND quize_no='$quize_no' ");
$count=mysqli_num_rows($result);
if($count>0)
{
echo "1";
}
else
{
// Here I am Inserting Value in to Database
$query = mysqli_query($con,"insert into score_mm(name, phone, quize_no, score, date, time) values ('$name', '$phone','$quize_no', '$score', '$date', '$time')");
echo "Score Submitted Succesfully";
mysqli_close($con);
}
If there should truly never be a situation where you end up with duplicate quize_no and phone combinations in that table, then the first thing you should do is change your table structure to add a unique key to those columns.
For example:
ALTER TABLE score_mm ADD UNIQUE (quize_no, phone);
This won't fix whatever is causing multiple insert requests to be called, but it would at least protect your data integrity by not allowing any rows with duplicate value combinations.
I have a table with a user id and a date, several users connect at the same time and only one user a day can do insert in the database.
I have a slow connection to the server and what it takes to do the select of the last entry, whether it has been today or not, since it can not be a primary key because the date can vary, sometimes it makes double registrations for the same day.
How can I do this so that this does not happen and I only insure an insert a day?
Thank you
Code:
<?php
$sql = "SELECT MAX(timestamp_pole) as last_pole FROM pole WHERE id_group = ". $id_grup;
$resultado = $mysqli->query($sql);
$resultado = $resultado->fetch_assoc();
$las_00 = date('Y-m-d');
$las_00 = strtotime($las_00);
if ($resultado['last_pole'] >= $las_00){
} else {
$sql = "INSERT INTO pole (timestamp_pole, id_user, id_group) VALUES (". $timestamp .",". $user['id'] .",". $id_group .")";
$mysqli->query($sql);
//return addslashes($sql);
if (isset($user['username']))
return "#". $user['username'] ." pole!";
else
return $user['name'] ." pole!";
}
?>
you can create unique index using (date, id_group) as key, by that way you can make sure that there isn't any duplicated date in same group. Also remember to implement try/ catch as running insert query.
I host multiple servers for multiplayer games and I am requiring some help with creating a PHP MySQL script.
I have made scripts for the game servers that output a few variables to a php script. These variables include the player name, a GUID number (Game User ID) and a couple other unimportant things. These are sent to the php script every time a player joins the server.
Anyway what I basically need it to do is every time a player joins the server it saves the player name, guid and join date/timestamp to a row in a MySQL table. The player will always have only one GUID code, which is sort of like their cd-key. What I have at this current time:
if ( $action == "save")
{
$name = mysql_real_escape_string($_GET['name']);
$guid = mysql_real_escape_string($_GET['guid']);
}
mysql_query("INSERT INTO `players` (`name`, `guid`) VALUES ('$name', '$guid') ON DUPLICATE KEY UPDATE `last_joined`=CURRENT_TIMESTAMP")or die(mysql_error());
echo "-10";
die();
Now, this works great as it is. But what I need it to do is; if the player comes on the server with a different name, it will log that instance into a new row and if they come on again with the same name it will update the same row with the current time stamp. And for instance, if they change their name back to the first name they use it will update the row that has that name recorded with the current time stamp.
The only thing I have tried is making the 'name' column, a primary key and on a duplicate entry it would update it. However if I did that and another player came on the server with the same name it would just update the last player's data.
So it needs to record every username a player uses.
There's probably quite a simple solution but I've never had the time to learn to MySQL and I need this done soon.
Thanks for any help.
Make the GUID the primary unique key.
Then instead of just inserting the row, check if that guid exists in the database first and then if it does, update the row. If it doesn't then you can insert it.
You can take a shot for this:
$guid = mysqli_real_escape_string($conn, $_GET["guid"]);
$name = mysqli_real_escape_string($conn, $_GET["name"]);
if (!empty($guid) && !empty($name)) {
//Check if the user exists
$sql = "SELECT COUNT(*) AS cnt FROM players WHERE guid = " . $guid;
$res = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($res);
if ($row['cnt']) {
//If yes, update
$sql = "UPDATE players SET `last_joined` = NOW()
WHERE `guid` = " . $guid;
} else {
//If no, insert
$sql = "INSERT INTO players (`guid`, `name`, `last_joined`)
VALUES (" . $guid . ", '" . $name . "', NOW())";
}
mysqli_query($conn, $sql);
echo "-10";
die();
} else {
echo 'Missing parameter';
die();
}
NOTE:
I am using mysqli fucntions, because mysql functions are deprecated. You can use PDO also.
I’ve created a little weekly trivia game for my website. Basically its five questions, then at the end the user can add their score to a scoreboard.
The problem is that I want the scores to carry from week to week and cumulate. So let’s say you got 4 points one week, then 5 points the next. I want the scoreboard to reflect you have 9 points.
So I created a small form with an i
nvisible field that has the users score, a field for the username, and a field for the e-mail address. Next week, when the user takes the quiz again, I want their score to be updated if the username and e-mail match a record in the database. If no record does match, I want an entry to be created.
Here’s the script I came up with, however, it doesn’t work (which doesn’t surprise me, I’m pretty new to PHP/MySQL)
$name = $_POST['name']; //The Username
$score = $_POST['submitscore']; //The users score (0-5)
$email = $_POST['email'];//Users email address
$date = date("F j, Y, g:i a");//The date and time
if($name != '') {
$qry = "SELECT * FROM scoreboard WHERE name='$name'";
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) > 0) {
$sum = ($row['SUM(score)']+$score);
"UPDATE scoreboard SET score = '$sum' WHERE name = '$name'";
}
else
$q = mysql_query("INSERT INTO scoreboard (`name`, `email`, `date`, `score`) VALUES ('$name', '$email', '$date', '$score');");
#mysql_free_result($result);
}
else {
die("Query failed");
}
}
My table scoreboard looks like this
id........name........email...........date...........score
1........J.Doe.....j.doe#xyz.com.....7/27/11.........4
You're looking for INSERT... ON DUPLICATE KEY syntax
"INSERT INTO scoreboard (`name`, `email`, `date`, `score`) ".
" VALUES ('$name', '$email', '$date', '$score') ".
"ON DUPLICATE KEY UPDATE `score` = $sum";
Aside:
Use mysql_real_escape_string!
$name = mysql_real_escape_string( $_POST['name'] );
$score = mysql_real_escape_string( $_POST['submitscore'] );
$email = mysql_real_escape_string( $_POST['email'] );
$date = date("F j, Y, g:i a");//The date and time
EDIT
First, this doesn't really work unless you have a column SUM(SCORE):
$sum = ($row['SUM(score)']+$score);
If you want the sum of a column, you need to put that in the MySQL query directly. If you just want the score for that row, however, you can use $row['score']. If you need to add to an existing score you don't need to select for the value (thanks to a1ex07 for pointing this out)
ON DUPLICATE KEY UPDATE `score` = $score + score
This line is incorrect:
$sum = ($row['SUM(score)']+$score);
You probably want to replace it by:
$sum = ($row['score']+$score);
As you are new to PHP/MySQL I recommend you to read about MySQL Injections as your queries contain potential risks.
I'd have a database table to hold quizzes; a database table for members; and a database table that contains foreign keys to both tables along with a score so only one record can be created for each member and each quiz.
I'd also save the score in a session when the user finishes the quiz so the user can't then just submit any old score to your database; the score entered is the score your application generated.
This way, you can then just query SUM(score) of a member based on that member's ID.
I am taking a calendar feed with a PHP file and I need to compare it to my database. If the $lastEdited variable is different than what is in the database, I need to change the record. I'm really new to SQL, so I'm not sure what to do. I just have Date_Edited set as a VARCHAR so I just need to compare the strings. I have this:
$query = "SELECT * FROM myTable WHERE Event_ID='$id'";
$result = mysql_query($query);
if (!mysql_num_rows($result)) {
mysql_query("INSERT INTO myTable (Event_ID, Date_added, Date_edited, Title)
VALUES ('$id', '$dateAdded', '$lastEdited', '$title')");
}
How do I compare $lastEdited to Date_edited and change the row if they are different?
you need to do something like
$row = mysql_fetch_array($result, MYSQL_ASSOC);
if($lastEdited != $row['Date_added']){
# run update query
mysql_query("update myTable set
// here insert all update fields you need like
Date_added = '$dateAdded', Date_edited = '$lastEdited' , Title = '$title'
WHERE Event_ID='$id' ");
}
You probably want to use the UPDATE statement.