Form won't save anything in 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 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')";

Related

Info does not submit into database

We have an assignment for school and I've tried to build the application, however some text that I want to have inserted into a database doesn't get submitted.
I've tried different things, but the page does not show an error either.
This is the code of my insert page
<head>
</head>
<body>
<form action="index.php" method="post">
ID: <input type="text" name="id"><br/>
Server: <input type="text" name="Server"><br/>
Student: <input type="text" name="Student"><br/>
Docent: <input type="text" name="Docent"><br/>
Project: <input type="text" name="Project"><br/>
Startdatum: <input type="text" name="Startdatum"><br/>
Einddatum: <input type="text" name="Einddatum"><br/>
<input type="submit" name="submit">
</form>
<?php
if(isset($_POST['submit'])) {
$con = mysqli_connect("localhost", "root", "usbw", "serverruimte");
if(!$con) {
die(mysqli_connect_error());
}
$sql = "INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES ('$_POST[id]','$_POST[Server]','$_POST[Student]','$_POST[Docent]','$_POST[Project]','$_POST[startdatum]','$_POST[einddatum]')";
$result = mysqli_query($con, $sql);
if($result) {
echo "Opslaan voltooid!";
} else {
echo mysqli_error($con);
}
mysqli_close($con);
}
?>
</body>
</html>
Basically, what happens is: https://i.imgur.com/aUOx5yj.mp4
Does anyone know what the problem is and why the inserted data does not show up on the index page? The data does show on the page when I submit it directly into the MYSQL database.
Warning: You are wide open to SQL Injections and should use parameterized prepared statements instead of manually building your queries. They are provided by PDO or by MySQLi. Never trust any kind of input! Even when your queries are executed only by trusted users, you are still in risk of corrupting your data. Escaping is not enough!
When working with MySQLi you should enable automatic error reporting instead of checking for errors manually. Checking for errors manually is a terrible practice, very error prone and should be avoided at all costs. Let MySQLi throw exceptions and do not catch them. See How to get the error message in MySQLi?
When opening MySQLi connection you must specify the correct charset. The recommended one is utf8mb4.
if (isset($_POST['submit'])) {
// Enable automatic error reporting
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// Create new instance of MySQLi class
$con = new mysqli("localhost", "root", "usbw", "serverruimte");
// Set correct charset. Important!
$con->set_charset('utf8mb4');
$stmt = $con->prepare('INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES (?,?,?,?,?,?,?)');
$stmt->bind_param('sssssss', $_POST['id'], $_POST['Server'], $_POST['Student'], $_POST['Docent'], $_POST['Project'], $_POST['startdatum'], $_POST['einddatum']);
$stmt->execute();
echo "Opslaan voltooid!";
mysqli_close($con);
}
Change this line:
$sql = "INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES ('$_POST[id]','$_POST[Server]','$_POST[Student]','$_POST[Docent]','$_POST[Project]','$_POST[startdatum]','$_POST[einddatum]')";
to:
$sql = "INSERT INTO serverruimte (id,Server,Student,Docent,Project,startdatum,einddatum) VALUES ('".$_POST['id']."','".$_POST['Server']."','".$_POST[Student]."','".$_POST['Docent']."','".$_POST['Project']."','".$_POST['Startdatum']."','".$_POST['Einddatum']."')";
Reason behind this change is because your query is wrong for the following reasons:
You were using strings instead of concatenating your real values coming from $_POST
Some of your indexes in $_POST were misspelled. For example:
$_POST[einddatum] should be $_POST['Einddatum']
Also, consider that this code is vulnerable to SQL Injection

Simple PHP 'blog entry' form not submitting to MYSQL 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 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.

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 :).

PHP form not writing to mySQL database

I'm just learning PHP and am trying the most basic thing: capturing info from a form and sticking it into a table in a mySQL database. I'm embarrassed to ask such a stupid newbie question, but after reviewing two books, several Stack Overflow posts, and 7 different tutorials, I still can't get my pathetic code to write a few lousy metrics to my database.
Here's the latest version of the code. Could someone please tell me what I am doing wrong?
* Basic HTML Form *
<form method="post" action="post_metrics_stack.php" >
<p>Date<br />
<input name="date" type="text" /></p>
<p>Metric1<br />
<input name="metric1" type="text" /></p>
<p>Metric2<br />
<input name="metric2" type="text" /></p>
<input type="submit" name="submit" value="Submit" />
</form>
* Processor File *
<?php
$date=$_POST['date'];
$metric1=$_POST['metric1'];
$metric2=$_POST['metric2'];
$con = mysql_connect("localhost", "root", "mypassword");
if (!$con)
{die('Could not connect to mysql: ' . mysql_error());}
$mydb = mysql_select_db("mydatabasename");
if (!$mydb)
{die('Could not connect to database: ' . mysql_error());}
mysql_query("INSERT INTO my_metrics VALUES ('$date', '$metric1', '$metric2')");
Print "Your metrics have been successfully added to the database.";
mysql_close($con);
?>
Your mysql-syntax is wrong.
Try
INSERT INTO my_metrics
SET
date = '$date',
metric1 = '$metric1',
metric2 = '$metric2'
Depending on what the table looks like, your code may or may not work,
"INSERT INTO my_metrics VALUES ('$date', '$metric1', '$metric2')"
assumes that the fields are in that order, and that there are no fields before this one.
"INSERT INTO my_metrics (date, metric1, metric2) VALUES ('$date', '$metric1', '$metric2')"
would be more future proof, and may also solve your problem as they are going to insert into the correct fields.
It is also possible that you are getting some bad data for the field definitions, try doing the insert in phpmyadmin or at the command line instead of in php, then work backwards from there.
As far as the vulnerability to SQL injection, you should feed your input strings to mysql_real_escape_string();. This will escape any unwanted characters.
When connecting to the database, you write
$con = mysql_connect("localhost", "root", "mypassword");
if (!$con)
{die('Could not connect to mysql: ' . mysql_error());}
You can simplify this, and making this more readable by writing
mysql_connect('localhost','root','mypassword') or die('Could not connect to mysql:<hr>'.mysql_error());
For solving your problem, see if specifieng column names helps. If you don't, mysql will assume you enter values in the order of the columns, you might get some trouble with an ID field, or something like that. Your query could look like this:
"INSERT INTO my metrics (date,metric1,metric2) VALUES ('$data','$metric1','$metric2'))"
And finally, here's a speed concideration.
There are two ways to write strings: using single quotes ('string'), and using double quotes ("string"). in the case of 'string' and "string", they will work exactly the same, but there is a difference. Look at the following code
$age=3
echo 'the cat is $age years old.';
//prints out 'the cat is $age years old.'
echo "the cat is $age years old.";
//prints out 'the cat is 3 years old'
echo 'the cat is '.$age.' years old';
//prints out 'the cat is 3 years old'.
As you can see from this example, when you use single quotes, PHP doesn't check the string for variables and other things to parse inside the string. Doing that takes PHP longer than concatinating the variable to the string. so although
echo "the cat is $age years old"
is shorter to type than
echo 'the cat is '.$age.' years old';
it will boost your page loading when you write larger applications.
Hooray! Hooray! Hooray!
Thank you all for such helpful advice! It finally works! Here's the updated code in case any other newbies have the same issue. (Hope I didn't screw anything else up.)
Form
<form method="post" action="post_metrics_stack.php" >
<p>Date<br />
<input name="date" type="text" /></p>
<p>Metric1<br />
<input name="metric1" type="text" /></p>
<p>Metric2<br />
<input name="metric2" type="text" /></p>
<input type="submit" name="submit" value="Submit" />
</form>
Processor
<?php
ini_set('display_errors', 1); error_reporting(E_ALL);
// 1. Create connection to database
mysql_connect('localhost','root','mypassword') or die('Could not connect to mysql: <hr>'.mysql_error());
// 2. Select database
mysql_select_db("my_metrics") or die('Could not connect to database:<hr>'.mysql_error());
// 3. Assign variables (after connection as required by escape string)
$date=mysql_real_escape_string($_POST['date']);
$metric1=mysql_real_escape_string($_POST['metric1']);
$metric2=mysql_real_escape_string($_POST['metric2']);
// 4. Insert data into table
mysql_query("INSERT INTO my_metrics (date, metric1, metric2) VALUES ('$date', '$metric1', '$metric2')");
Echo 'Your information has been successfully added to the database.';
print_r($_POST);
mysql_close()
?>
Here you go love :) try W3c it a good place for new pepps
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$sql="INSERT INTO my_metrics (date, metric1, metric2)
VALUES
('$_POST[date]','$_POST[mertric1]','$_POST[metric2]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "Your metrics have been successfully added to the database.";
mysql_close($con)
?>

Categories