473,386 Members | 1,736 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Refreshing the page INSERTs into the database

I am 12 and need help with my code, when I press the refresh button it reposts the data into the database and utmately reposts the comment. This could be bad because if someone (Don't Even Think About Doing This) presses the refresh button a bunch (And I Mean A Bunch) it could fill up my server then bring down my bandwidth. Here is my code

Expand|Select|Wrap|Line Numbers
  1. <html>
  2. <?php
  3. class formValidation{
  4. function checkLength($string, $min, $max, $awnser)    {
  5. $length = strlen($string);
  6. if($length < $min)    {
  7.     die("The $awnser is to short");
  8. }
  9. if($length >$max)    {
  10.     die("The $awnser is to long");
  11. }
  12. }
  13. }
  14. //////////////////////////////////////////////////////////////////////////
  15. include('loginSQL.php');
  16.     $connection = mysql_connect($db_host, $db_username, $db_password);
  17.     if(!connection){
  18.         die ("Could not connect to the database:<br>");
  19.     };
  20.     $select = mysql_select_db($db_database);
  21.     if(!$select){
  22.     die("Could not select the database.<br./>");
  23.     };
  24.     $query = "SELECT * FROM comments";
  25.     $result = mysql_query($query);
  26.     if(!$result){
  27.         die("Could not execute the query <br>".mysql_error());
  28.     };
  29. if(!is_null($_POST['name']))    {
  30.     formValidation::checkLength($_POST['name'],2,50,name);
  31.     $name = $_POST['name'];
  32.     formValidation::checkLength($_POST['comment'],0,500,comment);
  33.     $comment = $_POST['comment'];
  34.     $date = date("F/j/Y");
  35.     $time = date("g:i:A");
  36.     $query = "INSERT INTO comments VALUES ('$name', '$comment', '$time', '$date');";
  37.     $result = mysql_query($query);
  38.     if(!$result){
  39.         die("Could not insert the comment".mysql_error());
  40.     };
  41.     $query = "SELECT * FROM comments";
  42.     $result = mysql_query($query);
  43.     if(!$result){
  44.         die("Could not execute the query <br>".mysql_error());
  45.     };
  46. };
  47. $_POST['name'] = NULL;
  48. ?>
  49. <font size = "5" color = "Grey"> Comments </font>
  50. <hr>
  51. <?php
  52.     while ($result_row = mysql_fetch_row(($result))){
  53.         echo $result_row[0];
  54.         echo ' Left this comment on ';
  55.         echo $result_row[3];
  56.         echo ' at ';
  57.         echo $result_row[2];
  58.         echo '<br>';
  59.         echo $result_row[1];
  60.         echo '<hr>';
  61.     };
  62. ?>
  63. <hr>
  64. <font size ="5" color = "Grey"> Leave A Comment!</font><br>
  65. <form action = "comments.php" method = "post">
  66. Name<br>
  67. <input = "text" name = "name"><br>
  68. <textarea cols = "40" rows = "5" name = "comment">
  69. Type your comment here!
  70. </textarea><br>
  71. <input type = "submit">
  72. </form>
  73. <hr>
  74. </html>
  75.  
  76.  
  77.  
  78. <!--
  79. Problems
  80. When Pressing The Refresh Button It Posts The Comment Again
  81. -->
Thanks for all the help, and by the way the link is here link

It also does not do the date correctly but I can fix that.

Thanks,
Matt
May 16 '07 #1
13 2250
pbmods
5,821 Expert 4TB
Renamed the thread to better match contents.

Heya, rcmatt4321. Welcome to TSDN!

About the easiest way I can think of to put a stop to this is to add a unique key to your table. Log in to your MySQL server and type:

Expand|Select|Wrap|Line Numbers
  1. ALTER TABLE `comments` ADD UNIQUE KEY `nameTime` (`name`, `time`);
  2.  
Substitute the actual names of your columns where appropriate (and you can change the name of the key from 'nameTime' to whatever you want).

This is really more of a failsafe than a fix, but it will prevent the script from inserting values for that User more than once a minute.

Incidentally, rather than figure the date manually, you can use NOW()

Expand|Select|Wrap|Line Numbers
  1. mysql_query("INSERT INTO `comments` VALUES('$name', '$comment', NOW(), NOW())");
  2.  
May 16 '07 #2
Renamed the thread to better match contents.
Sorry! Thanks!
May 16 '07 #3
Thank you so much! I'll do that when I finish my homework. :)

Matt
May 16 '07 #4
When I try to query the db to mod the table it gives me the error
#1170 - BLOB/TEXT column 'name' used in key specification without a key length

I am using blobs for the comments and names, if this helps any. I have not used the Mod table before so I don't really understand what it does, this would be great help.

Thanks,
Matt
May 16 '07 #5
pbmods
5,821 Expert 4TB
I am using blobs for the comments and names, if this helps any. I have not used the Mod table before so I don't really understand what it does, this would be great help.
blob is really not the proper data type for textual stuff; you'd want to use text, or better yet varchar for that.

Here's some info on string types in MySQL:
http://dev.mysql.com/doc/refman/5.0/...ing-types.html

Since blobs and texts are so huge, it's generally not efficient (nor useful) to index them in their entireties. While you could create a fulltext index, this will probably not be in the best interests of your application.

Instead, I would change the `name` and `comment` fields to varchars:

Expand|Select|Wrap|Line Numbers
  1. ALTER TABLE `comments` CHANGE `name` `name` varchar(100) not null;
  2. ALTER TABLE `comments` CHANGE `comment` `comment` varchar(1000) not null;
  3. ALTER TABLE `comments` ADD UNIQUE KEY `postLimiter` (`name`, `time`);
  4.  
This gives you 100 characters to work with (come on... whose name is REALLY that long?), and 1000 characters for a comment.

In addition to saving space on your server's hard drive, it will encourage your Users to post more meaningful comments; since they don't have nearly as much space to work with, they have to make it count!

You could probably even get away with smaller sizes; test it out and see what works best for you. You can always go back and make it larger/smaller.
May 16 '07 #6
pbmods
5,821 Expert 4TB
Incidentally (and because I have to justify to myself why I haven't moved this thread to the MySQL forum), your problem illustrates a good reason why you should generally try to keep your display (or 'view') code separate from your data ('model') code.

Here's a simple example. Suppose we have a form that posts data to a database. You might be familiar with the concept :)

If we do this:
mypage.php
Expand|Select|Wrap|Line Numbers
  1. <!--    mypage.php    -->
  2. <?php if(! isset($_POST['data'])): ?>
  3. <form action="mypage.php" method="post">
  4.     <textarea name="data"></textarea>
  5.     <input type="submit" value="Add to DB" />
  6. </form>
  7. <?php else:
  8.     mysql_connect( ... );
  9.     mysql_query("REPLACE INTO `mytable` (`data`) VALUES('" . addslashes($_POST['data']) . "')");
  10.     endif;
  11. ?>
  12.  
We have a nice, compact little script that will make your life miserable if the User refreshes the page.

But what if we did this:

mypage.html
Expand|Select|Wrap|Line Numbers
  1. <!--  mypage.html -->
  2. <form action="process.php" method="post">
  3.     <textarea name="data"></textarea>
  4.     <input type="submit" value="Add to DB" />
  5. </form>
  6.  
process.php
Expand|Select|Wrap|Line Numbers
  1. <?php
  2.     //  process.php
  3.  
  4.     if(isset($_POST['data'])) {
  5.         try {
  6.             mysql_connect( ... );
  7.             mysql_query("REPLACE INTO `mytable` (`data`) VALUES('" . addslashes($_POST['data']) . "')") || throw new Exception(mysql_error());
  8.             $message = 'SUCCESS';
  9.         } catch (Exception $e) {
  10.             $message = 'MYSQL_' . urlencode($e->getMessage());
  11.         }
  12.     } else
  13.         $message = 'NO_DATA';
  14.  
  15.     // Redirect to form.
  16.     header("Location: mypage.html?message=$message");
  17.     exit;
  18. ?>
  19.  
Once you redirect the User back to the form page, it doesn't matter how many times he refreshes the page. As long as you don't use up your bandwidth for the month, he can't do any damage.
May 16 '07 #7
That is so much help, I think mine was so long because I tried to do the database and PHP on one page. Im printing all this stuff now, even though I have two books, so I can look at it at school when I have free class tine.

Thanks,
Matt
May 16 '07 #8
O.K. I took the basic concept you had and simplified it a little bit and I wrote the code during literacy. So I put it on my server when I got home and worked most of the bugs out. It should work, I just have trouble redirecting and also some trouble out-putting the comments. I have simplified it so I don't post the time and date right now, Ill do that later.
Here is the Comments.php code
[PHP]<html>
<?php
include('loginSQL.php');
$connection = mysql_connect($db_host, $db_username, $db_password);
if(!$connection) {
die("Could Not Connect To The Database<br>");
};
$select = mysql_select_db($db_database);
if(!$select) {
die("Could Not Select The Database");
};
$query = "SELECT * FROM comments";
$result = mysql_query($query);
if(!result) {
die("Could Not Query The Database".mysql_error());
};
while($result_row = mysql_fetch_row(($result))) {
echo $result_row[1];
echo " posted this comment";
echo "<br>";
echo $result_row[2];
echo "<hr>";
};
?>
<font size = "5" color = "grey">Leave A Comment!</font><br>
<a href = "http://www.ontheballtennis.com/leaveComment.php"><Font size = "3" color = "grey">Click Here To Leave A Comment</Font></a>
</html>[/PHP]

And Here is the leaveComment.php code
[PHP]<html>
<?php
if(isset($_POST['name'])) {
include('loginSQL.php');
$connection = mysql_connect($db_host, $db_username, $db_password);
if(!$connection) {
die("Could Not Connect To The Database<br>");
};
$select = mysql_select_db($db_database);
if(!$select) {
die("Could Not Select The Database");
};
$name = $_POST['name'];
$comment = $_POST['comment'];
$query = "INSERT INTO comments (name) VALUES ('$name');";
$result = mysql_query($query);
if(!result) {
die("Could Not Query The Database".mysql_error());
};
$query = "INSERT INTO comments (comment) VALUES ('$comment');";
$result = mysql_query($query);
if(!result) {
die("Could Not Query The Database".mysql_error());
};
header('Location: http://www.ontheballtennis.com/comments.php');
echo "</html>";
};
if(!isset($_POST['name'])) {
echo "<font size = \"5\" color = \"grey\">Type your comment and name then press submit!</font><br>";
echo "<form action = \"leaveComment.php\" method = \"post\">";
echo "Name<br>";
echo "<input type = \"text\" name = \"name\"><br>";
echo "Comment <br>";
echo "<textarea cols = \"40\" rows = \"5\" name = \"comment\">";
echo "Type Your Comment Here! Be sure to delete this before you leave the comment.";
echo "</textarea><br>";
echo "<input type = \"submit\">";
echo "</form>";
echo "</html>";
};
?>[/PHP]

When it comes to the redirect part my server outputs this error

Warning: Cannot modify header information - headers already sent by (output started at /hsphere/local/home/rcmatt12/ontheballtennis.com/leaveComment.php:2) in /hsphere/local/home/rcmatt12/ontheballtennis.com/leaveComment.php on line 25

Now about the outputting part, when it outputs the comments it leaves the name and no comment then goes like it is going to post the next comment and posts no name and the comment like this

When I put in my name as Bob and comment as Brillant it posts it like this

Bob posted this comment
//// Comment Should Go Here//////

////Name Should Go Here///// posted this comment
Brilliant!

Thanks for the help,
Matt
May 17 '07 #9
If it helps any, I my comments table has three cols

a post number (not used right now)
name
comment

Thanks,
Matt
May 17 '07 #10
pbmods
5,821 Expert 4TB
header('Location: http://www.ontheballtennis.com/comments.php');
[/PHP]

When it comes to the redirect part my server outputs this error

Warning: Cannot modify header information - headers already sent by (output started at /hsphere/local/home/rcmatt12/ontheballtennis.com/leaveComment.php:2) in /hsphere/local/home/rcmatt12/ontheballtennis.com/leaveComment.php on line 25
When you redirect using header, you can't send any output to the browser, or else it won't work. As a general rule, I like to put an exit statement right after every redirect:

Expand|Select|Wrap|Line Numbers
  1. header('Location: somepage.php');
  2. exit;
  3.  
You also need to make sure that you don't output anything before you do the redirect, either. Note that spaces in front of the first <?php tag count!

If you want to have different layouts for entering comments vs. viewing comments, you might want to create three files: One that displays the form to submit the comments, one that displays the comments, and a third script that saves the comments.

When that last script finishes saving the comment, it could then redirect to the page that displays the comments (since you can redirect wherever you want o_O).

Now about the outputting part, when it outputs the comments it leaves the name and no comment then goes like it is going to post the next comment and posts no name and the comment like this

When I put in my name as Bob and comment as Brillant it posts it like this

Bob posted this comment
//// Comment Should Go Here//////

////Name Should Go Here///// posted this comment
Brilliant!

Expand|Select|Wrap|Line Numbers
  1. while($result_row = mysql_fetch_row(($result))) {
  2.     echo $result_row[1];
  3.     echo " posted this comment";
  4.     echo "<br>";
  5.     echo $result_row[2];
  6.     echo "<hr>";
  7. };
  8.  
Try this. It won't solve the problem, but it should give you a better idea of what you're working with:
Expand|Select|Wrap|Line Numbers
  1. while($result_row = mysql_fetch_row(($result, MYSQL_ASSOC))) {
  2.     print_r($result_row);
  3.     print('<hr />');
  4. };
  5.  
print_r will quickly become your best friend when working with arrays. Also, pass MYSQL_ASSOC as the second argument to mysql_fetch_row to retrieve a much more developer-friendly associative array that allows you to use column names instead of having to memorize the order :)
May 17 '07 #11
Hey Im working on it, my server is down so I cannot put it up to test it out. Ill check back with you later on how it goes.
May 17 '07 #12
I got it! You helped me so much! If you want to see it click here

Here is my code if you are interested. I figured out the redirect thing also. Feel free to copy it and use it.

comments.php
[PHP]<html>
<?php
include('loginSQL.php');
$connection = mysql_connect($db_host, $db_username, $db_password);
if(!$connection) {
die("Could Not Connect To The Database<br>");
};
$select = mysql_select_db($db_database);
if(!$select) {
die("Could Not Select The Database");
};
$query = "SELECT * FROM comments";
$result = mysql_query($query);
if(!result) {
die("Could Not Query The Database".mysql_error());
};
while($result_row = mysql_fetch_row(($result))) {
echo $result_row[1];
echo " posted this comment";
echo "<br>";
echo $result_row[2];
echo "<hr>";
};
?>
<font size = "5" color = "gray">Leave A Comment!</font><br>
<a href = "http://www.ontheballtennis.com/comment_leaving/working/leaveComment.htm"><Font size = "3" color = "black">Click Here To Leave A Comment</Font></a>
</html>[/PHP]

leaveComment.htm
[HTML]<html>
<body bgcolor = "Navy">
<font size = "5" color = "white">Type your comment and name then press submit!</font><br>
<form action = "processComment.php" method = "post">
<font color = "white"> Name </font><br>
<input type = "text" name = "name"><br>
<font color = "white">Comment </font><br>
<textarea cols = "40" rows = "5" name = "comment">
Type Your Comment Here! Be sure to delete this before you leave the comment.
</textarea>
<br>
<input type = "submit">
</form>
</html>[/HTML]

processComment.php
[PHP]<?php
include('loginSQL.php');
$connection = mysql_connect($db_host, $db_username, $db_password);
if(!$connection) {
die("Could Not Connect To The Database<br>");
};
$select = mysql_select_db($db_database);
if(!$select) {
die("Could Not Select The Database");
};
$name = $_POST['name'];
$comment = $_POST['comment'];
$query = "INSERT INTO comments VALUES (\"\", '$name', '$comment');";
$result = mysql_query($query);
if(!$result) {
die("Could Not Query The Database".mysql_error());
};
header('Location: http://www.ontheballtennis.com/comment_leaving/working/comments.php');
exit();
?>
[/PHP]

If you are wondering what loginSQL.php is it is a file containing my database URL, password, username and database.

Here is what it would look like.

loginSQL

<?php
$db_host = '///Put Host URL Here///';
$db_database = '///Put Database Name Here///;
$db_username = '///Put Username Here///';
$db_password = '///Put Password Here///';
?>

List Of What Does What

Comments.php

Outputs all comments in database and provides a link to leaveComment.htm where you can type in your name and comment

leaveComment.htm

Provides input areas for your name and comment when you press the submit button it goes to the processComment.php page

Process Comment.php

Inputs the comment into the database and redirects to the comments.php page where you would see your comment that you just posted.



List of things left to do

Make a way to post a title (Should Be Easy!)
Make it look better! Way better!
Replies (The hardest one!)
Other cosmetic stuff
More data points like e-mail and website
Spam prevention
No posting the defualt message
No posting long names or comments
No bots posting thousands of coments (ie:a random generated image to enter text in)
Time and date
Other stuff!

Thanks for the Help!,
Matt
May 18 '07 #13
pbmods
5,821 Expert 4TB
Glad to hear you got it working!

Good luck with your project, and post back anytime if you get stuck.

pbmods
May 18 '07 #14

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: James Evans | last post by:
I am having some problems with my vb.net\asp.net\sql 2000 app. Two web forms. All stored procs for data access. One form does inserts and delets - no problems. The other form does the updates. The...
1
by: sentinel | last post by:
Hello, I'm having problems refreshing a main window, and am not sure really whether the solution will be Javascript or PHP related. Firstly, I have a main file that calls a pop-up box which...
0
by: msnews | last post by:
Hi -- I'm very, very new to ASP.Net, and I've been trying for several days to figure out how to update a datagrid AND refresh it on the client side so that the page doesn't refresh. I've torn my...
1
by: Ian Walsh | last post by:
I have two pages in my project. Page 1 has a command button that when it is clicked inserts a record in a database and does a server.transfer to Page2. The problem is, if I do a refresh when...
5
by: Jensen Bredal | last post by:
Hello, I need to display self refreshing information on a web page written with asp.net. I would image that the info would be displayed either as part of a user control or a web control. How can...
1
by: planetthoughtful | last post by:
Hi All, I have an ASP.NET page that is used to insert records into an SQL Server table (see previous post). I also have a GridView on the same page that displays the results of a query on the...
8
by: Marcel | last post by:
I have a problem with a PHP page that seems to get executed twice. I am running PHP5 ISAPI on 2003 server. The script is a PHP page with a form. When the form is submitted one record have to...
5
by: JJ | last post by:
I want to have two lists (may have to be listboxes) on a page that are populated from a database. I then need to be able to click on an entry in one box and add it to the other, _preferably_...
7
by: raknin | last post by:
I'm using AJAX on my website, but internet explorer does not seem to actually be refreshing the data I retrieve via AJAX when I refresh the page. For example, I have a button that when pressed uses...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.