Simple PHP 'blog entry' form not submitting to MYSQL database? [duplicate] - php

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 7 years ago.
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!

Your if(isset($_POST['submit'])) { condition will not set as true because you did not set a name tag for your submit button.
It should be
<input value="Submit" type="submit" name="submit"/>
Then on the re-assigning to another variable the passed-on data from the form, it should not be $POST["title"], it should be $_POST["title"].
You should also consider using mysqli_real_escape_string to prevent SQL injections.
$post_title = mysqli_real_escape_string($connection, $_POST["title"]);
$post_content = mysqli_real_escape_string($connection, $_POST["blog"]);
But still, you should use prepared statement rather than using mysqli_* with the functions of the deprecated mysql_* API.
Regarding the error you are getting for undefined variable, why don't you just scrap the input checking part of your code, and replace it with simply this:
if(!empty($_POST["title"]) || !empty($_POST["blog"])){ /* IF BOTH INPUTS HAVE CONTENTS */
/* THE CODE YOU WANT TO EXECUTE */
}
else {
$error = "<p>Please supply a title or a blog content.</p>\n";
}
Or just remove your input checking, and use HTML's required attribute.
<input name="title" type="text" required>
<textarea name="blog" cols="100" rows="5" required>
so that your PHP code will be straight-forward:
if(isset($_POST["submit"])){
/* YOUR INSERT QUERY HERE */
}
The cons of required, as well as the !empty() condition, is that it accepts empty space (). To bypass this, you should use Javascript or libraries that support this kind of stuff.

In your html form, the submit element has two "value" attributes but no "name" attribute. Therefore it is not being found in the if(isset($_POST['submit'])) check and the original form being displayed as if nothing was posted.

Related

Undefined Variable PHP + MySQL [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
I know stackoverflow disapproves of repeat questions, but bear with me as I have scanned many similar questions without finding specific resolutions that will help me. (Mostly they mention things about avoiding database insertions)
I encounter these error messages:
here db connection success
Notice: Undefined variable: firstname in C:\xampp\htdocs\practice_connection_app\submit.php on line 10
Notice: Undefined variable: lastname in C:\xampp\htdocs\practice_connection_app\submit.php on line 10
Notice: Undefined variable: conn in C:\xampp\htdocs\practice_connection_app\submit.php on line 11
Fatal error: Call to a member function exec() on null in C:\xampp\htdocs\practice_connection_app\submit.php on line 11
The first result simply shows that I have connected to my database which I made using phpMyadmin.
Here is my relevant code (my html submission page which calls on a php action):
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>student info</title>
</head>
<body>
<br>
Enter your first name and last name in the corresponding boxes.
<br>
<form action="submit.php" method="POST">
First: <input type="text" name="firstname"/>
<br>
Last: <input type="text" name="lastname"/>
<br>
<input type="submit">
</form>
</body>
</html>
the database connection (I think)
<?php
echo 'here';
$dsn = 'mysql:host=localhost;dbname=practice_students';
$username = 'test_usr';
$password = 'pa55word';
try {
$db = new PDO($dsn, $username, $password);
echo 'db connection success';
} catch (PDOException $e) {
$error_message = $e->getMessage();
include('database_error.php');
exit();
}
?>
AND my php submit page
<?php
echo 'here ';
$dsn = 'mysql:host=localhost;dbname=practice_students';
try {
$db = new PDO($dsn);
echo 'db connection success';
$sql = "INSERT INTO people (firstname, lastname)
VALUES ('$firstname', '$lastname')";
$conn->exec($sql);
echo "Now we know your name! Hi," . " " . $firstname . " " . $lastname;
} catch (PDOException $e) {
$error_message = $e->getMessage();
include('database_error.php');
exit();
}
?>
I understand that I may need to do some 'cleaning up' to avoid database insertions, but for now I would just like to know how I can ensure my submissions are going to the database and can be returned.
Thanks in advance!
Not sure which manual you ahve been reading to end up with that code....
You need to access your POST variables (using $_POST['firstname']) AFTER sanitizing them of course....
EDIT:
To access the POSTed variable, you can do the following:
$firstname = $_POST['firstname'];
But you really need some santization going on, you could use php's filter_var:
$firstname = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);
Though, you can do better than that, and be very strict in what you allow through your filters / sanitizers... Please go investigate this part after you get your code "working" :)

Form won't save anything in database [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
My form won't save in my db
connect code saved as con_mysql.php:
<?php
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PSWD', '*****');
DEFINE ('DB_NAME', 'lexusdb');
$dbcon = mysqli_connect(DB_HOST, DB_USER, DB_PSWD, DB_NAME);
?>
form code:
<form method="post" action="newep.php">
<input type="hidden" name="submitted" value="true" />
<fieldset>
<legend>New Content:</legend>
<label>Name: <input type="text" name="newcontent" /></label>
</fieldset>
<br />
<input type="submit" value="add new anime" />
</form>
<?php
echo $newrecord
?>
PHP:
<?php
if (isset($_POST['submit'])) {
include('con_mysql.php');
$nanime = $_POST['newcontent'];
$sqlinsert = "INSERT INTO title (title_name) VALUES ('$newcontent')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('Error inserting new record');
}
$newrecord = "1 anime added";
}
?>
at first it just won't save anything in DB using the form, and now it also have Undefined variable: newrecord
all files saved in the same folder and newep.php is also created. my db consist of table named title, inside title have title_id INT(4) not null auto_increment then title_name VARCHAR(255) not null. I hope you guys can help me with this one as you guys have help me by just searching for what i need THANKS
Edit :
There is few things that your code is missing , but its ok , you still learning and its great way to start , learning from the faults is good .
One of the things and its one of the most important things that you missed is that you have to prevent SQL Injection in your code , even if you code was perfect but you query has that issue then you are in troubles , How can you protect your Query ? by this way : SQL INJECTION
Second , i see you using MYSQLI , which is a good relational database driver, but i prefer you start to use PDO . Whats PDO ?
PDO is an acronym for PHP Data Objects. PDO is a lean, consistent way
to access databases. This means developers can write portable code
much easier. PDO is not an abstraction layer like PearDB. PDO is a
more like a data access layer which uses a unified API (Application
Programming Interface).
Its easy and simple . What's the differenet between PDO and MYSQLI ?
Different between MYSQLI and PDO
Third thing and i will take that from one of the comments by Fred , You need to start using Error reporting , read this :
Errors Reports
Now to the code .
In your code you tried to echo a variable from the form before you receive the data from the form ( before the submit happen ) , so you should first send the data and receive it then do whatever you want with it .
In your code :
<?php
echo $newrecord
?>
The right way as you can see it here :
if (isset($_POST['submit']))
{
include_once('con_mysql.php');
$nanime = $_POST['newcontent'];
$sqlinsert = "INSERT INTO title (title_name) VALUES ('$nanime')";
if (!mysqli_query($dbcon, $sqlinsert))
{
die('Error inserting new record');
}
else
{
$newrecord = "1 anime added";
echo $newrecord;
}
}
I hope that my answer helped you , and remember the first part cause its so important .
Here is the full code .
<html>
<head>
</head>
<body>
<form method="post" action="">
<input type="hidden" name="submitted" value="true" />
<fieldset>
<legend>New Content:</legend>
<label>Name:
<input type="text" name="newcontent" /></label>
</fieldset>
<br />
<input type="submit" name="submit" value="add new anime" />
</form>
<?php
if (isset($_POST['submit']))
{
include_once('con_mysql.php');
$nanime = $_POST['newcontent'];
$sqlinsert = "INSERT INTO title (title_name) VALUES ('$nanime')";
if (!mysqli_query($dbcon, $sqlinsert))
{
die('Error inserting new record');
}
else
{
$newrecord = "1 anime added";
echo $newrecord;
}
}
?>
</body>
</html>
It looks like you have a typo when including the file which opens connection. Instead of:
include('con_mysql.php.php');
I guess it should be:
include('con_mysql.php');
The next thing is checking your $_POST. Only fields with a name would be there, so you need to change your condition from:
if (isset($_POST['submit'])) {
to:
if (!empty($_POST)) {
and finally you are using an uninitialized variable in your query,
so change that line:
$sqlinsert = "INSERT INTO title (title_name) VALUES ('$newcontent')";
to
$sqlinsert = "INSERT INTO title (title_name) VALUES ('$nanime')";

inserts a blank row in mysql db [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 8 years ago.
I am having issues when trying to insert ("username" as i use as an example) into my mysql db.. anyways, as soon as I update the site, I get the "success" message I set, if it worked as it should and a blank row is inserted into my db. However, it also works the normal way when typing something into the textbox (after I got the "success" message) and press submit, it's also getting inserted into the db. But my issue is this first blank insert that shouldn't be there, I have no further idea how to solve that one atm :/
I also get a notice in the top of the site, saying "Undefined index: username", I have no idea what I've done wrong :/
Here's my code btw:
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "pw";
$dbname = "dbname";
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
}
$user = $_POST["username"];
$sql = "INSERT INTO account (username) VALUES ('$user')";
if($conn->query($sql) === true) {
echo "Success!";
} else {
echo "Error: " . $sql . "<br />" . $conn->error;
}
$conn->close();
?>
<form method="POST" action="">
<input type="text" name="username" placeholder="Username" /><br /><br />
<input type="submit" name="submit" value="Go" />
</form>
Thx in adv. :)
1) You are vulnerable to sql injection attacks. Enjoy having your server pwn3d.
2) Your code runs unconditionally, EVERY TIME the page is loaded. Therefore when a user first hits the page, you run your code. Since no form has been submitted, $_POST['username'] is undefined and you end up inserting an empty string into the DB.
At bare minimum you should have something like
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
... db code here ...
}
so that it only runs when a POST was performed.

can't insert data in a mysql database using php

first of all i am pretty new with mysql and php and for now i just want to insert some data in a mysql database form two text box using php.
here the database name is "info" and table name is "students" having three columns like id(primary key, auto increment activated), name and dept. There are two text boxes txtName and txtDept. I want that when i press the enter button the data form the text boxes will be inserted into the mysql database. I have tried the following code but data is not being inserted in the table....
<html>
<form mehtod="post" action="home.php">
<input type="text" name="txtName" />
<input type="text" name="txtDept" />
<input type="submit" value="Enter"/>
</form>
</html>
<?php
$con = mysqli_connect("localhost","root","","info");
if($_POST){
$name = $_POST['txtName'];
$dept = $_POST['txtDept'];
echo $name;
mysqli_query($con,"INSERT INTO students(name,dept) VALUES($name,$dept);");
}
?>
There are a few things wrong with your posted code.
mehtod="post" it should be method="post" - typo.
Plus, quote your VALUES
VALUES('$name','$dept')
DO use prepared statements, or PDO with prepared statements.
because your present code is open to SQL injection
and add error reporting
error_reporting(E_ALL);
ini_set('display_errors', 1);
You should also check for DB errors.
$con = mysqli_connect("localhost","root","","info")
or die("Error " . mysqli_error($con));
as well as or die(mysqli_error($con)) to mysqli_query()
Sidenote/suggestion:
If your entire code is inside the same file (which appears to be), consider wrapping your PHP/SQL inside a conditional statement using the submit button named attribute, otherwise, you may get an Undefined index... warning.
Naming your submit button <input type="submit" name="submit" value="Enter"/>
and doing
if(isset($_POST['submit'])){ code to execute }
Just doing if($_POST){ may give unexpected results when error reporting is set.
Rewrite: with some added security using mysqli_real_escape_string() and stripslashes()
<html>
<form method="post" action="home.php">
<input type="text" name="txtName" />
<input type="text" name="txtDept" />
<input type="submit" name="submit" value="Enter"/>
</form>
</html>
<?php
$con = mysqli_connect("localhost","root","","info")
or die("Error " . mysqli_error($con));
if(isset($_POST['submit'])){
$name = stripslashes($_POST['txtName']);
$name = mysqli_real_escape_string($con,$_POST['txtName']);
$dept = stripslashes($_POST['txtDept']);
$dept = mysqli_real_escape_string($con,$_POST['txtDept']);
echo $name;
mysqli_query($con,"INSERT INTO `students` (`name`, `dept`) VALUES ('$name','$dept')")
or die(mysqli_error($con));
}
?>
As per the manual: http://php.net/manual/en/mysqli.connect-error.php and if you wish to use the following method where a comment has been given to that effect:
<?php
$link = #mysqli_connect('localhost', 'fake_user', 'my_password', 'my_db');
if (!$link) {
die('Connect Error: ' . mysqli_connect_error());
}
?>
God save us all...
Use PDO class instead :). By using PDO you can additionally make prepared statement on client side and use named parameters. More over if you ever have to change your database driver PDO support around 12 different drivers (eighteen different databases!) where MySQLi supports only one driver (MySQL). :(
In term of performance MySQLi is around 2,5% faster however this is not a big difference at all. My choice is PDO anyway :).

Form submission giving me a server error

I've tried looking for the problem but I can't seem to figure it out. The form shows with no errors, but on google chrome it just says "Server Error" when I try and submit the form.
<?php
if (empty($_GET["entries"])) //check if the admin entered # of weeks
{
?>
<p>How many weeks do you want to make? </p>
<form action="" method="get">
<input type="text" name="entries" placeholder="Number of weeks" />
<br/>
<input type="submit" name="submit_entries" />
</form>
<?php
}
else
{
//Second form
if (isset($_POST["submit"])) //check if submitted
{
//Process form
$entries=$_GET['entries'];
$newWeeks=$_POST['week'];
$db= mysql_connect("localhost", "root", "root");
if(!$db) die("Error connecting to MySQL database.");
mysql_select_db("onlineform", $db);
$sql = "INSERT INTO onlineformdata (numberOfWeeks, newCampSessions) VALUES (" . PrepSQL($entries) . "," . PrepSQL($newWeeks) . ")";
mysql_query($sql);
if (mysql_query($sql) === FALSE) {
die(mysql_error());
}
mysql_close();
}
else //if not submitted yet, show the form
{
echo '<form action="" method="post">';
for ($count = 0; $count < $_GET["entries"]; $count++)
{
echo 'Enter a beginning to ending date for the week: <input type="text" name="week"><br/>';
}
echo '<input type="submit" name="submit"></form>';
}
}
?>
Maybe it's because I can't have the first form having an action pointing to itself (Where I'm using a method="get".
You don't appear to have defined the PrepSQL() anywhere. If that's the case you should be getting a fatal error, something like
Fatal error: Call to undefined function PrepSQL ...
Once that's fixed, if you're insert query is failing, it will probably be because of the values lacking enclosing quotes.
For future debugging you can turn errors on:
error_reporting(E_ALL);
ini_set('display_errors', '1');
Or you can just observe your server's error log. How that is done depends on the server setup so I suggest asking your host for directions.
Side note:
The mysql_* library is deprecated, consider upgrading to PDO or MySQLi
The use of a Prepared Statement is preferred to concatenating variables into your SQL.

Categories