Inserting data to database via web form - php

I have looked for the answer to my question and seeing as all programming varies I can't seem to fix my problem. I have created a php file that does in fact connect to my database. However, when I try submitting data to my database via my php webpage it won't go through. The same happens when I try to display info from my database to a webpage. Seeing as it is in fact connecting to the database, I'm not sure what the issue is. Any help is appreciated, try to dumb it down for me as much as possible when you answer. Also, I have triple-checked my database name and table names to make sure they match up with my coding. Here's my code:
Connection to database:
<?php
DEFINE ('DB_USER', 'root');
DEFINE ('DB_PSWD', '');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'art database');
$dbcon = mysqli_connect(DB_HOST, DB_USER, DB_PSWD, DB_NAME);
?>
My form to insert data to my database:
<?php
if (isset($_POST['submitted'])) {
include('connect-mysql.php');
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$sqlinsert = "INSERT INTO users (first name, last name) VALUES ('$fname','$lname')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
$newrecord = "1 record added to the database";
} // end of the main if statement
?>
<html>
<head>
<title>Insert Data into DB</title>
</head>
<body>
<hl>Insert Data into DB</hl>
<form method="post" action="insert-data.php">
<input type="hidden" name="submitted" value="true"/>
<fieldset>
<legend>New People</legend>
<label>First Name:<input type="text" name="fname" /></label>
<label>Last Name:<input type="text" name="lname" /></label>
</fieldset>
<br />
<input type="submit" value="add new person" />
</form>
<?php
echo $newrecord;
?>
</body>
</html>

The reason it's not working is because you have spaces in your columns/query.
INSERT INTO users (first name, last name)
wrap them in backticks like this:
INSERT INTO users (`first name`, `last name`)
It is not recommended to use spaces in column names or tables.
Try and use underscores instead, or remove the spaces and make the appropriate changes to your columns in your DB also, if you do.
You should also consider using:
('" . $fname . "','" . $lname . "')
instead of ('$fname','$lname')
I'm also questioning this => DEFINE ('DB_NAME', 'art database');
There is a space in between art and database. If that is the case and is in fact the name you've given your DB, do rename it to art_database and use DEFINE ('DB_NAME', 'art_database'); instead.
And do use the following for added protection:
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
Interesting article to read on protection:
How can I prevent SQL injection in PHP?
EDIT: (options)
OPTION 1, in 2 files:
First, rename your columns to firstname and lastname and use the following code and naming your file insert-data.php
DB query file (insert-data.php)
<?php
if (isset($_POST['submit'])) {
include('connect-mysql.php');
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
$sqlinsert = "INSERT INTO `users` (firstname, lastname) VALUES ('" . $fname . "','" . $lname . "')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
echo "1 record added to the database";
} // end of the main if statement
?>
Then in a seperate file, your HTML form; name it db_form.php for example:
HTML form (db_form.php)
<html>
<head>
<title>Insert Data into DB</title>
</head>
<body>
<hl>Insert Data into DB</hl>
<form method="post" action="insert-data.php">
<input type="hidden" name="submitted" value="true"/>
<fieldset>
<legend>New People</legend>
<label>First Name:<input type="text" name="fname" /></label>
<label>Last Name:<input type="text" name="lname" /></label>
</fieldset>
<br />
<input type="submit" name="submit" value="add new person" />
</form>
</body>
</html>
NEW EDIT - OPTION 2, all in one file:
Use this in one page, with nothing else added:
<?php
if (isset($_POST['submit'])) {
if(empty($_POST['fname'])) {
die("Fill in the first name field.");
}
if(empty($_POST['lname'])) {
die("Fill in the last name field.");
}
include('connect-mysql.php');
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
$sqlinsert = "INSERT INTO `users` (firstname, lastname) VALUES ('" . $fname . "','" . $lname . "')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
echo "1 record added to the database";
} // end of the main if statement
?>
<html>
<head>
<title>Insert Data into DB</title>
</head>
<body>
<hl>Insert Data into DB</hl>
<form method="post" action="">
<fieldset>
<legend>New People</legend>
<label>First Name:<input type="text" name="fname" /></label>
<label>Last Name:<input type="text" name="lname" /></label>
</fieldset>
<br />
<input type="submit" name="submit" value="add new person" />
</form>
<?php
echo $newrecord;
?>
</body>
</html>

I have made some changes, which is working fine for me
Where i can ignore if data is already in database
You Can try this to
<?php
if (isset($_POST['submit'])) {
include('db.inc.php');
$fname = mysqli_real_escape_string($dbcon,trim($_POST['fname']));
$lname = mysqli_real_escape_string($dbcon,trim($_POST['lname']));
// $sqlinsert = "INSERT INTO `user` (firstname, lastname) VALUES ('" . $fname . "','" . $lname . "')";
$sqlinsert = "INSERT IGNORE INTO `dbname`.`user` (`fname`, `lname`) VALUES ( '$fname', '$lname')";
if (!mysqli_query($dbcon, $sqlinsert)) {
die('error inserting new record');
} //end of nested if
echo "1 record added to the database";
} // end of the main if statement
?>
Where db.inc.php is a different file in same directory for connecting database
<?php
$dbcon=mysqli_connect("localhost","dbuser","yourpassword","dbname");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>

Related

How Do I populate my table in SQL with input from the user? PHP

Just starting out with PHP. I have code that gets user input through a form and enters the input into a mySQL table. The code has no parse errors. But when a user submits their name and email. It is not going into the table, the table is still empty, and I cannot seem to figure out the problem. Here is my code:
<div id="main">
<h1>Insert data into database using PDO</h1>
<div id="login">
<h2>Students Form</h2>
<hr/>
<form action="" method="post">
<label>Student Name :</label>
<input type="text" name="name" id="Fname" required="required" placeholder="Please Enter Your Name"/><br/><br/>
<label>Student Email :</label>
<input type="text" name="email" id="email" required="required" placeholder="Pear#gmsil.com"/><br/><br/>
<input type="submit" value=" Submit " name="submit"/><br/>
</form>
</div>
</div>
<?php
//server name
$db_hostname = "lll";
//database name
$db_database = "lll";
//username
$db_username = "lll";
$db_password = "lll;";
$db_charset = "utf8mb4";
//a string specifying the database type, the hostname and name of the database
$dsn = "mysql:host=$db_hostname;dbname=$db_database;charset=$db_charset";
$opt = array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE =>PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
);
try {
//create connection
$pdo = new PDO($dsn,$db_username,$db_password,$opt);
if (isset($_POST["submit"])) {
$pdo->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO students (name,email)";
VALUES ('". $_POST["name"] ."','" . $_POST["email"] . "');
if ($pdo->query($sql)) {
echo "<script type= 'text/javascript'>alert('New Student Inserted Successfully');</script>";
} else {
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}
}
} catch (PDOException $e) {
echo $e->getMessage();
}
?>
in the line of code where you write the SQL statement, you placed an extra "; before the second half of the query.
Change
$sql = "INSERT INTO students (name,email)";
VALUES ('". $_POST["name"] ."','" . $_POST["email"] . "');
to
$sql = "INSERT INTO students (name,email) VALUES ('". $_POST["name"] ."','" . $_POST["email"] . "');
This should fix the problem with your failed inserts.

Can't insert new records through PHP into mysql database

When I press the submit button I get error.
object not found error.
And the page automatically adds empty entries with auto incremented primary key (without pressing the submit button).
I am still a beginner in PHP, I searched thoroughly but I can't find out what's wrong in code.
<html>
<head>
<title>Add New Record in MySQL Database</title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="Name">Full Name:</label>
<input type="text" name="Name" id="Name">
</p>
<p>
<label for="Code">Code:</label>
<input type="text" name="Code" id="Code">
</p>
<p>
<label for="GPA">GPA:</label>
<input type="text" name="GPA" id="GPA">
</p>
<input type="submit" value="Submit">
</form>
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "username", "password", "students");
// Check connection
if ($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$full_name = filter_input(INPUT_POST, 'full_name');
$code = filter_input(INPUT_POST, 'code');
$gpa = filter_input(INPUT_POST, 'gpa');
// attempt insert query execution
$sql = "INSERT INTO info VALUES ('$full_name', '$code', '$gpa')";
if (mysqli_query($link, $sql)) {
echo "Records added successfully. $full_name";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
</body>
</html>
Try this:
$full_name = filter_input(INPUT_POST, 'Name');
$code = filter_input(INPUT_POST, 'Code');
$gpa = filter_input(INPUT_POST, 'GPA');
The reason why I wrote that is because your input names contain Name, Code and GPA so you need to write this exactly as your input names (case-sensitive).
Do with isset(). when the submit button clicks only the code runs.
Inside the php you should use the form input name field.
<?php
if(isset($_POST['submit'])){
$link = mysqli_connect("localhost", "username", "password", "students");
if ($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$full_name = filter_input(INPUT_POST, 'full_name');
$code = filter_input(INPUT_POST, 'code');
$gpa = filter_input(INPUT_POST, 'gpa');
//to prevent sql injection attack
$full_name = mysqli_real_escape_string($link, $full_name);
$code = mysqli_real_escape_string($link, $code);
$gpa = mysqli_real_escape_string($link, $gpa);
// attempt insert query execution
$sql = "INSERT INTO info (Name,Code,GPA) VALUES ('$full_name', '$code', '$gpa')";
if (mysqli_query($link, $sql)) {
echo "Records added successfully. $full_name";
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
}
?>
<html>
<head>
<title>Add New Record in MySQL Database</title>
</head>
<body>
<form action="insert.php" method="post">
<p>
<label for="Name">Full Name:</label>
<input type="text" name="full_name" id="Name">
</p>
<p>
<label for="Code">Code:</label>
<input type="text" name="code" id="Code">
</p>
<p>
<label for="GPA">GPA:</label>
<input type="text" name="gpa" id="GPA">
</p>
<input type="submit" name="submit" value="submit">
</form>
</body>
</html>
The problem is the input name. You named Full Name input with name="Name", but you declare $full_name = filter_input(INPUT_POST, 'full_name'); in php section. you must change full_name to Name. As well as the Code and GPA input.

MYSQL database not showing inserted data from HTML form

I am fairly new to PHP and I was following a simple tutorial on youtube, I followed the youtube video, double and tripple checked to make sure everything I typed was correct and data was still not being inserted.
I searched the internet for hours and I came up with a fix, sort of but I don't think it's the correct way to do it
HTML
<html>
<head>
<title>Insert Form Data In MYSQL Database Using PHP</title>
</head>
<body>
<form action="insert.php" method="post">
Name : <input type="text" name="username">
<br/>
Email : <input type="text" name="email">
<br/>
<input type="submit" value="Insert">
</form>
</body>
</html>
PHP
<?php
$con = mysqli_connect('localhost','root','');
if (!$con) {
echo 'Not Connected To Server';
}
if (!mysqli_select_db($con,'tutorial')) {
echo 'Database Not Selected';
}
if (isset($_POST['username'])){
$Name = $_POST['username'];
}
if (isset($_POST['email'])){
$Email = $_POST['email'];
}
$sql = "INSERT INTO person (Name, Email) VALUES ('John', 'john#gmail.com')";
if (!mysqli_query($con,$sql)) {
echo 'Not Inserted';
} else {
echo 'Inserted Successfully!';
}
header("refresh:10; url=index.html");
?>
I replaced '$Name' and '$Email' with John and john#gmail.com, then I type it into the html form and the data goes into the database correctly.
I then found another HTML form online with more PHP but it does the same thing(not inserting any data to the database)
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Record Form</title>
</head>
<body>
<form action="insert1.php" method="post">
<p>
<label for="firstName">First Name:</label>
<input type="text" name="firstname" id="firstName">
</p>
<p>
<label for="lastName">Last Name:</label>
<input type="text" name="lastname" id="lastName">
</p>
<p>
<label for="emailAddress">Email Address:</label>
<input type="text" name="email" id="emailAddress">
</p>
<input type="submit" value="Submit">
</form>
</body>
</html>
PHP
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $_POST['firstname']);
$last_name = mysqli_real_escape_string($link, $_POST['lastname']);
$email_address = mysqli_real_escape_string($link, $_POST['email']);
// attempt insert query execution
$sql = "INSERT INTO persons (first_name, last_name, email_address) VALUES ('$first_name', '$last_name', '$email_address')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>
The fields are blank, any help will be greatly appreacited!
Btw This is how the fields display I'm using xampp server.
I had used the below code and it works fine for me.
<?php
$link = mysqli_connect("localhost", "root", "", "dummy");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
/* Collect below values from $_POST
$firstname = 'John';
$lastname = 'Doe';
$email = 'test#gmail.com';
*/
// Escape user inputs for security
$first_name = mysqli_real_escape_string($link, $firstname);
$last_name = mysqli_real_escape_string($link, $lastname);
$email_address = mysqli_real_escape_string($link, $email);
// attempt insert query execution
$sql = "INSERT INTO accounts (account_firstname, account_lastname, account_email) VALUES ('$first_name', '$last_name', '$email_address')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
?>

Form Redirect after Submit to PHP mySQL db

I need to redirect submissions so that users aren't taken to a blank screen.
Here's the code for my form::
<form action="giveaway_execute.php" method="post">
First Name:
<input type="text" name="firstname" /><br />
Last Name:
<input type="text" name="lastname" /><br />
etc...
...
...
<p><input type="submit" value="Submit"/>
</p>
</form>
and here's the php for 'giveaway_execute.php' which interacts with the mySQL db (everything submits; removed password and db name for security)::
<?php
define ( 'DB_NAME','xxxx');
define ( 'DB_USER','xxxx');
define ( 'DB_PASSWORD','xxxx');
define ( 'DB_HOST','localhost');
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!link) {
die('Could not connect: ' .mysql_error());
}
$db_selected = mysql_select_db(DB_NAME, $link);
if (!$db_selected) {
die('Can\'t use ' . DB_NAME . ': ' . mysql_error());
}
$value1 = $_POST['firstname'];
$value2 = $_POST['lastname'];
$value3 = $_POST['phone'];
$value4 = $_POST['street'];
$value5 = $_POST['city'];
$value6 = $_POST['state'];
$value7 = $_POST['zip'];
$value8 = $_POST['email'];
$value9 = $_POST['weddingdate'];
$sql = "INSERT INTO entrants (firstname, lastname, phone, street, city, state, zip, email, weddingdate) VALUES ('$value1', '$value2', '$value3', '$value4', '$value5', '$value6', '$value7', '$value8', '$value9')";
if (!mysql_query($sql)) {
die('Error: ' . mysql_error());
}
mysql_close();
?>
I've tried redirects on the PHP file but nothing is working. Any suggestions would be greatly appreciated.
Thank you.
You can just include another page after you're done with your database operations, or as suggested you can use a header call but be sure to use an absolute url.
Also worth noting your code is highly vulnerable to SQL injection, and it doesn't do any validation.
It's a good idea to use isset on your fields to avoid getting notices and SQL errors if fields aren't set.
Finally, it's recommended to use a library such as PDO or mysqli over the older mysql_* extension.
try
header('location:page2.php');
at the end of the file.
Replace page2.php with the actual page you want to send them to
// process.php
$db = new PDO('mysql:host=localhost;dbname=test', 'root', 'root');
if(isset($_POST['value'])){
error_log(print_r($_POST,1),0);
$db->query('INSERT INTO test (id, value) VALUES (NULL, "'.$_POST['value'].'")');
header('Location: http://google.com');
exit();
}
else {
echo "$_POST is not set.";
}
// form.php
<form action="process.php" method="post">
<input type="text" name="value">
<input type="submit" id="submit-btn" value="Submit">
</form>
Try something simpler and build from there. Also read this: http://www.php.net/manual/en/pdo.prepared-statements.php

Trying to write to a MySQL database with a PHP form

I'm trying to do a simple write to database with an HTML form, using PHP.
I've run the SQL query in the database and it works perfectly. However, using the form doesn't work. I'm not sure why. Any help? The user/pass/db name are all correct.
<?php
if(isset($_POST['submit']))
{
$con = mysql_connect("localhost","delives0_ideas","ideas");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("delives0_ideas", $con);
mysql_query("INSERT INTO data (firstName, lastName, email, idea) VALUES ('$_POST['firstName']','$_POST['lastName']', '$_POST['email']', '$_POST['idea']')");
//also email it to us besides writing it into the database
mysql_close($con);
?>
<form method="post">
<strong>First name:</strong> <input type="text" name="firstName"/>
<br/>
<strong>Last name:</strong> <input type="text" name="lastName"/>
<br/>
<strong>Email:</strong> <input type="text" name="email"/> #####Put a javascript checker for valid emails, like name#site.com format
<br/>
<br/>
<strong>Idea:</strong>
<br/>
<textarea rows="10" cols="30" name="idea">
Hit us with your best shot.
</textarea>
<br/>
<input name="submit" type="submit" value="Submit"/>
</form>
You forgot the "action = nameofyourpage.php" inside the form markup. And I would add a "or die (mysql_error())" at the end of your query to check the syntax of the request.
you've got a few errors in your script - please check the following
http://pastie.org/1056569
<?php
if(isset($_POST['submit']))
{
$con = mysql_connect("localhost","delives0_ideas","ideas");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("delives0_ideas", $con);
$sqlCmd = sprintf("INSERT INTO data (firstName, lastName, email, idea)
VALUES ('%s','%s','%s','%s')",
mysql_real_escape_string($_POST["firstName"]),
mysql_real_escape_string($_POST["lastName"]),
mysql_real_escape_string($_POST["email"]),
mysql_real_escape_string($_POST["idea"]));
mysql_query($sqlCmd);
mysql_close($con);
}
?>
<form method="post">
<strong>First name:</strong> <input type="text" name="firstName"/><br/>
<strong>Last name:</strong> <input type="text" name="lastName"/><br/>
<strong>Email:</strong> <input type="text" name="email"/>
<strong>Idea:</strong><br/>
<textarea rows="10" cols="30" name="idea">Hit us with your best shot.</textarea><br/>
<input name="submit" type="submit" value="Submit"/>
</form>
You already have the answer to your question as to why it was not working, but please check this article about SQL injection attacks before putting this code into production.
you have error
mysql_query("INSERT INTO data (firstName, lastName, email, idea) VALUES
('$_POST['firstName']','$_POST['lastName']', '$_POST['email']', '$_POST['idea']')");
Error = '$_POST['firstName']' you have chatter ' in post field
and you can change
$firstname = $_POST['firstName'];
$lastname = $_POST['lastName'];
$email = $_POST['email'];
$idea = $_POST['idea'];
mysql_query("INSERT INTO data (firstName, lastName, email, idea) VALUES ('{$firstname}','{$lastname}', '{$email}', '{$idea}')");
or with mysql query
mysql_query("INSERT INTO data SET firstName='{$firstname}', lastName='{$lastname}',
email='{$email}', idea='{$idea}'");

Categories