I have a simple form with some PHP code to post to a database some simple information.
The connection to the database is just fine because it display items I have manually entered exactly how I want it to; however. I cannot get it to post from the form into the database. I have tinkered with a lot of code with no luck. Anyone see anything I’m missing? Here is the code:
<center>
<form action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="POST">
<strong><h2><br><br>Enter in my guestbook!</h2></strong><br>
<h3>Nickname:</h3><input type="text" name="guestbook_name" maxlength="25"><br>
<h3>Write About Your Day:</h3><textarea name="guesbook_message" rows="6" cols="60" maxlength="255"></textarea><br>
<input type ="submit" value="POST">
</form>
<br>
<hr>
<br>
<?php
if (mysql_connect('localhost', 'root', 'root') && mysql_select_db('mydb')) {
//echo 'Connected to the database!';
$time = gmdate("l dS \of F Y h:i:s A");
$errors = array();
if (isset($_POST['guestbook_name'], $_POST['guestbook_message'])) {
echo 'Set data!';
$guestbook_name = mysql_real_escape_string(htmlentities( $_POST['guestbook_name']));
$guestbook_message = mysql_real_escape_string(htmlentities( $_POST['guestbook_message']));
if (empty($guestbook_name) || empty($guestbook_message)) {
$errors[] = 'All fields are required.';
}
if (strlen($guestbook_name)>25 || strlen($guestbook_message)>250){
$errors[] = 'One or more fields exceeded the character limit!';
}
if (empty($erros)) {
$insert = "INSERT INTO guestbook VALUES ('','$time','$guestbook_name','$guestbook_message')";
if (mysql_query($insert)){
header ('Location: '.$_SERVER['PHP_SELF']);
} else {
$errors[] = 'Something went wrong. Try again.';
}
} else {
foreach($errors as $error) {
echo'<p><strong>'.$error.'</strong></p>';
}
}
}
// display entries
$entries = mysql_query("SELECT timestamp, name, message FROM guestbook ORDER BY timestamp DESC");
if (mysql_num_rows($entries)==0){
echo 'No entries, yet.';
} else {
//echo 'Entries found.';
while ($entries_row = mysql_fetch_assoc($entries)){
$entries_timestamp = $entries_row['timestamp'];
$entries_name = $entries_row['name'];
$entries_message = $entries_row['message'];
echo '<p><strong>Posted by '.$entries_name.' on '.$entries_timestamp.'</strong>:<br><br>'.$entries_message.'</p><br><br>';
}
}
} else {
echo 'Could not connect at this time.';
}
?>
</center>
My main issue is the submitting the database, any help would be great, thanks!
Kyle B.
We will need to see your database table structure vs. your insert sql statement to see if you are inserting properly.
Most likely cause of failed insert is not setting a field value which is set to NOT NULL, (either by not inserting a value, or having an empty/mistyped variable).
But more common problems are: