I have been writing some code for a forum and am new to PHP, but I have run into some trouble. When I test the program by entering an answer, I get a web page that says "ERROR".
After changing echo "ERROR"
to echo mysql_error()
, the webpage changed to this:
Notice: Undefined index: id in C:\xampp5\htdocs\add_answer.php on line 14
Notice: Undefined index: a_name in C:\xampp5\htdocs\add_answer.php on line 30
Notice: Undefined index: a_email in C:\xampp5\htdocs\add_answer.php on line 31
Notice: Undefined index: a_answer in C:\xampp5\htdocs\add_answer.php on line 32 Duplicate entry '1' for key 'PRIMARY'
<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="forum_answer"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Get value of id that sent from hidden field
$id = $_POST['id'];
// Find highest answer number.
$sql="SELECT MAX(a_id) AS Maxa_id FROM $tbl_name WHERE question_id='$id'";
$result=mysql_query($sql);
$rows=mysql_fetch_array($result);
// add + 1 to highest answer number and keep it in variable name "$Max_id". if there no answer yet set it = 1
if ($rows) {
$Max_id = $rows['Maxa_id']+1;
}
else {
$Max_id = 1;
}
// get values that sent from form
$a_name = $_POST['a_name'];
$a_email = $_POST['a_email'];
$a_answer = $_POST['a_answer'];
$datetime=date("d/m/y H:i:s"); // create date and time
// Insert answer
$sql2="INSERT INTO $tbl_name(question_id, a_id, a_name, a_email, a_answer, a_datetime)VALUES('$id', '$Max_id', '$a_name', '$a_email', '$a_answer', '$datetime')";
$result2=mysql_query($sql2);
if($result2){
echo "Successful<BR>";
echo "<a href='view_topic.php?id=".$id."'>View your answer</a>";
// If added new answer, add value +1 in reply column
$tbl_name2="forum_question";
$sql3="UPDATE $tbl_name2 SET reply='$Max_id' WHERE id='$id'";
$result3=mysql_query($sql3);
}
else {
echo "ERROR";
}
// Close connection
mysql_close
();
?>
For the moment I am not concerned with security, as I intend to fix security issues later down the track.
You have a race condition in your code. When multiple users hit the database at the same time, they will eventually read the same $Max_id
and subsequently try to insert the same $Max_id + 1
. Eg.:
You need to declare the primary key column with the AUTO_INCREMENT
attribute (or simply declare it as a SERIAL
). This way, the database engine will automatically update the id with a guaranteed unique value when you insert new rows.