GordanAndrews GordanAndrews - 6 months ago 23
PHP Question

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?

Answer

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);
 }
?>