PHP Creating Form to insert data into Database - php

I'm creating a website as an activity and I'm not sure how to proceed. I have a database file (.db) that has Customer information (firstname, lastname, address, phone) and I'm wanting to create a form to input more data into those fields.
I've been given a function in a separate file called queryDb.php:
function addCustomer($fname, $lname, $address, $phone) {
$db = new MyDB();
if(!$db){
echo '<script type="text/javascript">alert("'.$db->lastErrorMsg().'");</script>';
} else {
//echo "Opened database successfully\n";
}
$sql ='INSERT INTO CUSTOMERS (FIRSTNAME, LASTNAME, ADDRESS, PHONE) VALUES ("'.$fname.'", "'.$lname.'", "'.$address.'", "'.$phone.'");';
$db->query($sql);
}
In my main php file I have this up the top:
<?php
require_once "queryDb.php";
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$address = $_POST["address"];
$phone = $_POST["phone"];
?>
and the form, I've only created it for two inputs, Address and phone to test it:
<form action="reviewsubmit.php" method="post">
Test Address
<input type="text" id="address" name="address" placeholder="test"> />
Test phone
<input type="text" id="phone" name="phone" placeholder="test"> />
<input type="submit" name="Submit" value="Submit" />
</form>
I'm not sure how I can call the function from the other file to use in this file. How can I do this?

Everything seems ok, call the function after this:
<?php
require_once "queryDb.php";
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$address = $_POST["address"];
$phone = $_POST["phone"];
addCustomer($firstname, $lastname, $address, $phone);

In your main php file, you should write the following:
if($_POST)
{
require_once "queryDb.php";
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$address = $_POST["address"];
$phone = $_POST["phone"];
$result = addCustomer($firstname, $lastname, $address, $phone);
//Some redirect here based on the result
}
Of course you need to make sure that your form's action (reviewsubmit.php) is correct (Your main php file must be reviewsubmit.php, otherwise change the action to be your desired file).
Also you must add firstname and lastname inputs to your form like the following:
Firstname
<input type="text" id="firstname" name="firstname" placeholder="Enter Firstname"> />
Lastname
<input type="text" id="firstname" name="firstname" placeholder="Enter Firstname"> />

you sould use two separate files, one with your form an the other with rour function. And make an ajax call to your function.

Related

Register Form PHP not inserting values into DB, just reloading the page

I really can not find what am I doing wrong in my registration form, unfortunately the page is just reloading instead of inserting values from form to my DB table.
Register.php
<?php
require_once("./Connection.php");
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$options = array("cost"=>5);
$hashPassword = password_hash($password,PASSWORD_BCRYPT,$options);
$sql = "insert into agents (firstName, lastName, email, phone, password) value ('".$firstName."', '".$lastName."', '".$email."','".$phone."','".$hashPassword."')";
$result = mysqli_query($conn, $sql);
if($result)
{
echo "Registration successfully";
}
}
?>
Connection.php
<?php
$conn = mysqli_connect("localhost","root","","KBHestate");
if(!$conn){
die("Connection error: " . mysqli_connect_error());
}
Register Form
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<input type="text" name="firstName" value="" placeholder="First Name">
<input type="text" name="lastName" value="" placeholder="Surname">
<input type="text" name="email" value="" placeholder="Email">
<input type="text" name="phone" value="" placeholder="Phone">
<input type="password" name="password" value="" placeholder="Password">
<button type="submit" name="submit">Submit</button>
</form>
Please make sure the following line has no problem when it is interpreted by the PHP:
$options = array("cost"=>5);
$hashPassword = password_hash($password,PASSWORD_BCRYPT,$options);
On the other hand, please make sure that the password field is wide enough to store the $hasPassword data
Your code looks fine, it should work. I am hoping you are having Register form in the same file Register.php
But as you mentioned it's just reload the page that means there must be a exception/error from mysql query that is not handled in your code.
You have not shared your table structure. So, I am answering you based on the common mistake.
Like one of your table column width is varchar(10) and you are trying to pass data of length 20 char.
So, i suggest you to add below code in your Register.php as the else condition for if($result). So, it will display the error if any.
else {
echo("Error description: " . $conn->error);
}
Now your Register.php code will be look like below:
<?php
require_once("./Connection.php");
if(isset($_POST['submit'])){
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$password = $_POST['password'];
$options = array("cost"=>5);
$hashPassword = password_hash($password,PASSWORD_BCRYPT,$options);
$sql = "insert into agents (firstName, lastName, email, phone, password) value ('".$firstName."', '".$lastName."', '".$email."','".$phone."','".$hashPassword."')";
$result = mysqli_query($conn, $sql);
if($result)
{
echo "Registration successfully";
}else {
echo("Error description: " . $conn->error);
}
}
?>

Save login form data using php

html webpage screenshotphp code shown on button clickmySql database tableI need to store user login data. i am using phpMyAdmin. When I click on submit button, data is not stored. Instead the php code is shown. Both code files are given below. What I am doing wrong. Help me. I
am unable to store user data using phpmyadmin in xampp.
my html code
<html>
<head>
<title>Yahoo Signin And Signup Form</title>
</head>
<body>
<h2 style="color: midnightblue">yahoo!</h2>
<hr color="magenta">
<form method="post" action="connect.php" >
<fieldset style="background:#6495ED;">
<legend style="padding:20px 0; font-size:20px;">Signup:</legend>
<label for ="firstName">Enter First Name</label><br>
<input type="text" placeholder="First name" id="firstName" name ="firstName">
<br>
<label for ="lastName">Enter Last Name</label><br>
<input type="text" placeholder="Last name" id="lastName" name ="lastName">
<br>
<label for ="email">Enter Email</label><br>
<input type="text" placeholder="Email" id="email" name ="email"><br>
<label for ="password">Enter Password</label><br>
<input type="password" placeholder="Password" id="password" name ="password">
<br>
<label for ="number">Enter Mobile Number</label><br>
<input placeholder="03---" id="number" name ="number"><br>
<label for ="date">Enter Date of Birth</label><br>
<input type="text" placeholder="DD/MM/YY" id="date" name ="date"><br>
<label for ="gender">Enter Gender</label><br>
<input type="text" placeholder="Male/Female/Other" id="gender" name
="gender"><br>
<br><button style="background-color:orangered;border-
color:dodgerblue;color:lightyellow">Signup</button>
</fielsdet>
</form>
</body>
</html>
my connect.php
<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$date = $_POST['date'];
$gender = $_POST['gender'];
// Making Connection with database
$con = new mysqli('localhost','root','','phpdata');
if ($con -> connect_error) {
die('Connection failed :'.$conn -> connect_error);
}
else{
$stmt = $con->query("INSERT INTO signup(firstName, lastName, email, password,
number, date, gender)
values(?,?,?,?,?,?,?)");
$stmt->bind_param("ssssiss",$firstName, $lastName, $email, $password,
$number, $date, $gender);
$stmt->execute();
echo "Sign up successful";
$stmt->close();
$con->close();
}?>
Use prepare instead of query. All everything is ok.:
$stmt = $con->prepare("INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values(?,?,?,?,?,?,?)");
And make button type as submit:
<br><button type="submit" style="background-color:orangered;border-color:dodgerblue;color:lightyellow">Signup</button>
here is the code, it works fine with me
<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$date = $_POST['date'];
$gender = $_POST['gender'];
// Making Connection with database
$con = new mysqli('localhost','root','','phpdata');
if ($con -> connect_error) {
die('Connection failed :'.$conn -> connect_error);
}
else{
$stmt = $con->query("INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values("'.$firstName.'","'.$lastName.'","'.$email.'","'.$password.'","'.$number.'","'.$date.'","'.$gender.'")");
if ($con->query($stmt) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$con->close();
}//end of else of connection
?>
Add type in your submit button.
<button type='submit' style="background-color:orangered;border-color:dodgerblue;color:lightyellow">Signup</button>
and also your question marks and params ara not matching. it should be match. otherwise data won't store your db
correct that line also
The main problem is you are not loading code via apache server try to open http://localhost/signup.html instead of C:/xmapp/htdocs/connect.php
It seems you want to user PDO but your connection string not correct
<?php
$firstName = trim($_POST['firstName']);
$lastName = trim($_POST['lastName']);
$email = trim($_POST['email']);
$password = md5(trim($_POST['password']));
$number = trim($_POST['number']);
$date = trim($_POST['date']);
$gender = trim($_POST['gender']);
$con= new PDO("mysql:host=127.0.0.1;dbname=phpdata", 'root', 'root');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqli = "INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values(?,?,?,?,?,?,?)";
try {
$stmt= $con->prepare($sqli);
$stmt->bindParam(1,$firstName);
$stmt->bindParam(2,$lastName);
$stmt->bindParam(3,$email);
$stmt->bindParam(4,$password);
$stmt->bindParam(5,$number);
$stmt->bindParam(6,$date);
$stmt->bindParam(7,$gender);
$status = $stmt->execute();
echo "Sign up successful";
$stmt->close();
$con->close();
} catch(PDOException $e) {
echo "Error ".$e->getMessage();
}
?>
another problem is with your html form button type is missing
<button type="submit".... />
Here is the complete code after analyzing it for a lot of time. in your $stmt variable there was no query, it was empty. This code works fine just copy and paste it.
<?php
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
$email = $_POST['email'];
$password = $_POST['password'];
$number = $_POST['number'];
$date = $_POST['date'];
$gender = $_POST['gender'];
// Making Connection with database
$con = new mysqli('localhost','root','','abc');
if ($con -> connect_error) {
die('Connection failed :'.$conn -> connect_error);
}
else{
$sql = "INSERT INTO signup(firstName, lastName, email, password, number, date, gender)
values('$firstName','$lastName','$email','$password','$number','$date','$gender')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
$con->close();
}//end of else of connection
?>

PHP Form data into database

I've created a form that inserts data into a database.
I've been given the two functions to get the data and display it, these are located in a file called queryDb.php:
function addCustomer($fname, $lname, $address, $phone) {
$db = new MyDB();
if(!$db){
echo '<script type="text/javascript">alert("'.$db->lastErrorMsg().'");</script>';
} else {
//echo "Opened database successfully\n";
}
$sql ='INSERT INTO CUSTOMERS (FIRSTNAME, LASTNAME, ADDRESS, PHONE) VALUES ("'.$fname.'", "'.$lname.'", "'.$address.'", "'.$phone.'");';
$db->query($sql);
}
get function:
function getCustomers($searchTerm = null) {
$db = new MyDB();
if(!$db){
echo '<script type="text/javascript">alert("'.$db->lastErrorMsg().'");</script>';
} else {
//echo "Opened database successfully\n";
}
if(!$searchTerm) {
$sql ='SELECT * from CUSTOMERS;';
} else {
$sql ='SELECT * FROM CUSTOMERS WHERE FIRSTNAME LIKE "'.$searchTerm.'" OR LASTNAME LIKE "'.$searchTerm.'" OR ADDRESS LIKE "'.$searchTerm.'" OR PHONE LIKE "'.$searchTerm.'"';
}
$ret = $db->query($sql);
$array = [];
if(!$ret){
echo $db->lastErrorMsg();
return [];
} else {
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
$array[] = $row;
}
$db->close();
return $array;
}
}
In my reviewsubmit.php I have this up the top:
<?php
require_once "queryDb.php";
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$address = $_POST["address"];
$phone = $_POST["phone"];
addCustomer($firstname, $lastname, $address, $phone);
?>
And this is my form:
<form action="reviewsubmit.php" method="post">
<label for="firstname">First name:</label>
<input type="text" id="firstname" name="firstname" placeholder="Enter First name" required /><br>
<label for="lastname">Last Name:</label>
<input type="text" id="lastname" name="lastname" placeholder="Enter Last name" required /><br>
<label for="address">Address:</label>
<input type="text" id="address" name="address" placeholder="Enter Address" required /><br>
<label for="phone">Phone:</label>
<input type="text" id="phone" name="phone" placeholder="Enter Phone" required /><br>
<input type="submit" name="Submit" value="Submit" />
</form>
The problem is the first time when I click 'Submit', it puts empty values into the Database, when I click 'Submit' a second time it puts the actual values I typed in:
image
What is causing it to add empty values into the database?
Try with this
<?php
require_once "queryDb.php";
if(isset($_post['Submit')){
$firstname = $_POST["firstname"];
$lastname = $_POST["lastname"];
$address = $_POST["address"];
$phone = $_POST["phone"];
addCustomer($firstname, $lastname, $address, $phone);
}
?>
Checking that the submitted values are not empty or null before inserting them into the Database is your best bet.
<?php
require_once "queryDb.php";
$firstname = isset($_POST["firstname"])? htmlspecialchars(trim($_POST["firstname"])) : null;
$lastname = isset($_POST["lastname"]) ? htmlspecialchars(trim($_POST["lastname"])) : null;
$address = isset($_POST["address"]) ? htmlspecialchars(trim($_POST["address"])) : null;
$phone = isset($_POST["phone"]) ? htmlspecialchars(trim($_POST["phone"])) : null;
// CHECK THAT YOU DON'T HAVE NULL OR EMPTY FIELD VALUES BEFORE INSERTING ANYTHING INTO DATABASE
if(!is_null($firstname) && !is_null($lastname) && !is_null($address) && !is_null($phone) ){
addCustomer($firstname, $lastname, $address, $phone);
}
?>
A row is inserted into the database the first time you load the page. This is happening because you are not checking if the form has actually been submitted.
You will need to check if the form is already posted. You can do that like this:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
IF (isset($_POST['submit'])) {
// Do the database stuff
}
}
// Your form here
You can check if $_POST['Submit'] is set and $_POST is not empty before calling addCustomer function. PHP function empty and isset may help you with this.

PHP application not saving data to MySQL database

I am creating my first Wordpress plugin and have been stumped for a couple of days. So far I am trying to just get my plugin to save data to the MySQL database on my localhost. When I enter info into the form it creates a new row, which auto increments, but does not pass any of the info that I have entered into the database.
I understand that I have to clean up a lot of this code before I use it but I am just starting and stumped on this particular issue.
Here is the relevant code;
dvi_customer_info.php file
<?php
require('database.php');
require('customer_info_functions.php');
if ($action == 'add_customer') {
$rep = $_POST['rep'];
$business = $_POST['business'];
$address = $_POST['address'];
$phone = $_POST['phone'];
$name = $_POST['name'];
$email = $_POST['email'];
}
add_customer($rep, $business, $address, $phone, $name, $email);
include('dvi_customer_info_sheet.php');
customer_info_functions.php file
<?php
function add_customer($rep, $business, $address, $phone, $name, $email) {
global $db;
$query = "INSERT INTO customers
(repName, customerBusiness, customerAddress, customerPhone, customerName, customerEmail)
VALUES
('$rep', '$business', '$address', '$phone', '$name', '$email')";
$db->exec($query);
}
?>
dvi_customer_info_sheet.php file
<body>
<h1>Customer Info Sheet</h1>
<form action="dvi_customer_info.php" method="post" id="customer_info_sheet_form">
<input type="hidden" name="action" value="add_customer" />
<label>Name of Rep:</label>
<input type="input" name="rep" />
<br />
<label>Name of Business:</label>
<input type="input" name="business" />
<br />
<label>Address:</label>
<input type="input" name="address" />
<br />
<label>Phone #:</label>
<input type="input" name="phone" />
<br />
<label>Name of Decision Maker:</label>
<input type="input" name="name" />
<br />
<label>Email:</label>
<input type="input" name="email" />
<br />
<label> </label>
<input type="submit" value="Add Customer" />
<br /> <br />
</form>
</body>
"INSERT INTO customers
(repName, customerBusiness, customerAddress, customerPhone, customerName, customerEmail)
VALUES
(\"$rep\", $business,...)
(Use double quotes "$rep" or don't use any quotes $business ( use this option) as anything within single quotes is taken as it is i.e a string constant and hence the variable inside that didn't get substituted by it's value
Try This
$query = "INSERT INTO customers
(repName, customerBusiness, customerAddress, customerPhone, customerName, customerEmail)
VALUES
('".$rep."', '".$business."', '".$address."', '".$phone."', '".$name."', '".$email."')";
And Also
I am not clear About your if condition if($action =='add_customer' ) instead of that try
if(isset($_POST['add_customer']))
What is $action?
you can use wordpress default action to insert record in to database like this below code it's sure to insert your record in mysql database.
You have no need to use function to just insert record in database just put this code in dvi_customer_info.php file
<?php
require('database.php');
require('customer_info_functions.php');
global $wpdb;
if ($action == 'add_customer') {
$rep = $_POST['rep'];
$business = $_POST['business'];
$address = $_POST['address'];
$phone = $_POST['phone'];
$name = $_POST['name'];
$email = $_POST['email'];
$your_table_name_here = $wpdb->prefix . 'yourdatanase_table';
$data = array(
'repName' => $rep,
'customerBusiness' => $business,
'customerAddress' => $address,
'customerPhone' => $phone,
'customerName' => $name,
'customerEmail' => $email
);
$idsa = $wpdb->insert($your_table_name_here, $data);
if ($idsa) {
echo '<p class="alert-box success tfamsg">Franchise Setting Inserted.</p>';
}
}
include('dvi_customer_info_sheet.php');
?>
Now it will insert record in database you had also change your database table $your_table_name_here.
Thanks

registration not working in php

hi i am trying to create a registration page using html and php and the database is mysql. the IDE i am using is cloud9. the code for my form is as follows:
<form action="signup_code.php" method="post">
<p>Name<br/><input type="text" name="name" maxlength="20" ></p>
<p>Phone Number<br/><input type="number" name="phone" maxlength="20" ></p>
<p>Email<br/><input type="email" name="email" maxlength="50" ></p>
<p>Password<br/><input type="password" name="pass1" maxlength="20" ></p>
<p>Confirm Password<br/><input type="password" name="pass2" maxlength="20" ></p>
<p>Address<br/><input type="text" name="address" maxlength="20" ></p>
<button type="submit" class="btn btn-default">Signup
</button>
</form>
the code in the signup_code .php is :
<?php
$IP = "0.0.0.0";
$dbuser = "bhaskey";
$conn = mysqli_connect($IP, $dbuser, "","trydb");
if(! $conn )
{
die('Could not connect: ' . mysqli_error());
}
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['email'];
$pass1 = $_POST['pass1'];
$pass2 = $_POST['pass2'];
$address = $_POST['address'];
$query = "SELECT email FROM user_main where email='".$email."'";
$result = mysqli_query($conn,$query);
$numResults = mysqli_num_rows($result);
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) // Validate email address
{
$message = "Invalid email address please type a valid email!!";
}
elseif($numResults>=1)
{
$message = $email." Email already exist!!";
}
else
{
mysqli_query("(insert into user_main(name,phone, email,pass1, pass2, address) values
('".$name."','".$phone."', '".$email."', '".pass1."','",$pass2."','".$address."')");
echo $message = "Signup Sucessfully!!";
}
mysqli_close($conn);
?>
however when i am executing the the code i.e clicking the signup button in the form, it is giving me the following result
"Cannot POST /bhaskey/eshopper/signup_code.php"
where i am going wrong. i am sure it must be a silly mistake. but since i am pretty new and still in learning phase, it is becoming troublesome for me.
EDIT: i tried to pass the whole path of the .php file to the action in form. but after i click on the submit button, the page turns whte and nothing is displayed anymore.
i tried clearing browser cache but its not helping.
You have to replace your this code
$conn = mysql_connect($IP, $dbuser, "","trydb");
to this code
$conn = new mysqli($IP, $dbuser, "","trydb");
and also replace this code
mysql_close($conn);
to this code
mysqli_close($conn);
$IP = "0.0.0.0";?
Instead you should use 'localhost' or possibly 127.0.0.1.

Categories