Please whats wrong with this code?
Im using it to add some data to database but im getting empty $toid and $toname when trying to insert.
This is the form. The variables $toid and $toname are ok here.
//write new message
if (isset($_GET['action']) && $_GET['action'] == compose) {
if (isset($_GET['toid'])) {
$toid = $_GET['toid'];
$tosql = "select * from authors where id =".$toid."";
$toquery = mysql_query($tosql,$connection) or die(mysql_error());
$torow = mysql_fetch_array($toquery);
$toname = $torow['displayname'];
if (isset($_GET['subject'])) { $subject = $_GET['subject']; }
if (isset($_GET['message'])) {
$message = $_GET['message'];
echo "<h3>Replying</h3>
<table>
<tr>
<td colspan='2'>Replying to ".$toname.".</td>
</tr>
<tr>
<td colspan='2'>".$subject."".nl2br($message)."<br />
</td>
</tr>
</table><br />Type your answer:<br /><br />";
} else { echo "New message"; }
echo "<form action=\"mail.php?action=send\" method=post>
<table>
<tr>
<td>To:</td><td><input type=\"text\" name=\"to\" size=\"50\" value=\"".$toname."\"></td>
</tr>
<tr>
<td>Title:</td><td><input type=text name=subject size=50 value=".$subject."></td>
</tr>
<tr>
<td valign=\"top\">Message:</td><td><textarea rows=\"10\" cols=\"70\" name=\"message\"></textarea></td>
</tr>
<tr>
<td align=\"right\" colspan=\"2\"><input id=\"submitstyle\" type=\"submit\" value=\"Enviar Mensagem\"></td>
</tr>
</table>
</form>";
}
}
Here is the code to insert the message to databse, the $toid and $toname are empty here. Its suposed to being retrieved from the form above, right?
//send message
if (isset($_GET['action']) && $_GET['action'] == send) {
if ($subject == "" || $message == "") {
header('Location: mail.php?action=compose&toid='.$toid.'&subject=\''.$subject.'\'&sendpm=false');
exit();
}
$date = DATE(YmdHis);
echo $userid."from<br />to".$toid."<br />toname".$toname;
$sendsql = "INSERT INTO mail (sender, reciever, subject, message, created_at, status, sender_deleted, reciever_deleted)
VALUES (".$userid.", ".$toid.", ".$subject.", ".$message.", ".$date.",unread, 0, 0)";
$sendquery = mysql_query($sendsql,$connection) or die(mysql_error());
echo "<div class=\"alert\" style=\"text-align: center; margin-top: 13px;\"><b>Mensagem particular enviada com sucesso!</b></div>
<br /><table align=\"center\" width=\"75%\" class=\"sortable\">
<tr>
<td colspan='2' style=\"text-align:center;font-weight:normal;\">Mensagem particular enviada para ".$toname.".</td>
</tr>
<tr>
<td colspan='2'>
Title: ".$subject."
Message: ".nl2br($message)."
</td>
</tr>
</table>";
}
Im also getting this sql error You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' RE: assunto3, 3, 20121017023723,unread, 0, 0)' at line 2 wich i think its because of the empty variables mentioned.
First, you need to pass those variables as hidden form values: http://www.echoecho.com/htmlforms07.htm
Then you need to get the variables from the form via $_POST.
Try $toid = $_POST['toid'] and $toname = $_POST['toname']. But be wary about SQL injection: http://php.net/manual/en/security.database.sql-injection.php
Don't just accept values blindly from $_POST. Be sure to validate and filter them first.
Or if toid/toname aren't changable by the user, why not just requery for them?
You need to escape the INSERT values, and put strings in quotes:
$sendsql = 'INSERT INTO mail (sender, reciever, subject, message, created_at, status, sender_deleted, reciever_deleted)
VALUES ("'.mysql_real_escape_string($userid).'", "'.mysql_real_escape_string($toid).'", "'.mysql_real_escape_string($subject).'", "'.mysql_real_escape_string($message).'", "'.mysql_real_escape_string($date).'","unread", 0, 0)';
Also, be sure you always escape the values that are immediately used in SQL queries from $_GET or $_POST. Otherwise, you are most likely to experience SQL injection
You need to write SQL Statement in php like that:
$tosql = "select * from authors where id ='$toid'";
and
$sendsql = "INSERT INTO mail (sender, reciever, subject, message, created_at, status, sender_deleted, reciever_deleted)
VALUES ('$userid', '$toid', '$subject', '$message', '$date', 'unread', 0, 0)";
i think this will be help you.
Related
I'm trying to create a form which allows you to update a database table using php.
I'm kinda new to PHP so excuse me if I make a stupid mistake in the code.
This is my edit.php code:
<html>
<head>
</head>
<body>
<?php
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM cats");
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<?php
while($row = mysqli_fetch_array($result))
{
$name = $row['name'];
$email = $row['email'];
$rank = $row['rank'];
$birth = $row['birth'];
$joined = $row['joined'];
$steamid = $row['steamid'];
?>
<td width="100"></td>
<td><?=$name?></td>
</tr>
<tr>
<td width="100">Email</td>
<td><input name="emailid" type="text" value="<?=$email?>"></td>
</tr>
<tr>
<td width="100">Rank</td>
<td><input name="rankid" type="text" value="<?=$rank?>"></td>
</tr>
<tr>
<td width="100">Birth</td>
<td><input name="birthid" type="text" value="<?=$birth?>"></td>
</tr>
<tr>
<td width="100">Joined</td>
<td><input name="joinedid" type="text" value="<?=$joined?>"></td>
</tr>
<tr>
<td width="100">Steamid</td>
<td><input name="steamidid" type="text" value="<?=$steamid?>"></td>
</tr>
<?php } ?>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="update" type="submit" id="update" value="Update">
</td>
</tr>
</table>
</form>
<?php
if(isset($_POST['update']))
{
$name = $row['nameid'];
$email = $row['emailid'];
$rank = $row['rankid'];
$birth = $row['birthid'];
$joined = $row['joinedid'];
$steamid = $row['steamidid'];
$update = mysqli_query($con,"UPDATE cats SET email = '$email', rank = '$rank', birth = '$birth', joined = '$joined', steamid = '$steamid' WHERE name = '$name';");
$retval = mysqli_query($con,"UPDATE cats SET email = '$email', rank = '$rank', birth = '$birth', joined = '$joined', steamid = '$steamid' WHERE name = '$name';");
if (!$update) {
echo "Could not update data: " . mysqli_error($con);
}
echo "Updated data successfully\n";
}
mysqli_close($con);
?>
</body>
</html>
It shows the table and information but the updating isn't working.
Updated data successfully
I've checked the database but it's not updating anything.
Dear i think you change the record based on Name because you can use $name in where clause and you can also change the Name than never true where clause so that your query execute successfully but not effected on any of the row.
you want to get for editable record and that's unique id base update row it will defiantly work.
Try to use PHP PDO database access functions, your code as it stands is vulnerable to SQL-Injection! PDO will also make debugging and working with the database much easier.
I think your check for "update" in $_POST is not working because update is not a field inside your form but the submit button itself, try to check for one of the fields instead.
Informations:
With mysqli_error() you need to write about which connection you want to get errors, like this:
mysqli_error($con);
With mysqli_query() you need to give two parameters, connection and query like this:
$update = mysqli_query($con,"UPDATE cats SET email = '$email', rank = '$rank', birth = '$birth', joined = '$joined', steamid = '$steamid' WHERE name = '$name';");
How to debug:
If you want to check that UPDATE query return any error you can do something like this:
if (!$update) {
echo "Could not update data: " . mysqli_error($con);
}
You can try to debug your query with something like this:
$sql = "UPDATE cats SET email = '$email', rank = '$rank', birth = '$birth', joined = '$joined', steamid = '$steamid' WHERE name = '$name';";
echo $sql; // this output write in your phpMyadmin to check if there are any errors.
$update = mysqli_query($con, $sql);
Other problem we got:
1. I think also you should have else in your code, f.ex.:
if (!$update) {
echo "Could not update data: " . mysqli_error($con);
} else {
echo "Updated data successfully\n";
}
2. You are not getting data from $_POST it should be like:
$name = $_POST['nameid']; // not $row['nameid']
$email = $_POST['emailid'];
$rank = $_POST['rankid'];
$birth = $_POST['birthid'];
$joined = $_POST['joinedid'];
$steamid = $_POST['steamidid'];
More about used functions:
PHP: mysqli::$error
PHP: mysqli::query
In your case it is Procedural style
I have made a simple php cms form with database but it does not work properly when I want to submit the form with some dummy data! I don't know why it happens & also I added the mysqli_error() to get the type of error that I'm facing with but I only got this:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '','','')' at line 2
<?php
if (isset($_POST['submit'])){
$post_title = $_POST['title'];
$post_date = date('d-m-y');
$post_author = $_POST['author'];
$post_keywords = $_POST['keywords'];
$post_content = $_POST['content'];
$post_image = $_FILES['image']['name'];
$image_tmp = $_FILES['image']['tmp_name'];
if ($post_title=='' or $post_keywords='' or $post_content='' or $post_author=''){
echo '<script>alert("Some fields are missing")</script>';
}else{
move_uploaded_file($image_tmp,"post_images/$post_image");
$insert_query = "INSERT INTO posts
(post_title,post_date,post_author,post_image,post_keywords,post_content) VALUES ('$post_title','$post_date','$post_author',$post_image','$post_keywords','$post_content')";
$insert_post = mysqli_query($con,$insert_query);
if ($insert_post){
echo '<h3 style="color:green">Post has been added successfully.</h3>';
}else{
echo mysqli_error($con);
}
}
}
?>
<form method="POST" action="" enctype="multipart/form-data">
<table width="600" align="center" border="10">
<tr>
<td align="center"><h6>Insert Post Title</h6></td>
<td align="center"><input type="text" name="title"/></td></br>
</tr>
<tr>
<td align="center"><h6>Insert Post Author</h6></td>
<td align="center"><input type="text" name="author"/></td></br>
</tr>
<tr>
<td align="center"><h6>Insert Post Keywords</h6></td>
<td align="center"><input type="text" name="keywords"/></td></br>
</tr>
<tr>
<td align="center"><h6>Insert Post Image</h6></td>
<td align="center"><input type="file" name="image"/></td></br>
</tr>
<tr>
<td align="center"><h6>Insert Post Content</h6></td>
<td align="center"><textarea name="content" cols="10" rows="10"></textarea></td></br>
</tr>
<tr>
<td align="center"><input type="submit" name="submit" value="Submit"/></td>
</tr>
</table>
</form>
It would be very helpful to me if you share your solution for this problem... thanks!
You are missing a quote just before $post_image:
,$post_image'
Should be:
,'$post_image'
So the complete SQL statement becomes then:
$insert_query = "INSERT INTO posts
(post_title, post_date, post_author, post_image, post_keywords, post_content)
VALUES ('$post_title', '$post_date', '$post_author', '$post_image',
'$post_keywords', '$post_content')";
Please note that you are doing assignments in this if:
if ($post_title=='' or $post_keywords='' or $post_content='' or $post_author=''){
You should be using double == instead of =.
Finally, your code is vulnerable to SQL injection. So please use prepared statements with parameters.
writing if statement in this way is better
// this not always works
if ($post_title=='' or $post_keywords='' or $post_content='' or $post_author=''){
echo '<script>alert("Some fields are missing")</script>';
}
// yeah much better
if (empty($post_title) || empty($post_keywords) || empty($post_content) || empty($post_author)){
echo '<script>alert("Some fields are missing")</script>';
}
and sql mistake most probably because of here
'$post_keywords','$post_content')";
$post_keywords and $post_content is null or empty
Changes
Use empty for check empty variable
Use || instead of or
Check validation for what you are doing. (move_uploaded_file)
Be careful with quotes ($post_image') - This is the bug in your code
Enhance mysqli_error (if (!$insert_post){)
Code
<?php
if (isset($_POST['submit']))
{
$post_title = $_POST['title'];
$post_date = date('d-m-y');
$post_author = $_POST['author'];
$post_keywords = $_POST['keywords'];
$post_content = $_POST['content'];
$post_image = $_FILES['image']['name'];
$image_tmp = $_FILES['image']['tmp_name'];
if (empty($post_title) || empty($post_keywords) || empty($post_content) || empty($post_author))
{
echo '<script>alert("Some fields are missing")</script>';
}
else
{
if (!move_uploaded_file($image_tmp,"post_images/$post_image")) {
echo "Move Failed";
}
else
{
$insert_query = "INSERT INTO posts (post_title,post_date,post_author,post_image,post_keywords,post_content) VALUES ('$post_title','$post_date','$post_author','$post_image','$post_keywords','$post_content')";
$insert_post = mysqli_query($con,$insert_query);
if (!$insert_post){
echo mysqli_error($con);
}
else
{
echo '<h3 style="color:green">Post has been added successfully.</h3>';
}
}
}
}
?>
My player message system isn't working. You start on the Diplomacy page which lists the player nations. Once a player nation is selected they are sent to the send message page which shows any messages between themselves and the nation selected. It also gives them a message box to write their own message to send. Here is the code.
if(isset($_POST['message']) && !empty($_POST['message'])){
$sender = $_GET['nation'];
$receiver = $_GET['receiver'];
$random_number = rand();
$message = $_POST['message'];
$type = $_GET['type'];
$check_con = mysql_query("SELECT `hash` FROM `message_group` WHERE (`user_one`='$sender' AND `user_two`='$receiver') OR (`user_one`='$receiver' AND `user_two`='$sender')");
if(mysql_num_rows($check_con) ===1){
$get_hash = mysql_fetch_assoc($check_con);
$hash = $get_hash['hash'];
mysql_query("INSERT INTO messages (group_hash, from_id, message, seen) VALUES('$hash','$sender','$message','0')");
echo "<p>Message Sent!</p>";
}else{
mysql_query("INSERT INTO message_group (user_one, user_two, hash) VALUES('$sender','$receiver','$random_number')");
mysql_query("INSERT INTO messages (group_hash, from_id, message, seen) VALUES('$random_number','$sender','$message','0')");
echo "<p>Conversation Started!</p>";
}
}
?>
<form method="POST" action="index.php?page=gc3025/send_beta.php&game=<?php echo $game; ?>&type=<?php echo $type; ?>&nation=<?php echo $nations_id; ?>&user=<?php echo $user_id; ?>&receiver=<?php echo $receiver_id; ?>">
<table>
Enter Message:
<tr>
<td></td>
<td><textarea name='message' rows='7' cols='60'></textarea></td>
</tr>
<td><input type='submit' value="Send Message" /></td>
</table>
</form>
If under FORM ACTION I link the page to itself it works but you have to refresh the page to see the new message which also resends the message. If the FORM ACTION goes to the previous page then it does not INSERT the message into the table on the server.
You can use AJAX to load data dynamically into page without reloading. I'm going to post an example using jQuery.
Your current page with the form, lets name it form.php. Removed the posting message logic, kept the form, added ajax request.
<div id="messages"></div>
<form id="message_form" method="POST" action="#">
<table>
<p>Enter Message:</p>
<tr>
<td></td>
<td><textarea name='message' rows='7' cols='60'></textarea></td>
</tr>
<tr>
<td colspan="2"><input type='submit' value="Send Message" /></td>
</tr>
</table>
</form>
<script type="text/javascript">
$("#message_form").submit(function(){
var url = "./send.php";
var send_data = { game: "<?php echo $game; ?>", type: "<?php echo $type; ?>", nation: "<?php echo $nations_id; ?>", user: "<?php echo $user_id; ?>", receiver: "<?php echo $receiver_id; ?>" };
$.post(url, send_data).done(function(received_data){
reload_messages();
});
});
function reload_messages(){
var url = "./read_messages.php";
var send_data = { ... }; // add data you want to send to the reading script, such as filtering or limit numbers
$.post(url, send_data).done(function(received_data){
$("#messages").html(received_data);
});
}
<script>
Now send.php. Here's your original posting message logic, repaired SQL injection vulnerability (read notes in the bottom of the answer).
if(isset($_POST['message']) && !empty($_POST['message'])){
$sender = mysql_real_escape_string($_GET['nation']);
$receiver = mysql_real_escape_string($_GET['receiver']);
$random_number = rand();
$message = mysql_real_escape_string($_POST['message']);
$type = mysql_real_escape_string($_GET['type']);
$check_con = mysql_query("SELECT `hash` FROM `message_group` WHERE (`user_one`='".$sender."' AND `user_two`='".$receiver."') OR (`user_one`='."$receiver."' AND `user_two`='."$sender."')");
if(mysql_num_rows($check_con) ===1){
$get_hash = mysql_fetch_assoc($check_con);
$hash = $get_hash['hash'];
mysql_query("INSERT INTO messages (group_hash, from_id, message, seen) VALUES('$hash','$sender','$message','0')");
echo "<p>Message Sent!</p>";
}else{
mysql_query("INSERT INTO message_group (user_one, user_two, hash) VALUES('".$sender."','".$receiver."','".$random_number."')");
mysql_query("INSERT INTO messages (group_hash, from_id, message, seen) VALUES('".$random_number."','".$sender."','".$message."','0')");
echo "<p>Conversation Started!</p>";
}
}
Your code doesn't show reading messages logic, so I'm just going to put simple select query here.
$query = mysql_query("SELECT ... ");
while($row = mysql_fetch_assoc($query)){
echo $row[...];
}
By the way, just few notes to your code:
1.Original code is vulnerable to SQL injection. Use mysql_real_escape_string() to escape input values to the queries or better prepared statements.
2.If you don't have same number of <td> columns in <tr> rows, use colspan attribute.
3.The "Enter message" (or any other text) should be at least in <p>, within a table cell, or outside table.
4.The last <td> wasn't wrapped in any <tr>
Ok help..my registration page worked on the local server but its now saying that the two mysql lines are not valid when its online..why does it change when it goes online? the code pasted is all thats relevant. for some reason it doesnt like the transaction..and the email check mysql bit
include 'Connect.php'; //Connects to database
//When form is submit:-
if(isset($_POST['submit']))
{
// On submit, retrieve table values for php.
$Firstname = mysql_real_escape_string($_POST['firstname']);
$Surname = mysql_real_escape_string($_POST['surname']);
$Password = mysql_real_escape_string($_POST['password']);
$PasswordCheck = mysql_real_escape_string($_POST['passwordcheck']);
$Email = mysql_real_escape_string($_POST['email']);
$EmailCheck = mysql_real_escape_string($_POST['emailcheck']);
//CHECKS.
//Check username is available by retrieving any same values from the DB table.
$CheckEmailAvailable = mysql_query("SELECT * FROM 'user_details' WHERE Email = '$Email'");
echo $CheckEmailAvailable;
// $result = mysql_query("SELECT * FROM $tbl WHERE Email='$email' and LoginPassword='$password'");
$Results = mysql_fetch_array($CheckEmailAvailable);
//If Username field is blank.
if($Email == null )
{
echo "You must enter an email address.";
$url = htmlspecialchars($_SERVER['HTTP_REFERER']);
echo "<br/><br/>";
echo "<a href='$url'>Click Here To Return</a>";
die();
}
//If RESULTS is any value other than NULL, die.
if($Results != null )
{
echo "Email already taken. Please try another.";
$url = htmlspecialchars($_SERVER['HTTP_REFERER']);
echo "<br/><br/>";
echo "<a href='$url'>Click Here To Return</a>";
die();
}
//If Password and PasswordCheck fields in reg do not match, die.
if($Password != $PasswordCheck)
{
echo "The passwords you have entered do not match. Please try again.";
$url = htmlspecialchars($_SERVER['HTTP_REFERER']);
echo "<br/><br/>";
echo "<a href='$url'>Click Here To Return</a>";
die();
}
//If Password field is NULL (i.e. blank) die.
if($Password == Null)
{
echo "Your password must not be blank.";
$url = htmlspecialchars($_SERVER['HTTP_REFERER']);
echo "<br/><br/>";
echo "<a href='$url'>Click Here To Return</a>";
die();
}
//If Email and EmailCheck are not equal, die.
if($Email != $EmailCheck)
{
echo "The email addresses you have entered do not match. Please try again.";
$url = htmlspecialchars($_SERVER['HTTP_REFERER']);
echo "<br/><br/>";
echo "<a href='$url'>Click Here To Return</a>";
die();
}
//ELSE add data to DB.
else
{
//BEGIN TRANS
mysql_query("BEGIN TRAN");
//TABLE ADD.
$sql=mysql_query("INSERT INTO `user_details` (`Firstname`, `Surname`, `Email`, `Password`) VALUES ('$Firstname', '$Surname', '$Email', '$Password')")
or mysql_query("ROLLBACK TRAN") . die(mysql_error("Error registering, the database may be down, please try again later."));
//COMMIT transaction, to ensure data is added properly.
mysql_query("COMMIT TRAN");
header( 'Location: RegSucc.php' ) ;
}
} ?>
<html>
<!--Registration Form-->
<form name="form1" method="post" style="margin-left: 28%" action="Register.php">
<table width="100%" border="0" cellpadding="3" cellspacing="1">
<tr>
<td colspan="3"><strong>Register Account</strong></td>
</tr>
<tr>
<td style="width: 83px">First Name:</td>
<td>:</td>
<td><input name="firstname" type="text"/></td>
</tr>
<tr>
<td style="width: 83px">Surname:</td>
<td>:</td>
<td><input name="surname" type="text"/></td>
</tr>
<tr>
<td style="width: 83px">Email Address:</td>
<td>:</td>
<td><input name="email" type="text"/></td>
</tr>
<tr>
<td style="width: 83px">Email Address Confirmation:</td>
<td>:</td>
<td><input name="emailcheck" type="text"/></td>
</tr>
<tr>
<td style="width: 83px">Password:</td>
<td>:</td>
<td><input name="password" type="password"/></td>
</tr>
<tr>
<td style="width: 83px">Verify Password:</td>
<td>:</td>
<td><input name="passwordcheck" type="password"/></td>
</tr>
<tr>
<td style="width: 83px"> </td>
<td> </td>
<td><input type="submit" name="submit" value="Register"/></td>
</tr>
</table>
</form>
The query
SELECT * FROM 'user_details' WHERE Email = '$Email'
Is invalid. When denoting table names, it is good practice to use backticks, but using quotes will not work!
SELECT * FROM `user_details` WHERE Email = '$Email'
On your localhost, it may be setup to work with quotes. However, that is not the way it is "supposed" to be, and the server's installation may be different. Moral of the story: don't take shortcuts or use ugly code. Don't forget to backtick table names or columns, don't use PHP shorttags, etc.
$sql=mysql_query("INSERT INTO `user_details` (`Firstname`, `Surname`, `Email`, `Password`) VALUES ('$Firstname', '$Surname', '$Email', '$Password')")
should be
$sql=mysql_query("INSERT INTO user_details (Firstname, Surname, Email, Password) VALUES ('$Firstname', '$Surname', '$Email', '$Password')")
Also
SELECT * FROM 'user_details' WHERE Email = '$Email'
should be
SELECT * FROM user_details WHERE Email = '$Email'
that's it...
Change this line
$CheckEmailAvailable = mysql_query("SELECT * FROM 'user_details' WHERE Email = '$Email'");
to
$CheckEmailAvailable = mysql_query("SELECT * FROM user_details WHERE Email = '".$Email."'");
The problem is that when you moved to another server online (I can guess you were developing on Windows[which is case insensitive in MySQL], and your online server is Linux[case sensitive in MySQL]
If your string contains a variable to be evaluated and parsed, the use of single quotes around that variable name, within the double quote containing that string, is not so reliable most times. The best approach, (from personal experiences) is to do a concatenation.
I have a form in my website, but I can't fix one problem. When I write some text in the form box, it sends the data to the database. When I hit refresh, the page sends the same data again, to the database. What is the problem with my code?
<?php
if(isset($_POST['submit']))
{
$err = array();
$diss = $_POST['type'];
$sub = $_POST['sub'];
$msg = $_POST['msg'];
$uname = $_SESSION['uname'];
$date = "On " . date("F Y h:i:s A");
if (!isset($_SESSION['uname']))
$err[] = "You need to login";
else
{
if(empty($sub) && empty($msg))
$err[] = "All field required";
else
{
if(empty($sub))
$err[] = "Subject Requried";
if(empty($msg))
$err[] = "Message Requried";
}
}
if(!empty($err))
{
foreach($err as $er)
{
echo "<font color=red><b>$er</b></font>";
}
}
else
{
$sql= mysql_query("INSERT INTO discussion VALUES ('', '$diss', '$sub', '$msg', '$uname', '$date' ) ");
if(!$sql)
echo "Can't submit your discussion";
else
{
echo "Discussion was submitted";
}
}
}
?>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post"
name="discussion">
<table width="240" border="0" cellspacing="0" cellpadding="0">
<tr>
<td style="width:230;"><b>Select your Discussion</b>
<select name="type">
<?php
$sqld = mysql_query("SELECT * FROM distype");
while($row = mysql_fetch_assoc($sqld))
{
$d_id = $row['d_id'];
$diss = $row['type'];
echo "<option value='$diss'>$diss</option>";
}
?>
</select></td>
</tr>
<tr>
<td><b>Subject</b></td>
</tr>
<tr>
<td><input type="text" name="sub" value="" size="33" class=""/></td>
</tr>
<tr>
<td><b>Message</b></td>
</tr>
<tr>
<td><textarea cols="30" rows="3" name="msg" class=""></textarea></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td><input type="submit" name="submit" value="Submit Form"><br>
<td></td>
</tr>
</table>
On successful form submit you need to reload the url or redirect him somewhere to prevent user from inserting data to the database.
$sql= mysql_query("INSERT INTO discussion VALUES ('', '$diss', '$sub', '$msg', '$uname', '$date' ) ");
if(!$sql)
echo "Can't submit your discussion";
else
{
header("Location: page.php?mode=success");
//or
header("Location: ".$_SERVER['REQUEST_URI']); //which will just reload the page
}
The problem is, that your code will execute the same way when sent the same data. You need to protect against double inserts by one of many contructs:
Unique key on the table
Store hash of last post in session, refuse post if it has the same hash as stored
redirect user to different page on succes, so that a refresh will not cause the same POST