I'm working on a script, but it won't work.
When a user makes a post, NOW() will be inserted. I want to make a script where the user will only be able to make a post when his last post differs at least 10 minutes from the post he wants to make at this moment. I don't want to make use of cookies, seeing people can delete them.
I have this code at the moment, but don't know how to move on. Thank you!
if ($db_found) {
$sql1="SELECT send_time FROM bloopp WHERE email='$email' ORDER BY id DESC LIMIT 1";
while($row = mysqli_fetch_array($result)) {
$last_post = $row['send_time'];
}
if ($last_post + 600 >= NOW() {
sql2 = "INSERT INTO bloopp (bloopp, browser, medium, send_time, email) VALUES
('$bloopp', '$browser', 'desktop', NOW(), '$email')";
$result = mysql_query($sql);
if($result) {
header('Location: index.php');
}
else {
echo "ERROR";
}
}
}
When dealing with time, it's handy if you can rely entirely on the database. This avoids mixing up the database conception of time with PHP's, which may be on different servers and/or have different time configuations.
So, try to locate a post made in the last ten minutes, and if there isn't one, you know you are good to go
SELECT COUNT(*) AS recent_posts
FROM bloopp
WHERE email=? AND (UNIX_TIMESTAMP(now()) - UNIX_TIMESTAMP(send_time))<600;
on the query you have :
sql2 = "INSERT INTO bloopp (bloopp, browser, medium, send_time, email) VALUES ('$bloopp', '$browser', 'desktop', NOW(), '$email')";
$result = mysql_query($sql);
shouldn;t that be
$sql = "INSERT INTO bloopp (bloopp, browser, medium, send_time, email) VALUES ('$bloopp', '$browser', 'desktop', NOW(), '$email')";
mind the sql2 / $sql replacement
Lets say you have table user
user_table:
id
email
bloop:
email
browser
....
Select * from user_table left join ( select max(send_time),email from bloop where email=$email ) max_sel on max_sel.email = user_table.email...
Something like this will get the user with his latest post (or null for new users who do not have a post, check put left joins), put the date in session and when he posts update it and such, you know how to do this.
Regards
Related
I'm trying to get the row ID after the slug (ex. post 1 returns "/bligpost.php?id=1").
Instead, it returns no ID.
Where am I doing it wrong? (I have included my other attempts in comments.)
mysql_connect("$hosty","$uname","$paswd");
#mysql_select_db($dbnme) or die( "Unable to select database");
$name=$_POST['Title'];
$slug="blogpost.php?id=";
$auth=$_POST['Author'];
$date=$_POST['Date'];
$cont=$_POST['Content'];
//$query = ("INSERT INTO Blogs (Name, URL, Content, Author, Date) VALUES ('$name', '$slug', '$cont', '$auth', '$date')");
mysql_query("INSERT INTO Blogs (id, Name, URL, Content, Author, Date) VALUES (NULL, '$name', '$slug', '$cont', '$auth', '$date')");
//$pind = mysql_query("SELECT LAST_INSERT_ID()");
mysql_query("UPDATE Blogs SET URL=blogpost.php?id=`id` WHIERE id=LAST_INSERT_ID()");
//mysql_query("UPDATE Blogs SET URL=blogpost.php?id=".$pind." WHERE Content=".$cont);
mysql_close();
Try with mysql_insert_id() like
mysql_query("INSERT INTO Blogs (id, Name, URL, Content, Author, Date) VALUES (NULL, '$name', '$slug', '$cont', '$auth', '$date')");
$id = mysql_insert_id();
echo "My Last Inserted Id ".$id;
Tr this LINK And dont use mysql_* functions due to they are depricated,instead of it,use mysqli_* or PDO statements
And try to update your update query like
mysql_query("UPDATE Blogs SET URL = 'blogpost.php?id=$id' WHERE id=$id");
EDIT Based on your commented query try like
mysql_query("UPDATE Blogs SET URL=blogpost.php?id=$pind WHERE Content='".$cont."'")
or
mysql_query("UPDATE Blogs SET URL=blogpost.php?id=$pind WHERE Content='$cont'")
What you're actually doing wrong in the commented line when assigning to $pind is you expect the mysql_query to return your new id, but what it actually returns is a resource from which you must get the id using mysql_fetch_row or any similar function from the mysql_fetch_ family.
As for the uncommented row with WHIERE id=LAST_INSERT_ID(), it would probably work, but you're not concatenating the prefix string with your id. You should do it like this:
mysql_query("UPDATE blogs SET url = CONCAT('blogpost.php?id=', id) WHERE id = LAST_INSERT_ID()");
On the other hand I don't approve of your design of holding your urls in the database when you already have everything you need in the database (i.e. the id), so you should just prepend the "blogpost.php?id=" to the id you get when selecting that row and you're all set, this url of yours is completely unnecessary.
Oh and people are correct when they say this is deprecated, but it seems you're still learning so this is probably a little easier to grasp than the mysqli approach so you can stick with it for now and move up to mysqli once you're comfortable.
Hope that helps. Good luck.
How about this?
$pind = mysql_insert_id();
http://php.net/manual/en/function.mysql-insert-id.php
$id = mysql_insert_id();
In table id field should be auto increment field
I am having some problems with a script, I am basically inputting data into a MySQL table. This data will be inserted in the table as 1 row.
Upon a row of data being entered into the table I want the current/specific row currently being entered to have the column 'account_type' to be updated from its default value 'member' to 'client'.
It's a long story why I need to do it this way but I do not want to simply just enter the value 'client' it must be updated from 'member' to client.
The script I have (which is the bit at the bottom) is currently doing just this but it is affecting all rows in the table, is there a way I can add a where clause to the update to say only affect the current row being entered and do not update all other rows in the table?
<?php ob_start();
// CONNECT TO THE DATABASE
require('../../includes/_config/connection.php');
// LOAD FUNCTIONS
require('../../includes/functions.php');
$username = $_POST['username'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$number = $_POST['number'];
$dob = $_POST['dob'];
$accounttype = $_POST['accounttype'];
$query="INSERT INTO ptb_registrations (
username,
password,
firstname,
lastname,
email,
number,
dob,
accounttype,
date_created )
VALUES(
'".$username."',
'".$password."',
'".$firstname."',
'".$lastname."',
'".$email."',
'".$number."',
'".$dob."',
'".$accounttype."',
now()
)";
mysql_query($query) or die();
$query="INSERT INTO ptb_users (
first_name,
last_name,
email,
password )
VALUES(
'".$firstname."',
'".$lastname."',
'".$email."',
MD5('".$password."')
)";
mysql_query($query) or dieerr();
$result = mysql_query("UPDATE ptb_users SET ptb_users.user_id = ptb_users.id,
ptb_users.account_type = 'Client'");
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
You can use the MySQL function LAST_INSERT_ID() to do this.
The old ext/MySQL extension exposes this functionality through mysql_insert_id(), but you can also access it directly, and more cleanly, and safely, in a query.
So you can do something like this:
$result = mysql_query("
UPDATE ptb_users
SET ptb_users.user_id = ptb_users.id,
ptb_users.account_type = 'Client'
WHERE id = LAST_INSERT_ID()
");
I know you say "it's a long story..." But what you are doing makes little-to-no sense. I can only imagine you are doing this because of a trigger - and that demonstrates quite nicely why triggers are generally a bad idea ;-)
Please try and re-think your design if at all possible.
Get the inserted ID after your first query then use it in the update (assuming you have a primary key with auto-increment).
Try With WHERE Condition on unique coloumn
mysql_query("UPDATE ptb_users SET ptb_users.user_id = ptb_users.id,
ptb_users.account_type = 'Client'" WHERE ptb_user.email='$email');
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.
Im having trouble with my sql statements. I dont know what im doing wrong but it keeps adding to the database much rather than uploading
$result = mysql_query("SELECT id FROM users where fbID=$userID");
if (mysql_num_rows($result) > 0) {
mysql_query("UPDATE users
SET firstName='$firstName'
, lastName='$lastName'
, facebookURL='$link'
, birthday='$birthday'
, update='$today'
, accessToken='$accessToken'
, parentEmailOne='$parentEmailOne'
, WHERE fbID='$userID'");
} else {
mysql_query("INSERT INTO users
(fbID, firstName, lastName, facebookURL, birthday
, updated, accessToken, parentEmailOne )
VALUES ('$userId', '$firstName', '$lastName', '$link', '$birthday'
, '$today', '$accessToken', '$parentEmailOne')");
}
i see that in the first query you use $userID , while in the INSERT you are using $userId
There is an extra comma in your first (I mean the UPDATE) query:
'... $parentEmailOne', WHERE fbID='$userID'");
^
You have an extra comma in your UPDATE statement before the WHERE clause:
parentEmailOne='$parentEmailOne', WHERE fbID='$userID'"
^^^^
But, also you should make sure that your variable $userID isn't empty and echo out mysql_num_rows() to see what you're getting back from the SELECT
Also, in your SELECT you use the variable $userID but in your INSERT you are using $userId. Note the capitalization difference.
You need quotes on the first query, fbID='$userID'
Also, you dont need this , before where, on the second SQL
And last, you use userID on the first reference, and userId on the last
Do the names contain any apostrophes?
You'll want to be sure to use mysql_real_escape_string
Are you saying it inserts rather than updating? In other words, it's failing to find existing records that you expect it to find?
I recommend that instead of doing "update if the record exists, otherwise insert" logic yourself, you look into MySQL's built-in functionality.
update is keyword and you must use from delimiter.
and one comma in first query is extra
$result = mysql_query("SELECT `id` FROM `users` where `fbID`=$userID");
if (mysql_num_rows($result) > 0) {
mysql_query("UPDATE `users` SET `firstName`='$firstName', `lastName`='$lastName', `facebookURL`='$link', `birthday`='$birthday', `update`='$today', `accessToken`='$accessToken', `parentEmailOne`='$parentEmailOne' WHERE `fbID`='$userID'");
} else {
mysql_query("INSERT INTO `users` (`fbID`, `firstName`, `lastName`, `facebookURL`, `birthday`, `updated`, `accessToken`, `parentEmailOne` ) VALUES ('$userId', '$firstName', '$lastName', '$link', '$birthday', '$today', '$accessToken', '$parentEmailOne')");
}
this is standard code
if the userID column is a varchar, you should quote the $userID variable in your first query
So here is the deal. I have looked around everywhere, and all other techniques relate to refreshing the browser, and methods to prevent the php page from resubmitting the post data. I am new to this (obviously :p) But anyways, my questions I believe is simple. I just want a method, possibly an if else statement that would check the post data entries, and if there is a match already in my table, than do not execute the query. I am not worried about querying all of the results of the table, as I only suspect this table will ever have 50-60 entries.
Here is the php page that handles the form submission:
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$city = $_POST['city'];
$state = $_POST['state'];
$submitDate = date("Y-m-d");
mysql_connect ("localhost", "abc", "123") or die ('Error: ' . mysql_error());
mysql_select_db ("members");
$query = "INSERT INTO persons (ID, firstName, lastName, email, city, state, submitDate)VALUES (
'NULL',
'".$firstName."',
'".$lastName."',
'".$email."',
'".$city."',
'".$state."',
'".$submitDate."'
)";
mysql_query($query) or die ('Error Updating database');
echo "Database Updated With: " .$firstName ." " .$lastName ." " .$email ." " .$city ." " .$state;
mysql_close($con);
Sorry, cant ever seem to get my php to format correctly with those code braces. Anyways. just to re-iterate, looking for a way to maybe based on the first and last name. if those already exist, then do not allow the submission of the data. I have tried a few if then statements but i do not think I am getting the concept down of comparing the result to my query. I hope this all makes sense!!!
I would suggest adding a UNIQUE index on the columns you want to have unique.
You can just use INSERT IGNORE INTO ... and let MySQL handle it.
$query = "INSERT IGNORE INTO persons (ID, firstName, lastName, email, city, state, submitDate) VALUES (
'NULL',
'".$firstName."',
'".$lastName."',
'".$email."',
'".$city."',
'".$state."',
'".$submitDate."'
)";
Is your problem only that refreshing the page resends the POST data? The pretty much standard way to prevent that is to redirect the browser after having processed the form data, like so:
header('Location: ' . $_SERVER['PHP_SELF']);
Keep in mind, changing headers has to be done before any output is sent to the browser, so this should be above your doctype, and be sure there is no white space before either.
One way of doing this is to make sure your table has appropriate primary keys set (firstname and lastname at least), and then just trying the insert and seeing whether it fails on duplicate. You can check the error message using the mysql_error() function for this purpose.
You can do a select on the database with those two fields to check if a row already exists, but if this is something that needs to be unique there should also be a unique index on those two columns in your MySQL table.
I had this issue as well. Basically what I did is before the insert, do a select on the criteria that would qualify as a duplicate and check for it to return; if it does not we are ok to enter.
$query = "SELECT COUNT(id) AS mycount FROM persons WHERE firstName = '".$firstnName."' AND lastName = '".$lastName."'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if($row['mycount'] == 0) {
//Do insert
}