Form not posting data into mysql Database - php

I am trying to post some data from my HTML form into my mysql database.
Here is my HTML code:
<!doctype html>
<html>
<head>
</head>
<body style="background-color:#BCB7B7">
<form id="form1" name="form1" method="post" style="text-align:center" action="post.php">
<input type="text" name="name" id="name" placeholder="Name">
<p></p>
<input type="text" name="age" id="age" placeholder="Age">
<p></p>
<input type="text" name="food" id="food" placeholder="Food">
<p></p>
<input type="submit" name="submit" id="submit" value="Submit">
</form>
</body>
</html>
and here is my php code:
<?php
$connect = mysql_connect("localhost","myusername","mypassword","mydbname");
mysql_select_db("mydbname",$connect);
mysql_query("INSERT INTO myTable VALUES Name = $_POST[name], Age = $_POST[age], Food = $_POST[food]");
?>
but the data does not get saved

Strings in SQL must be quoted. You are dumping your variables into the SQL without quotes.
Your syntax is also wrong. The format is INSERT INTO table_name (column_name, column_name) VALUES value, value.
You are also failing to escape the data, so you are vulnerable to SQL Injection attacks.
To fix your problems:
Stop using the deprecated mysql_ library and switch to mysqli_ or PDI
Use bound arguments to insert variables into your SQL
Use the correct syntax
This question about preventing SQL injection has examples of how to use those libraries safely.

There are 2 different versions of the INSERT command - you are using neither.
Either:
INSERT INTO myTable SET Name = "Peter",
Age = 15, Food = "pizza"
or
INSERT INTO myTable (Name, Age, Food) VALUES
("Peter", 15, "pizza")

You have to quote the values:
mysql_query("INSERT INTO myTable VALUES Name = '$_POST[name]', Age = '$_POST[age]', Food = '$_POST[food]'");
Hint: You should use mysqli_ or PDO_ functions as mysql_ functions are deprecated

try this
<?php
$connect = mysql_connect("localhost","myusername","mypassword","mydbname") or die("error while connecting to the database");
mysql_select_db("mydbname",$connect) or die("error while selecting the database");
mysql_query("INSERT INTO myTable VALUES ('" . mysql_real_escape_string($_POST[name]) . "', '" . mysql_real_escape_string($_POST[age]) . "', '". mysql_real_escape_string($_POST[food]) . "')");
?>

Related

Php MySQL simple form is inserting emptiness

I have this problem with phpMyAdmin. I've set up my simple php and mysql scripts and everything works fine. It connects to my mysql database(remote with my hosting provider) and it does actually insert all the required fields into the database. the problem is that the fields are all blank. there is nothing in them. here is my code:
<?php
$con = mysql_connect("myserverip","mydatabasename","my password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydatabasename", $con);
$sql="INSERT INTO nametable (firstname, lastname) VALUES('$_POST[firstname]','$_POST[lastname]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
The html is very simple, just two input fields with first name and last name:
The html:
<html>
<body>
<h1>A small example page to insert some data in to the MySQL database using PHP</h1>
<form action="insert.php" method="post">
Firstname: <input type="text" name="fname" /><br><br>
Lastname: <input type="text" name="lname" /><br><br>
<input type="submit" />
</form>
</body>
</html>
All help is appreciated.
Because you have enclosed your $_POST variables in single quotes ('), PHP is treating them as strings rather than as arrays, so the data is not being pulled from them. Your query should look something like this:
$sql = "
INSERT INTO
nametable (firstname, lastname)
VALUES
('" . $_POST['firstname'] . "', '" . $_POST['lastname'] . "')";
(whitespace added for readability)
Also, as some other users have pointed out, the mysql extension for PHP has been deprecated so it should not be used. Furthermore, the way your are building your query opens you up to something called SQL injection, which is very dangerous.
If this code is just for fun then that's fine, but you should not upload this to a production server under any circumstances.

How do I append data from a HTML form to a database on a button press? Possibly using PHP?

Okay so I have a webserver running off a Raspberry Pi at the moment and I have a really basic form with seven textboxes. I want the values entered into the textboxes to append to a database when I click the 'Submit' button. I have HTML code to create the form:
<!DOCTYPE html>
<html>
<head>
<title>Assignment Submission Form</title>
</head>
<body>
<form name="assi_subm" METHOD="POST" >
<p><label for="title">Title: </label><br><input id="title" name="title" type="text" size="25"></p>
<p><label for="password">Password: </label><br><input type="password" id="password" name="password" size="25" maxlength="20"></p>
<p><label for="soc">Statement of Contribution: </label><br><textarea style="width:300px;height:100px;" name="soc" id="soc"></textarea></p>
<p><label for="object">Project Objectives: </label><br><textarea style="width:300px;height:100px;" name="object" id="object"></textarea></p>
<p><label for="discuss">Review and Discussion of Technologies Used: </label><br><textarea style="width:300px;height:100px;" name="discuss" id="discuss"></textarea></p>
<p><label for="design">Design and Implementation: </label><br><textarea style="width:300px;height:100px;" name="design" id="design"></textarea></p>
<p><label for="references">References: </label><br><textarea style="width:300px;height:100px;" name="references" id="references"></textarea></p>
<p><input type="button" value="Submit"></p>
</form>
</body>
</html>
and that's fine, that opens as you'd expect. However I can't make the data from those textboxes actually append to the database when I click. I'm not totally sure if I'm even meant to be using PHP (I don't think I fully understand the concept in this situation) but I have the following code which is attempting to insert the data into the database by checking the button submission isn't empty? I'm not sure, I've been trying lots of different things but at the moment I'm just getting a blank page, I'm really confused, any help would be really appreciated.
This is my current PHP code:
<?php
$con = mysql_connect("localhost", "root", "password") or die("Could not connect");
$database = mysql_select_db("assignment_submission", $con) or die("Could not do");
$title_IP = $_POST['title'];
$password_IP = $_POST['password'];
$soc_IP = $_POST['soc'];
$object_IP = $_POST['object'];
$discuss_IP = $_POST['discuss'];
$design_IP = $_POST['design'];
$references_IP = $_POST['references'];
if (!empty($_POST)){
mysql_query($database, "INSERT INTO file_data (title, password, soc, object, discuss, design, references) values ($title_IP, $password_IP, $soc_IP, $object_IP, $discuss_IP, $design_IP, $references_IP);
}
?>
You have missing quotes around your values and a double quote plus a missing bracket.
You're also using the wrong variable $database for your insert, you can just remove it since you are using mysql_ as opposed to mysqli_ where DB connection is mandatory.
Another thing is the word references, it's a reserved word and must be wrapped in backticks.
`references`
Replace with the following:
mysql_query("INSERT INTO file_data (title, password, soc, object, discuss, design, `references`) values ('$title_IP', '$password_IP', '$soc_IP', '$object_IP', '$discuss_IP', '$design_IP', '$references_IP')");
Or you can also use:
if (!empty($_POST)){
$sql = "INSERT INTO file_data (title, password, soc, object, discuss, design, `references`) values ('$title_IP', '$password_IP', '$soc_IP', '$object_IP', '$discuss_IP', '$design_IP', '$references_IP')";
$query = mysql_query( $sql, $con );
if($query ){
echo "Success";
}
else{
die('Could not insert data: ' . mysql_error());
}
}
Your present code is open to SQL injection. Use prepared statements, or PDO.
As the very least, use mysql_real_escape_string() around your POST variables.
I.e.: $title_IP = mysql_real_escape_string($_POST['title']);
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
During development
Add error reporting to the top of your file(s)
error_reporting(E_ALL);
ini_set('display_errors', 1);
which will signal errors found.
Edit
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$con = mysql_connect("localhost", "root", "password") or die("Could not connect");
$database = mysql_select_db("assignment_submission", $con) or die("Could not do");
if (isset($_POST['submit'])){
$title_IP = $_POST['title'];
$password_IP = $_POST['password'];
$soc_IP = $_POST['soc'];
$object_IP = $_POST['object'];
$discuss_IP = $_POST['discuss'];
$design_IP = $_POST['design'];
$references_IP = $_POST['references'];
$sql = "INSERT INTO file_data (title, password, soc, object, discuss, design, `references`) values ('$title_IP', '$password_IP', '$soc_IP', '$object_IP', '$discuss_IP', '$design_IP', '$references_IP')";
$query = mysql_query( $sql, $con );
if($query ){
echo "Success";
}
else{
die('Could not insert data: ' . mysql_error());
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Assignment Submission Form</title>
</head>
<body>
<form name="assi_subm" METHOD="POST" action="">
<p><label for="title">Title: </label><br><input id="title" name="title" type="text" size="25"></p>
<p><label for="password">Password: </label><br><input type="password" id="password" name="password" size="25" maxlength="20"></p>
<p><label for="soc">Statement of Contribution: </label><br><textarea style="width:300px;height:100px;" name="soc" id="soc"></textarea></p>
<p><label for="object">Project Objectives: </label><br><textarea style="width:300px;height:100px;" name="object" id="object"></textarea></p>
<p><label for="discuss">Review and Discussion of Technologies Used: </label><br><textarea style="width:300px;height:100px;" name="discuss" id="discuss"></textarea></p>
<p><label for="design">Design and Implementation: </label><br><textarea style="width:300px;height:100px;" name="design" id="design"></textarea></p>
<p><label for="references">References: </label><br><textarea style="width:300px;height:100px;" name="references" id="references"></textarea></p>
<p><input type="submit" name="submit" value="Submit"></p>
</form>
</body>
</html>
Correct your sql query, use this code:
if (!empty($_POST)){
mysql_query($database, "INSERT INTO file_data ($title_IP, $password_IP, $soc_IP, $object_IP, $discuss_IP, $design_IP, $references_IP)
}
and $ signs in PHP are used to create as well as reference variables, so you gotta use them everywhere.

Inserting datafrom form into mysql with POST method

I havent do php for some time, but i dont really see what am I missing.
I am trying to insert some datas from FORM into MYSQL , but it still fail.
This is the file with FORM :
<html>
<head>
<link type="text/css" rel="stylesheet" href="stylesheet.css"/>
<title>registrace</title>
</head>
<body>
<H1> The Best Page! </H1>
<p>
"Please registrate"
<form action="zpracovani.php" method="post">
Name <input type="text" size="20" name="Name" value=""><br>
Surname <input type="text" size="30" name="Surname" value=""><br>
Username <input type="text" size="30" name="username" value=""><br>
Password <input type="text" size="10" name="password" value=""><br>
Retype password <input type="text" size="10" name="password2" value=""><br>
<input type="image" name="button" value="submit" class="button" src="button.jpg">
</form>
</p>
</body>
</html>
As you can see i am sending data to proceed into file "zpracovani.php". I did test if i am connected to mysql server ( It passes ) and also a check if i am connected to the right database ( Also passes with no probs ).
<html>
<?php
echo "Wait please";
$con=mysql_connect ('localhost','root','');
if (!$con)
{
die ( 'Could not connect: ' . mysql_error());
}
mysql_select_db ('registrace') or die("cannot select DB");
echo #mysql_ping() ? 'true' : 'false';
$sql="INSERT INTO 'registrace'(Name, surname, username, password).
VALUES('$_POST[Name]','$_POST[Surname]','$_POST[username]','$_POST[password]')";
$result=mysql_query($sql);
if($result){
echo("<br>Input data is succeed");
}else{
echo("<br>Input data is fail");`
}
mysql_close($con);
?>
</html>
Below is overwiev of mysql table I made.
ID int(11)
Name varchar(20) latin1_swedish_ci
Surname varchar(30) latin1_swedish_ci
username varchar(30) latin1_swedish_ci
password varchar(10) latin1_swedish_ci
However I am connected to the database and to correct table it still is unable to insert anyone into the database. Can anyone look into this and help me out, please?
Thanks in advance!
Either remove the quotes in 'registrace' or use backticks in INSERT INTO 'registrace'
Example:
INSERT INTO `registrace`
Using backticks is better.
Also remove the dot in:
$sql="INSERT INTO 'registrace'(Name, surname, username, password).
It should read as:
$sql="INSERT INTO `registrace` (Name, surname, username, password)
Reformatted:
$sql="INSERT INTO `registrace` (Name, surname, username, password)
VALUES
('{$_POST['Name']}','{$_POST['Surname']}','{$_POST['username']}','{$_POST['password']}')";
Or follow this convention:
$unsafe_variable = $_POST["user-input"]
$safe_variable = mysql_real_escape_string($unsafe_variable);
mysql_query("INSERT INTO table (column) VALUES ('" . $safe_variable . "')");
NOTE: I also noticed that you are using the same name for both your DB and your table.
Make sure that this is in fact the case.
Your DB:
mysql_select_db ('registrace')
and your table?
INSERT INTO `registrace`
Plus, it would be a good idea to increase the values for your VARCHAR's and consider using MySQLi_ and prepared statements or PDO. MySQL_ functions are deprecated.
Do read the following articles:
How can I prevent SQL injection in PHP?
On owasp.org
First: use mysqli
Second: get rid of mysql ping
Third: change:
"......'$_POST[xxx]'......"
into:
"......'{$_POST['xxx']}'....."
Thanks guys it is working now.
By the way the mysql ping was just a check to see if i am well connected as i wrote in my original post :)
Anyway it was very helpful thx

PHP FORM INSERT INTO not inserting records

I'm working on a Uni assignment and am having trouble inserting records to MySQL database using a form. My set up is below.
I can view entries in the database with no problem. I'm new to this so sorry in advance :(
conninfo.php
<?php
$strServer="localhost";
$strDatabase="djdatabase"; // CHANGE TO YOUR DATABASE NAME HERE
$strUser="root";
$strPwd=""; // Leave blank for WAMPServer
$strDB=mysql_connect($strServer,$strUser,$strPwd)or die("Could not open database");
$database=mysql_select_db("$strDatabase",$strDB);
?>
addnewdata.php
<?php include "conninfo.php";
$newdj=$_POST["dj"]; //pick up from form
$newfn=$_POST["fn"];
$newem=$_POST["em"];
$newwe=$_POST["we"];
$newpi=$_POST["pi"];
$newev=$_POST["ev"];
$query = "INSERT INTO dj(DJName, FirstName, Email, Website, Picture, EventNumber)VALUES('$newdj', '$newfn', '$newem', '$newwe', '$newpi', '$newev)";
mysql_query($query);
header("location:showall.php");
?>
enternewdata.php
<?php include "conninfo.php";?>
<html>
<head>
</head>
<body>
<form action="addnewdata.php" method="post">
DJ Name:<input type="text" name="dj"><br>
FirstName: <input type="text" name="fn" /><br>
Email: <input type="text" name="em" /><br>
Website: <input type="text" name="we" /><br>
Picture: <input type="text" name="pi" /><br>
EventID: <input type="text" name="ev" /><br>
<br><br>
<button type="submit">Submit</button>
</form>
</body>
</html>
Many Thanks for your help :)
had better use SET command to insert data
$query = "INSERT INTO dj SET
DJName=".$newdj.",
FirstName=".$newfn.",
Email=".$newem.",
Website=".$newwe.",
Picture=".$newpi.",
EventNumber=".$newev."";
$save = mysql_query($query);
if($save){
header("location:showall.php");
}else{
die(mysql_error());
}
You are missing a quote ' wich is causing the error that you cannot see because you haven't done any debug. Anyway you should just change to this
'$newwe', '$newpi', '$newev')"; //a quote was missing after '$newv
I would suggest you to also debug query by adding or die('INVALID QUERY: ' . mysql_error());
so code would look like
mysql_query($query) or die('INVALID QUERY: ' . mysql_error());
Since you said this is an university test I don't know if you are supposed to use mysql_* function (wich are deprecated), but I would strongly reccommend to switch to mysqli or PDO if you can for security reason.
You missed ' on your query on $newev that gives you an error
$query = "INSERT INTO dj(DJName, FirstName, Email, Website, Picture, EventNumber)VALUES('$newdj', '$newfn', '$newem', '$newwe', '$newpi', '$newev)";

Can't Insert Into Database

I have a database, and I can't insert values into it. Here's my database and my code.
Can you tell me what my problem is?
The output tell me that my sql syntax is wrong. However, I can add values from phpmadmin without any problems.
When I use code, I fail. And, I couldn't find any proble.
Thank yuy very much.
DATABASE
<?php
$db_username = "root";
$db_password = "pass";
$db = "rmado";
$db_server = "localhost";
$db_handle = mysql_connect($db_server, $db_username, $db_password);
$db_found = mysql_select_db($db, $db_handle);
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$title = $_POST['username'];
$desc = $_POST['password'];
$aaa = $_POST['type'];
$bbb = $_POST['email'];
$query = "insert into users(username, password, type, email) values ($title, $desc, $aaa, $bbb)";
mysql_query($query);
}
?>
<html>
<body>
<div id="login_form">
<form name="login_form" method="post" action="zort.php">
username: <input name="username" type="text" value="">
password: <input name="password" type="text" value="">
type: <input name="type" type="text" value="">
email: <input name="email" type="text" value="">
<input name="addtask" type="submit" value="add task">
</form>
</div>
<!-- end login_form-->
</body>
</html>
Thank you very much.
EDIT:
id: int(5)
title: varchar(30)
desc: varchar(50)
assigner_id: int(5)
assignee_id: int(5)
creation_date: date
due_date: date
status_id: int(5)
category_id: int(5)
and here's my php code:
$query = "insert into tasks (title, desc, assigner_id, assignee_id, creation_date, due_date, status_id, category_id) values ('$title', '$desc', $ass1, $ass2, '$cre', '$due', $stat, $cat)";
Where's wrong in this code? Thank you very much.
Per your original question: all those fields are text in your table. You're not encapsulating your values with quotation marks in your original query for these text fields. That is, the following will work for your example:
$query = "insert into users (username, password, type, email) values " .
"('$title', '$desc', '$aaa', '$bbb')";
This will let MySQL know what strings you want inserted for those fields.
However, there are several issues with what you have on this page. A malicious user could put some MySQL-acceptable strings into these fields and those could cause harm to your database. You need to escape your input strings to prevent malicious content from damaging your database.
Considering using also mysqli or PDO as you are using a deprecated library. See here for some examples.
Also, your fields should not be text fields. They really should be varchars and you should limit their length.
EDIT
Your second query needs to encapsulate desc with backticks because DESC is a reserved MySQL word for descending.

Categories