Trouble inserting into a sql table from a form [duplicate] - php

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

Related

Why this simple registration is not working [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I am a beginner in PHP. And decided to make a fully working model of a registration form. But when I program it, it doesn't work.
Here is the main HTML code
<html>
<form method="POST">
<input required type="text" name="name" placeholder="Your Name"><br>
<input required type="email" name="email" placeholder="Your Email"><br>
<input required type="password" name="pass" placeholder="Your Password"><br>
<button name="submit" type="submit" value="Submit">Submit</button>
</form>
</html>
Here is the PHP code
<?php
$conn = mysqli_connect("localhost", "root", "", "shayeq");
if (isset($_POST['submit'])) {
# code...
$user = $_POST['name'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$sql = "INSERT INTO 'user'(name, email, password) VALUE ('$user', '$email', '$pass')"
}
You have to run sql command.
$sql = "INSERT INTO user (name, email, password) VALUES ('$user', '$email', '$pass')";
$result = mysqli_query($sql);

Why does my user registration form not work properly?

I am trying to create a user registration form using php and mysql. When I try to hit the submit button no new record is added to my database. The database is functional and has worked with other forms.
HTML/FORM
<?php
include 'header.php';
?>
<section>
<div class="form">
<form action="signup.php" method="post">
<h1> Sign Up!</h1>
<p>First name:
<input type="text" name="fName" maxlength="15" required pattern="^[a-zA-Z]{3,20}$" placeholder="Enter Name" />
</p>
<p>Last name:
<input type="text" name="lName" maxlength="15" pattern="^[a-zA-Z]{3,20}$" required placeholder="Enter Last Name" />
</p>
<p>Email:
<input type="email" name="email" maxlength="40" required placeholder="Enter Email" />
</p>
<p>Username:
<input type="text" name="username" maxlength="20" ^[A-Za-z0-9_]{1,15}$ required placeholder="Enter Username" />
</p>
<p>Password:
<input type="password" name="password" maxlength="20" pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[A-Z])(?=.*[a-z]).*$" required placeholder="Enter Password" />
</p>
<p>Re-type Password:
<input type="password" name="password2" maxlength="20" pattern="^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?!.*\s).*$" required placeholder="Re-type Password" />
</p>
<p>
<button type="submit" name="signupbutton"> Sign up </button>
</p>
</form>
</div>
</section>
<div class="footerspecial">
<?php
include 'footer.php';
?>
</div>
PHP/SQL
<?php
//have they submitted at least once?
if(isset($POST['$password2'])){
$fName = $_POST['fName'];
$lName = $_POST['lName'];
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$password2 = $_POST['password2'];
//do the passwords NOT match?
if ($password !== $password2) {//do string comparison here
echo'<h2>Error: passwrods don\'t match!</h2>';
require ('registerform.php');
}
else {
//does the username already exist?
$sql = mysql_query("SELECT * FROM users WHERE username=='$username'");
if ($results=$con->query($sql)){
echo'<h2>Error: username is already taken</h2>';
require ('registerform.php');
}
else {
$sql = mysql_query("SELECT * FROM users WHERE email=='$email'");
if ($results=$con->query($sql)){
echo'<h2>Error: email already used</h2>';
require ('registerform.php');
}
else {
// If the values are posted, insert them into the database.
$sql= "INSERT INTO users (fName, lName, email, username, password, password2) VALUES ('$fName', '$lName', '$email', '$username', '$password', $password2)";
if (!$con->query($sql)){
echo 'Error: coulndt do suff';
}
else {
echo 'Account made';
}//ENDS SUCCESSFUL INSURT
}//ENDS EMAIL VALIDATION
}//ENDS THE USERNAME VALIDATION
}//END PASSWORD VALIDATION
}
?>
Picture of the form don't really know if its helpful but ya'know
https://gyazo.com/418b86ecb5090604a1f229e1e94fe3bf
I'm guessing here that your database doesn't have a password2 column (seems kind of pointless to have) so trying to insert into it will give an error.
You should read about MySQLi error reporting
Also add error_reporting(-1); at the start of your PHP file to show PHP errors.
P.S. your code is vulnerable to SQL injection, you should use prepared statements to be safe from this.
Could have multiple problems first you do not have the single quotes around $password2. This could be leading to a failed insert.
VALUES ('$fName', '$lName', '$email', '$username', '$password', $password2)";
Also I would echo the sql errors out as you are not doing. you can do this easily. Test the if statement for a true not a false
if ($con->query($sql)){
//if true then runs your code;
}
else {
echo "Error: " . $sql . "<br>" . $con->error; // This will echo out any sql errors you may have
}

PHP - Insert into database issue

I am trying to input data into a database.
i have used echo to see if the database is being read, it is and the database echo's as entered, it just does not insert into the database. This is the same code i used for the registration page, apart from a new amendments, and my reg page works perfectly so i am a little confused to why it is not working.
HTML
<!-- <div id="first">-->
<input type="text" id="fname" name="fname" value="" required>
<input type="text" id="lname" name="lname" value="" required>
<input type="text" id="email" name="email" value="" required>
<input type="number" id="phone" name="phone" value="" required>
<input type="submit" name="Update" value="Update">
<br>
PHP
<?php
session_start();
require('../mysql.inc.php');
?>
<?php
if (isset($_POST['Update'])) {
echo $c_fname = $_POST['fname'];
echo $c_lname = $_POST['lname'];
echo $c_email = $_POST['email'];
echo $c_phone = $_POST['phone'];
$insert_det = "INSERT INTO Cus_acc_details(CUS_Fname,CUS_Lname,CUS_Phone,Cus_Email) VALUES (?,?,?,?)";
$stmt = mysqli_prepare($dbc, $insert_det);
mysqli_stmt_bind_param($stmt, 'sssi', $c_fname, $c_lname, $c_email, $c_phone);
if ($insert_det) {
echo " Saved";
}
} else {
echo "<b> Error </b>";
}
?>
Any suggestions
The call to mysqli_stmt_execute() is missing, thus your statement will never be executed.
Try changing your insert query to
$insert_det = "INSERT INTO Cus_acc_details(CUS_Fname,CUS_Lname,Cus_Email,CUS_Phone) VALUES (?,?,?,?)";
$stmt = mysqli_prepare($dbc, $insert_det);
As you are mixing them up when declaring them on the placeholders and are casting email as a integer but trying to insert the phone number as the email and vice versa

Having problems switching over to mySQLi

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

PHP does not work INSERT INTO method

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.

Categories