I made a form to insert and modify categories in my project.
when i hit "submit" i get the record submitted into the database but it appears empty !
and if i go to the databse field and write the text myself it will appear good in MySQL and and "????" in the browser !
here is the code i wrote:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<?php
$con = mysql_connect("localhost","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb", $con);
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
('$_POST[name]','$_POST[parent_id]','$_POST[description]')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
<form action="ins.php" method="post">
category: <input type="text" name="name" /><br><br>
parent: <input type="text" name="parent_id" /><br><br>
description: <input type="text" name="description" /><br><br>
<input type="submit" />
</form>
</body>
</html>
You have to quote (using ") around your index name in your SQL request because $_POST is an array:
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
('".$_POST["name"]."','".$_POST["parent_id"]."','".$_POST["description"]."')";
But generally speaking please dont trust directly what's user are posting to your script to avoid SQL Injections. You can use mysqli::query which is way better and safer :
Mysqli
First sanitize your user input.
If you after that want to use the values from the array without all the concatenation everyone else mentions use {} around array accessors.
$sql="INSERT INTO categories (name, parent_id, description)
VALUES
('{$_POST['name']}','{$_POST['parent_id']}','{$_POST['description']}')";
To clean for example $_POST do something like this is a good start. This is a bit of my older code. As others have written use mysqli instead
function clean_array($t_array)
{
foreach($t_array as $key=>$value)
$array[$key] = mysql_real_escape_string( trim($value) );
return $t_array;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<body>
<?php
if ($_POST['action']=="doformpost") {
//only do DB insert if form is actually posted
$con = mysql_connect("localhost","user","pass");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb", $con);
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
('".$_POST['name']."','".$_POST['parent_id']."','".$_POST['description']."')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
}
?>
<form action="ins.php" method="post">
<input type="hidden" name="action" id="action" value="doformpost" />
category: <input type="text" name="name" /><br><br>
parent: <input type="text" name="parent_id" /><br><br>
description: <input type="text" name="description" /><br><br>
<input type="submit" />
</form>
</body>
</html>
Try using double quotes in your statement like this:
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
("'.$_POST['name'].'","'.$_POST['parent_id'].'","'.$_POST['description'].'")";
lots of issues here.
$_POST[name] should be $_POST['name']
your query will run even if the form is not submitted.
you are using deprecated mysql_* functions. Use PDO or mysqli
Your code is vulnerable to sql injection
With all that out, here's what you need to do.
Just to verify that the form is submitted, use
if( !empty($_POST['name']) &&
!empty($_POST['parent_id']) &&
!empty($_POST['description']) )
(use isset if empty value is allowed.)
Then run the query.
In PDO, the code will look like this ->
<?php
// configuration
$dbtype = "mysql";
$dbhost = "localhost";
$dbname = "mydb";
$dbuser = "user";
$dbpass = "pass";
// database connection
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
// query
$sql = "INSERT INTO categories (name, parent_id,description)
VALUES
(?,?,?)";
$q = $conn->prepare($sql);
$q->execute(array($_POST[name],$_POST[parent_id],$_POST[description]));
?>
This is just a start. you can use try and catch block to catch exceptions.
Before running query, check if form is submitted by !empty() or isset() as described above.
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
("'.$_POST['name'].'","'.$_POST['parent_id'].'","'.$_POST['description'].'")";
Please provide quotes while inserting values in database
I found that if you forget the simply html attribute in the <form> for METHOD="POST"... you will get blank data in your database despite all else working fine.
ie.. <form action="file.php" method=POST>
use this statement for your code
if( isset($_POST['name']) && isset($_POST['parent_id']) && isset($_POST['description']) )
//your insert query
Don't forgot about safety!
$sql="INSERT INTO categories (name, parent_id,description)
VALUES
('".mysql_real_escape_string($_POST['name'])."','".intval($_POST['parent_id'])."','".mysql_real_escape_string($_POST['description'])."')";
And i think a problem with encodings.
launch query before you inserting a data:
$sql = 'set names `utf-8`'; (for example)
Use Below insert query to insert data , i m sure it will definitely help you.
$sql="INSERT INTO categories (name,parent_id,description)
VALUES
('".$_POST['name']."','".$_POST['parent_id']."','".$_POST['description']."')";
Try this
<?php
if(isset($_POST['submit'])) {
$con = mysql_connect("localhost","user","pass");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("mydb", $con);
$sql="INSERT INTO categories (name, parent_id,description) VALUES
('".$_POST['name']."','".$_POST['parent_id']."','".$_POST['description']."')";
if (!mysql_query($sql,$con)) {
die('Error: ' . mysql_error());
} else {
echo "1 record added";
}
mysql_close($con);
}
?>
<html>
<body>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="post">
category: <input type="text" name="name" /><br><br>
parent: <input type="text" name="parent_id" /><br><br>
description: <input type="text" name="description" /><br><br>
<input type="submit"name="submit" value="Submit" />
</form>
</body>
</html>
Me too faced the same problem.
Proceed your insert query like this, this helped me.
$email_id = $_POST['email_id'];
$device_id = $_POST['device_id'];
***For My Sqli***
if(!empty($email_id ))
{
$result_insert = mysqli_query($db_conn,"INSERT INTO tableName (user_email, user_device_id,last_updated_by) VALUES('".$email_id."', '".$device_id."', '".$email_id."') ");
if(mysqli_affected_rows($db_conn)>0)
{
$response["success"] = 1;
$response["message"] = "Successfully Inserted";
}
else
{
$response["success"] = 0;
$response["message"] = "Problem in Inserting";
}
}
else
{
$response["success"] = 4;
$response["message"] = "Email id cannot be Blank";
}
}
///////////////////////////////////////////////////////////////////////////////
**For My Sql**
if(!empty($email_id ))
{
$result_insert = mysql_query("INSERT INTO tableName (user_email, user_device_id,last_updated_by) VALUES('".$email_id."', '".$device_id."', '".$email_id."') ");
if(mysql_affected_rows()>0)
{
$response["success"] = 1;
$response["message"] = "Successfully Inserted";
}
else
{
$response["success"] = 0;
$response["message"] = "Problem in Inserting";
}
}
else
{
$response["success"] = 4;
$response["message"] = "Email id cannot be Blank";
}
}
NOTE : here i have checked only for email.
Related
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);
?>
I have a user input form(HTML) that is supposed to take the information and insert it into a MySQL database via PHP. The PHP apparently executes and echoes "Your registration has completed successfully". A record is created in the database but the columns are blank(I have removed my server, database, and password from the PHP code).
HTML:
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="css/styles.css">
<title>User Portal</title>
</head>
<div class="inputContainer">
<header>
User Information Portal
</header>
<form action="php/userPost.php" method="post">
<label for=firstName">First Name</label>
<input type="text" id=firstName" name="fname">
<br><br>
<label for="lastName">Last Name</label>
<input type="text" id="lastName" name="lname">
<br><br>
<label for="eMail">Email</label>
<input type="text" id="eMail" name="email">
<br><br>
<label class="labelRole" for="userRole">Role -</label><br>
<input type="radio" id="userRole" name="role" value="Instructor"> Instructor
<input class="submitButton" type="submit" name="submit" value="Register">
</form>
</div>
</body>
PHP:
<?php
$sname = "server-name";
$uname = "username";
$pword = "password";
$dbname = "web_tech_test";
$conn = new mysqli($sname, $uname, $pword, $dbname);
if ($conn->connect_error) {
die("Connection failure: " . $conn->connect_error);
}
$fname = !empty($_POST['firstName']);
$lname = !empty($_POST['lastName']);
$email = !empty($_POST['eMail']);
$role = isset($_POST['userRole']);
$sql = "INSERT INTO users (first_name, last_name, email, role)
VALUES ('$fname', '$lname', '$email', '$role')";
if ($conn->query($sql) === TRUE) {
echo "Your registration has completed successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
This creates a new record in the DB but all the columns are blank. Any ideas why this may be happening?
$fname = !empty($_POST['firstName']);
$lname = !empty($_POST['lastName']);
$email = !empty($_POST['eMail']);
$role = isset($_POST['userRole']);
this code returns a boolean, not a string value...
Use !empty() just for validation
example
if(empty($_POST['eMail'])) {
die("Email cannot be empty");
}
You're confusing the id and the name tags on the inputs.
The name tags are the ones which will be submitted as keys to your server.
Try this in your server php script after submitting your form to see which key/values are actually received by the server:
var_dump($_POST);
Also, if you want to check that all fields have been filled out, use something similar as this:
if (empty($_POST['firstName'])) {
die("firstname is empty!");
}
In your current example you're actually saving a boolean to your variables.
And, last but not least, never insert variables from a potentially unsafe source (like a user input) directly into your SQL. Use pdo: http://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developers for this
Full code example to get you started:
//prepare your values
if (empty($_POST['fname']) || empty($_POST['lname']|| empty($_POST['email']|| !isset($_POST['role'])) {
die ("some values were empty or not set");
}
//prepare your database
$db = new PDO('mysql:host=server-name;dbname=web_tech_test;charset=utf8mb4', 'username', 'password');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //throw an exception if there is an error
//create your query
$stmt = $db->prepare("INSERT INTO users (first_name, last_name, email, role) VALUES (:first_name,:last_name,:email,:role)"); //create a query statement
$stmt->bindValue(":first_name", $firstName); //put your values into your statement
$stmt->bindValue(":last_name", $lastName);
$stmt->bindValue(":email", $email);
$stmt->bindValue(":role", $role);
if ($stmt->execute()) { //execute the query
echo "Your registration has completed successfully";
} else {
echo "Error :(";
}
I have managed to connect to database and I manage to insert using following code.
<?php
$username = 'root';
$password = '';
$db = 'demo';
$conn = new mysqli ('localhost',$username, $password, $db) or die("unable to connect");
$sql="insert into persons (first_name,last_name,email_address) values ('sara','smith','email#email.com')";
$query=mysqli_query($conn,$sql);
if($query)
echo 'data inserted';
?>
But the problem is that when I try to enter data using HTML form, it didn't work for me. I have tried to follow different tutorials and different answers here on stackoverflow. Can anyone please tell me the easiest way of inserting and getting data from MySQL using PHP ?
If there is any easy tutorial or blog from where i can learn and understand all this, I would love to watch or read.
I manage to do it in following way.
Create a file name index.php with following code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Add Record Form</title>
</head>
<body>
<form action="insert.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>
Then create another file name as insert.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);
?>
//procedural style
$mysqli = mysqli_connect('host','username','password','database_name');
//Output any connection error
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//inserting a record
$product_code = '"'.$mysqli->real_escape_string('P1234').'"';
$product_name = '"'.$mysqli->real_escape_string('42 inch TV').'"';
$product_price = '"'.$mysqli->real_escape_string('600').'"';
//MySqli Insert Query
$insert_row = $mysqli->query("INSERT INTO products (product_code, product_name, price) VALUES($product_code, $product_name, $product_price)");
if($insert_row){
print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />';
}else{
die('Error : ('. $mysqli->errno .') '. $mysqli->error);
}
A quick and untested example of using an HTML form with the POST method to insert data entered by a user into the db.
<?php
$result = false;
$dbhost = 'localhost';
$username = 'root';
$password = '';
$db = 'demo';
if( $_SERVER['REQUEST_METHOD']=='POST' ){
$conn = new mysqli ( $dbhost,$username, $password, $db );
if( $conn ){
$sql='insert into `persons` ( `first_name`,`last_name`,`email_address` ) values (?,?,?);';
$stmt=$conn->prepare( $sql );
$stmt->bind_param('sss', $_POST['firstname'], $_POST['lastname'], $_POST['email'] );
$result = $stmt->execute();
}
$conn->close();
}
?>
<!doctype html>
<html>
<head>
<title>Simple Form submission example</title>
</head>
<body>
<form method='post'>
<input type='text' name='firstname' />
<input type='text' name='lastname' />
<input type='text' name='email' />
<input type='submit' value='Submit' />
<?php
echo $result ? '<div>The database was updated</div>' : '';
?>
</form>
</body>
</html>
Try tutsplus or lynda, Provide you with the best tuto !
I've done a php script that will create a title and a text and load it to my database(mysql). When i press submit the script runs and create 1 row right and then like 3-5 empty rows.
The same thing happens when i refresh the page(empty form), 2 new empty rows shows in my database?
How do i solve it?
<?php
$con=mysqli_connect("xxx");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$rubrik = mysqli_real_escape_string($con, $_POST['rubrik']);
$editor = mysqli_real_escape_string($con, $_POST['editor1']);
$date = date("Yyyy-mm-dd");
$sql="INSERT INTO News (title, full_content, author, date_added) VALUES ('$rubrik', '$editor', 'admin', '2014-09-18')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
<form method="post" onSubmit=window.location="index.php">
Rubrik: <br/><input type="text" name="rubrik"><br/>
Nyhetstext:<br/> <textarea class="ckeditor" cols="80" id="editor1" name="editor1" rows="10">
</textarea><br/>
<input type="submit" value="Publicera nyhet">
</form>
Your INSERT query is executing every time when page loads, set a POST variable to check whether the form has been submitted or not and why you are using event attribute window.location for submitting form, you can simply use action attribute and set that value either blank or the file name where you want to send your data.
<form action="" method="post">
OR
<form action="index.php" method="post">
Your date variable is also wrong. To generate date into YYYY-MM-DD format write like below
$date = date('Y-m-d');
Your script may like this
if(isset($_POST['submit'])) {
your post variables and insert query goes here
}
You can also insert a hidden input field into your form tag like so
<form action="" method="post">
<input type="hidden" name="save" value="details">
other HTML code goes here
</form>
in that case you test the post variable like this
if(isset($_POST['save']) && $_POST['save'] === "details") {
your post variables and insert query goes here
}
First learn the basic concept about PHP from http://www.php.net/ and search for appropriate question over here before asking any question.
Wrap your php code around condition to check if the form is submitted or not. Like:
<?php
if(isset($_POST['submit')){
$con=mysqli_connect("xxx");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$rubrik = mysqli_real_escape_string($con, $_POST['rubrik']);
$editor = mysqli_real_escape_string($con, $_POST['editor1']);
$date = date("Yyyy-mm-dd");
$sql="INSERT INTO News (title, full_content, author, date_added) VALUES ('$rubrik', '$editor', 'admin', '2014-09-18')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}
?>
Always catch form submission. You can use isset() with this:
<?php
$con = mysqli_connect("xxx");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])){
// escape variables for security
$rubrik = mysqli_real_escape_string($con, $_POST['rubrik']);
$editor = mysqli_real_escape_string($con, $_POST['editor1']);
$date = date("Y-m-d"); // put the correct format on the date
$sql="INSERT INTO News (title, full_content, author, date_added) VALUES ('$rubrik', '$editor', 'admin', '$date')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
header('Location: index.php'); // always redirect
}
?>
<form method="post" action="">
Rubrik: <br/><input type="text" name="rubrik"><br/>
Nyhetstext:<br/><textarea class="ckeditor" cols="80" id="editor1" name="editor1" rows="10"></textarea><br/>
<input type="submit" name="submit" value="Publicera nyhet" />
<!-- ^^ add a name -->
</form>
You should check if $_SERVER['REQUEST_METHOD'] is POST and only then run the INSERT statement.
<?php
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$con=mysqli_connect("xxx");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$rubrik = mysqli_real_escape_string($con, $_POST['rubrik']);
$editor = mysqli_real_escape_string($con, $_POST['editor1']);
$date = date("Yyyy-mm-dd");
$sql="INSERT INTO News (title, full_content, author, date_added) VALUES ('$rubrik', '$editor', 'admin', '2014-09-18')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
}
?>
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();
}
?>