I am trying to create a simple blog entry form where a user enters the title, blog entry and submits it. The form should then insert the 'blog entry' into MYSQL using the insert query.
- I am getting NO errors.
- When I submit form nothing is changed, the database has no new entry and the form doesn't show "Post Submitted" or "Post Not Submitted".
Here is the blog.php code
<?php
// 1. Establish a connection using three functions: 1. mysqli_connect() 2. mysqli_connect_errno() 3. mysqli_connect_error()
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$dbname = "blog";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Test if connection occured
if(mysqli_connect_errno()) {
die("Database connection failed " . mysqli_connect_error() . "( " . mysqli_connect_errno() . " )");
}
//Form submitted
if(isset($_POST['submit'])) {
//Error checking
if(!$_POST['title']) {
$error['title_error'] = "<p>Please supply a title.</p>\n";
}
if(!$_POST['blog']) {
$error['blog_error'] = "<p>Please supply blog content.</p>\n";
}
//No errors, process
if(!is_array($error)) {
//Process your form
// 2. Perform Your Query
$post_title = $POST["title"];
$post_content = $POST["blog"];
$query = "INSERT INTO entries (blog_id, blog_title, blog_content)
VALUES ('null', '{$post_title}', '{$post_content}')";
$result = mysqli_query($connection, $query);
//Display confirmation of post.
if($result) {
echo "Post submitted!";
} else {
echo "Error, post NOT submitted!";
}
//Require or include any page footer you might have
//here as well so the style of your page isn't broken.
//Then exit the script.
exit;
} else {
echo $error;
}
}
?>
<doctype>
<html>
<head>
<title> Blog </title>
</head>
<body>
<form method="POST" action="blog.php">
Title: <input name="title" type="text"> <br />
Blog: <textarea name="blog" cols="100" rows="5"> Blog Text here... </textarea> <br />
<input value="submit" type="submit" value="Submit" />
</form>
</body>
</html>
Here is a screen shot of the form AFTER submitting it.
Here is a screenshot of MYSQL database called blog
, and table called entries
:
Here is the structure of my database:
Does anybody know what I'm doing wrong. I am new to PHP and I have no idea how to debug a problem when I'm getting no errors!
UPDATE 1. The solution worked. Thank you. However I getting the following error:
Notice: Undefined variable: error in C:\XAMPP\htdocs\blogwebsite\blog.php on line 30
I know it's because I have not initialized the $error[] array. But what is the standard way of getting rid of this error? Please help!