I'm trying to do a simple HTML form that sends data to DB:
Form:
<form action="processor.php" method="post">
<div class="field-box">
<label>Name:</label>
<input type="text" name="name" />
</div>
<div class="field-box">
<label>Age:</label>
<input type="text" />
</div>
<div class="field-box">
<label>Phone Number:</label>
<input type="text" name="email" />
</div>
<div class="field-box">
<label>Email:</label>
<input type="text" name="username"/>
<input type="submit">
</form>
And the SQL to send the data on processor.php:
//Connecting to sql db.
$connect = mysqli_connect("XXXXXXX","XXXXXXX","XXXXXXX","XXXXXX");
//Sending form data to sql db.
mysqli_query($connect,"INSERT INTO users (name, age, phone, email) VALUES ('$_POST['name']','$_POST['age']', '$_POST['phone']', '$_POST['email']')";
mysqli_close($connect);
I don't get error messages it just takes me to a blank page and no records are inserted into database.
The input for age lacks a name .
<div class="field-box">
<label>Age:</label>
<input type="text" name="age" />
</div>
And also do not insert directly a $_POST data. It would be best if you use mysqli_real_escape_string for added security. Your insert query as well lacks a closing parenthesis
//Connecting to sql db.
$connect = mysqli_connect("XXXXXXX","XXXXXXX","XXXXXXX","XXXXXX");
//Sending form data to sql db.
$name = mysqli_real_escape_string($connect, $_POST['name']);
$age = mysqli_real_escape_string($connect, $_POST['age']);
$phone = mysqli_real_escape_string($connect, $_POST['phone']);
$email = mysqli_real_escape_string($connect, $_POST['email']);
mysqli_query($connect,"INSERT INTO users (name, age, phone, email) VALUES ('$name', '$age', '$phone', '$email')");
There seems a problem with your query: A modified one looks like
mysqli_query($connect,"INSERT INTO users (name, age, phone, email)
VALUES ('".$_POST['name']."','".$_POST['age']."', '".$_POST['phone']."', '".$_POST['email']."')";
Directly inserting values without validations is not a good practice.
Use mysqli_real_escape_string before your entries towards database
Related
I'm trying to add revived form input into database.
<form action="index.php" method="post">
<input type="text" name="firstname" id="firstname">
<br>
<input type="text" name="lastname" id="lastname">
<br>
<input type="submit" name="submit" value="Submit">
if(isset($_POST['submit'])) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$query = "INSERT INTO users (firstname, lastname) VALUES ($firstname, $lastname)";
if($conn->query($query) === true) {
echo "added";
}else {
echo $con->error;
}
Example : Firstname = Jason / Lastname = Haw
After clicking on submit button, i see error message : Unknown column 'Jason' in 'field list'
Where is the wrong thing to do?
$query = "INSERT INTO users (firstname, lastname) VALUES ('$firstname', '$lastname')";
put single quote for $firstname.
but this is not a proper approach, you should use prepared statement.
your query is risk of sql injection, because no escaping the input.
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
How to construct an SQL query correctly in a PHP script? [duplicate]
Closed 5 years ago.
The expect result is for the data that is submitted through a HTML form, and then the form action is this code below. Proccessing the code below I was expecting it to insert the data from the form into a SQL table called customers. However the data is not being inserted and there is no errors showing on the page.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$uName = $_POST['uname'];
$password = sha1($_POST['upassword']);
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$dob = $_POST['dob'];
$address1 = $_POST['address1'];
$address2 = $_POST['address2'];
$postcode = $_POST['postcode'];
echo $uName;
echo $password;
include("dbconn.php");
$sql = "INSERT INTO customers (username, password_hash, customer_foremane, customer_surname, date_of_birth, customer_address1, customer_address2, customer_postcode) VALUES ('$uName', '$password', '$fname', '$lname', '$dob', '$address1', '$address2', '$postcode')";
mysqli_query($conn, $sql);
mysqli_close($conn);
?>
This is the form in which the data is from:
<div id = "reg_form">
<form name="register" action="register_customer.php" method="post">
<p id = "form_text"> Username: </p> <input name="uname" type="text" placeholder="Please enter a user name">
<p id = "form_text"> Password: </p> <input name="upassword" type="password" placeholder="Please enter a password"><br>
<p id = "form_text"> First Name: </p> <input name="fname" type="text" placeholder="Please enter your first name"><br>
<p id = "form_text"> Last Name: </p> <input name="lname" type="text" placeholder="Please enter your last name"><br>
<p id = "form_text"> Date of Birth: </p> <input name="dob" type="text" placeholder="Please enter your date of birth"><br>
<p id = "form_text"> Address 1: </p> <input name="address1" type="text" placeholder="Please enter first line of address"><br>
<p id = "form_text"> Address 2: </p> <input name="address2" type="text" placeholder="Please enter second line of address"><br>
<p id = "form_text"> Postcode: </p> <input name="postcode" type="text" placeholder="Please enter your postcode"><br>
<input name="submit" type="submit">
</form>
</div>
This is the dbconn.php:
<?php
$config = parse_ini_file('config.ini');
$conn = mysqli_connect('localhost',$config['username'],
$config['password'],$config['dbname']);
echo "Connected to the database";
?>
you have to use MySqli Prepared Statements for Inserting the query to make it more secure like below:
// prepare and bind Customers Query
$queryCustomers = $conn->prepare("INSERT INTO customers(username, password_hash, customer_foremane, customer_surname, date_of_birth, customer_address1, customer_address2, customer_postcode) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$queryCustomers->bind_param("ssssssss",$uName,$password,$fname,$lname,$dob,$address1,$address2,$postcode);
// execute Customers Query
$queryCustomers->execute();
// Close Connections
$queryCustomers->close();
To learn more, follow http://php.net/manual/en/mysqli.quickstart.prepared-statements.php
I'm new to PHP I have put together a simple form to input data into a database but the data doesn't seem to be inserting into the database. I've been trying to get it working all day.
shows the error Error to Inserting into database at the end of the code.
html
<div id="wrapper">
<section id="top_area">
<article class="box-right">
<form action="script/data.php" method="post">
<p>
<label>Company Name:</label>
<input name="company_name" required="required" placeholder="Joes Cleaners" type="text">
</p>
<p>
<label>Ref:</label>
<input name="ref_num" required="required" placeholder="D123" type="text">
</p>
<p>
<label>Website:</label>
<input name="website" required="required" placeholder="joescleaner.co.uk" type="text">
</p>
<p>
<label>Email:</label>
<input name="email" required="required" placeholder="joescleanersm#gmail.com" type="email">
</p>
<p>
<label>Telephone:</label>
<input name="tel" required="required" placeholder="0712345678" type="number">
</p>
<p>
<label>Message:</label>
<input name="message" required="required" placeholder="hello" type="text">
</p>
<p>
<input value="Submit" type="submit">
</p>
</form>
</article>
</section>
</div>
PHP
<?php
$db_hostname = 'localhost';
$db_database = 'form';
$db_username = 'user';
$db_password = 'password';
// Connect to server.
$db_server = mysql_connect($db_hostname, $db_username, $db_password)
or die("Unable to connect to MySQL: " . mysql_error());
// Select the database.
mysql_select_db($db_database)
or die("Unable to select database: " . mysql_error());
// Select the database.
mysql_select_db("form")
or die("Unable to select database: " . mysql_error());
// Get values from form
$company_name = $_POST['company_name'];
$ref_num = $_POST['ref_num'];
$website = $_POST['website'];
$email = $_POST['email'];
$tel = $_POST['tel'];
$message = $_POST['message'];
// Insert data into mysql
$sql="INSERT INTO users (company_name, ref_num, website, email, tel, message)
VALUES ('$company_name', '$ref_num', '$website', '$email', $tel, $message, NOW())";
$result = mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
header('Location: ../thankyou.php');
}
else {
echo "Error to Inserting into database";
}
// close mysql
mysql_close();
?>
You should start using PDO for DB access, mysql_query is deprecated.
PDO let's you make prepared statements. These are secured against SQL Injections (your code isn't).
$stmt = $dbh->prepare("INSERT INTO users (company_name, ref_num, website, email, tel, message) VALUES (:company_name, :ref_num, :website, :email, :tel, :message, NOW())");
$stmt->bindParam(':company_name', $company_name);
$stmt->bindParam(':ref_num', $ref_num);
// And bind the remaining parameters
[...]
$stmt->execute();
If this fails, you can get detailed informations by running
print_r($stmt->errorInfo());
That should help you with finding errors in your SQL.
$dbh is a new PDO instance (see PDO::__construct)
As in your query you are trying to insert more than column values.
Your query is :
$sql="INSERT INTO users (company_name, ref_num, website, email, tel, message) VALUES ('$company_name', '$ref_num', '$website', '$email', $tel, $message, NOW())"
Either remove NOW() data or add another column for NOW() data
Also you can try below query.
$sql="INSERT INTO users (company_name, ref_num, website, email, tel, message) VALUES ('$company_name', '$ref_num', '$website', '$email', $tel, $message)"
When fixed column errors like Programming Student says, you should modify your mysql_query command:
it needs the db connection you opened before.
Try this:
$result = mysql_query($db_server, $sql);
Why don't try Object Oriented syntax ?
if ($db_server->query($sql) === TRUE) {
header('Location: ../thankyou.php'); } else {
echo "Error: " . $conn->error;
}
}
I am trying to insert into customer table in eshop_db
When I run it, it does not have any error, but it did not store in mysql.
What it is problem in my code?
I don't understand really.
Please give some answer. Thanks.
--registerForm.php--
<form action="register.php" method="post">
<p>User ID: <input type="text" name="userId" size="30"/>*</p>
<p>Password: <input type="password" name="password" size="30"/>* </p>
<p>Retype Password: <input type="password" name="repassword" size="30"/>*</p>
<p>First Name: <input type="text" name="firstName" size="30"/>*</p>
<p>Last Name: <input type="text" name="lastName" size="30"/>*</p>
<p>Your Address (*):</p>
<p><textarea name="address" rows="5" cols="30"></textarea></p>
<p>Phone: <input type="text" name="phone" size="20"/>*</p>
<p>E-mail: <input type="text" name="email" size="21"/>*</p>
<p><input type="submit" value="Create Account"/></p>
</form>
--register.php--
<?php
require "sql_connection.php";
if(isset($_POST['submit']))
{
if($_POST["password"]==$_POST["repassword"])
{
mysql_query("insert into customer (userId, password, firstName, lastName, address, phone, email)
values ('$_POST[userId]','$_POST[password]','$_POST[firstName]','$_POST[lastName]','$_POST[addres]]','$_POST[phone]','$_POST[email]')")
or die(mysql_error());
}
}
?>
--sql_connection.php--
<?php
$db_host = "localhost";
$db_username = "root";
$db_pass = "mypass";
$db_name = "eshop_db";
#mysql_connect("$db_host", "$db_username", "$db_pass", "$db_name") or die("connection is fail.");
#mysql_select_db("$db_name") or die("database does not exsist.");
echo "Successfully connected!!";
?>
Typo, correct this part here:
'$_POST[addres]]' // wrong
'$_POST[address]' // right
Try this:
<?php
require "sql_connection.php";
if(isset($_POST['submit']) && $_POST["password"] == $_POST["repassword"]) {
mysql_query(
'INSERT INTO `customer` (`userId`, `password`, `firstName`, `lastName`, `address`, `phone`, `email`)
VALUES ('.$_POST['userId'].', '.$_POST['password'].', '.$_POST['firstName'].', '.$_POST['lastName'].', '.$_POST['address'].', '.$_POST['phone'].', '.$_POST['email'].')'
) or die(mysql_error());
}
Finally, filter and validate your incoming data.
Well, besides the obviously bad idea to directly use the values in the POST array, your indexes need to be quoted. So, $_POST['address'], etc. Also, array values need to be escaped with curly-braces if you're trying to do string injection.
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}'");