PHP & MySQL no inserting data into table (PDO) - php

I am having trouble getting a record to insert into my database, I have checked the code and all the variables and names match between PHP and the database.
There are no error messages and I am getting the text saying booking was created but, no record is entered into the database.
Here is the php code for inserting the record;
<div class="containter">
<?php
if (isset($_POST['submit'])) {
try {
include ('include\PDO.php');
$sql = "INSERT INTO customers(Customer_Name, Customer_Email, Customer_Contact) VALUES (:Customer_Name, :Customer_Email, :Customer_Contact)";
//Named Parameters
$stmt = $dbh->prepare($sql);
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
$Customer_Name = filter_input(INPUT_POST, 'Customer_Name');
$stmt->bindValue(':Customer_Name', $Customer_Name, PDO::PARAM_STR);
$Customer_Email = filter_input(INPUT_POST, 'Customer_Email');
$stmt->bindValue(':Customer_Email', $Customer_Email, PDO::PARAM_STR);
$Customer_Contact = filter_input(INPUT_POST, 'Customer_Contact');
$stmt->bindValue(':Customer_Contact', $Customer_Contact, PDO::PARAM_STR);
print $Customer_Contact;
print $Customer_Name;
print $Customer_Email;
$stmt->execute();
$dbh = null;
} catch (PDOException $e) {
//Error Messages
print "We have had an error: " . $e->getMessage() . "<br/>";
die();
}
?>
<p> Booking Created.</p>
<?php } else { ?>
<form action ="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">
<label>Name:</label> <input type="text" name ="Cusomer_Name">
<label>Email:</label> <input type="email" name ="Cusomer_Email">
<label>Contact:</label> <input type="tel" name ="Cusomer_Contact">
<input type="submit" name ="submit">
</form>
<?php } ?>
</div>
</body>
</html>
I have checked everything I can think of but I just cannot seem to get the records to add to the database.
Any ideas of what I'm doing wrong?

In the html form you have:
<label>Name:</label> <input type="text" name ="Cusomer_Name">
In the php code you filter Customer_Name:
$Customer_Name = filter_input(INPUT_POST, 'Customer_Name');
There is a missing 't' in the html form.
Put Customer_Name instead of Cusomer_Name in the html form and do the same thing for Cusomer_Email and Cusomer_Contact

$stmt->execute(); returns boolean with answer. Try following snippet to figure out where exactly problem is:
$success = $stmt->execute();
if (!$success){
print $stmt->errorInfo()[2]; //PDO driver error message
}

Related

POST method not inserting data into database table

I'm trying to play around with databases and inserting data dynamically with php.
At the moment I have a form with 'post' method and everything seems logical to me but it isn't inserting the data into the table.
Code is attached below, would appreciate if someone could point me into the right direction.
index.php:
<form action="index.php" method="post">
<label for="name">Name</label>
<input type="text" name="name" required>
<label for="breed">Breed</label>
<input type="text" name="breed">
<label for="age">Age</label>
<input type="text" name="age">
<input type="submit" name="submit" value="Submit">
</form>
<?php
require "connect.php";
if('submit') {
$name = $_POST['name'];
$breed = $_POST['breed'];
$age = $_POST['age'];
$newdog = mysqli_query('INSERT INTO `dogs`(`name`, `breed`, `age`) VALUES ([$name],[$breed],[$age)');
if ($newdog) {
echo "$name has been added to the database";
} else {
echo "$name has not been added to database.";
};
};
?>
connect.php:
<?php
$connect = mysqli_connect('localhost', 'max', 'password', 'db_test');
?>
<?php
require "connect.php";
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$breed = $_POST['breed'];
$age = $_POST['age'];
$newdog = mysqli_query($connect, 'INSERT INTO dogs(name, breed, age) VALUES ("'.$name.'","'.$breed.'","'.$age.'")');
if ($newdog) {
echo "$name has been added to the database";
} else {
echo "$name has not been added to database.";
};
};
?>
Change if('submit') {
TO
if(isset($_POST['submit'])){//check if it is set
}
Also change this line:
$newdog = mysqli_query('INSERT INTOdogs(name,breed,age) VALUES ([$name],[$breed],[$age)');
TO
$newdog = mysqli_query($connect, 'INSERT INTOdogs(name,breed,age) VALUES ($name,$breed,$age)');//remove square bracktes and add connection variable
Your code is very well vulnerable to SQL injection
Using prepared statements,
$stmt = $connect->prepare("INSERT INTO dogs (`name`, `breed`, `age`) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $name, $breed, $age);
if($stmt->execute() == true){
echo 'Saved';
} else {
echo 'Error '. $stmt->error;
}
Own answer: Figured it out, I had to configure PHPStorm to use MAMP Apache server instead of the internal server since that one apparently doesn't like $_POST[] requests

I have an input form with a prepaired statement that should input into sql and print the input but all I get is NULL printed on the page

I have an input form with a prepaired statement that should input into sql and print the input but all I get is a blank page with the input php address. Have i missed something? I have changed the code to below but all that appears is NULL. The date field is sql type date and the string i entered into it to test is "2008-11-11", without the quotes of course.
<?php
function shutdown(){
var_dump(error_get_last());
}
register_shutdown_function('shutdown');
session_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);
include("dbconfig.php");
$errorvar = "";
if (isset($_POST['submit'])) {
if (empty($_POST['Title']) || empty($_POST["Date"]) || empty($_POST["Country"]) || empty($_POST["bloguser"]) || empty($_POST["Blogentry"])) {
$errorvar = "You dun gooffed";
echo $errorvar;
} else {
//defining and injection protecting data
$title = $_POST['Title'];
$date = $_POST['Date'];
$country = $_POST['Country'];
$bloguser = $_POST['bloguser'];
$blogentry = $_POST['Blogentry'];
$stmt = $mysqli->prepare("INSERT INTO blogs (BlogName,blogDate,country,bloguser,Blogdata) VALUES (?,?,?,?,?)");
$stmt->bind_param('sssss', $title, $date, $country, $bloguser, $blogentry);
if ($stmt->execute()) {
echo "New records created successfully";
printf("%d Row inserted.\n", $stmt->affected_rows);
header("location:index.php");
} else {
header("location:index.php");
echo $conn->error;
}
$stmt->close();
$conn->close();
header("location:index.php");
}
}
?>
The html form is below
<fieldset style="width:45%"><legend>Blog data entry</legend>
<form name="Blogentry" action="Inputform.php" method="POST">
<label for="Title">Title: </label>
<input type="text" name="Title" value="" size="40"/><br>
<label for="Date">Date: </label>
<input type="text" name="Date" value="" size="40"/><br>
<label for="Country">Country: </label>
<input type="text" name="Country" value="" size="40"/><br>
<label for="bloguser">User: </label>
<input type="text" name="bloguser" value="" size="40"/><br>
<label for="Blogentry">Blog: </label>
<textarea name="Blogentry" rows="4" cols="20">
</textarea><br>
<input id="button" type="submit" name="submitblog" value="submit-blog">
</form>
</fieldset>
</body>
</html>
enable error reporting :
add on top of your script
error_reporting(E_ALL);
ini_set('display_errors', 1);
and then use prepared statements proper. As far as your script there no parameters that you are binding,
<?php
session_start();
include("dbconfig.php");
$errorvar = "";
if (isset($_POST['submit'])) {
if (empty($_POST['Title']) || empty($_POST["Date"]) || empty($_POST["Country"]) || empty($_POST["bloguser"]) || empty($_POST["Blogentry"])) {
$errorvar = "You dun gooffed";
echo $errorvar;
} else {
//defining and injection protecting data
$title = $_POST['Title'];
$date = $_POST['Date'];
$country = $_POST['Country'];
$bloguser = $_POST['bloguser'];
$blogentry = $_POST['Blogentry'];
$stmt = $conn->prepare("INSERT INTO blogs (BlogName,blogDate,country,bloguser,Blogdata) VALUES (?,?,?,?,?)");
$stmt->bind_param("sssss", $title, $date, $country, $bloguser, $blogentry);
if ($stmt->execute()) {
echo "New records created successfully";
printf("%d Row inserted.\n", $stmt->affected_rows);
header("location:index.php");
} else {
echo $conn->error;
}
$stmt->close();
$conn->close();
}
}
?>
you don't need to escape anything since you are using bind
so drop the mysqli_real_escape
you have errors in your query as I point out in the code below
$stmt = $mysqli->prepare("INSERT INTO blogs (BlogName,blogDate,country,bloguser,Blogdata) VALUES (?,?,?,?,?)");
// question marks will be replaced with data - use question marks!
$stmt->bind_param('sssss', $title, $date, $country, $bloguser, $blogentry);
// number of bound parameters should match number and order of question marks
$stmt->execute();

How to make a warning message if possible duplicate entry is added?

I have here the code for insertion using PDO and the insertion is working fine my problem is that how can i can determine if i inputted in the textbox the record that is already in the database,in my database ihave a column of ID, Firstname and Lastname, ID is auto increment,Firstname is set to unique and lastly is password set to varchar..what i want to happen is that when try to insert a record that is already in the database i want a warning message or maybe a alert message that tells me that "the record is already duplicate"..can somebody please help me with it?
here is the code
class.php
public function create($username,$password,$province)
{
try
{
$stmt = $this->db->prepare("INSERT INTO login(Firstname,Lastname) VALUES(:Firstname, :Lastname)");
$stmt->bindparam(":Firstname",$Firstname);
$stmt->bindparam(":Lastname",$Lastname);
$stmt->execute();
return true;
}
catch(PDOException $e)
{
echo $e->getMessage();
return false;
}
}
and here is index.php
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-save']))
{
$username = $_POST['Firstname'];
$password = $_POST['Lastname'];
if($crud->create($Firstname,$Lastname))
{
echo "<script type='text/javascript'>alert('Saved!');</script>";
}
else
{
echo "<script type='text/javascript'>alert('Insertion Failed!'); </script>";
}
}
?>
<form method="POST" class="signin" action="" name="Add" target="iframe">
<fieldset class="textbox">
<label class="username">
<span>Username</span>
<input id="Firstname" name="Firstname" value="" type="text" placeholder="Username" required/>
</label>
<label class="password">
<span>Password</span>
<input id="Lastname" name="Lastname" value="" type="password" Placeholder="Password" required/>
</label>
<br />
<button id="submit" type="submit" name="btn-save">Save</button>
<button id="submit" type="reset" name="reset">Reset</button>
<br />
<br />
<hr>
</fieldset>
</form>
If you have the correct UNIQUE keys set in your database, PDO will already throw such a warning/error. You can easily try it yourself by inserting twice the same name
You should try to change your code to this, as this will throw the actual error. The correct function to call would be PDOStatement::errorInfo
Example code would be like this:
public function create($username,$password,$province)
{
try
{
$stmt = $this->db->prepare("INSERT INTO login(Firstname,Lastname) VALUES(:Firstname, :Lastname)");
$stmt->bindparam(":Firstname",$Firstname);
$stmt->bindparam(":Lastname",$Lastname);
if (!$stmt->execute())
{
throw new Exception('Could not execute SQL statement: ' . var_export($stmt->errorInfo(), TRUE));
}
return true;
}
catch(Exception $e)
{
// Here you can filter on error messages and display a proper one.
return $e->getMessage();
}
}
In your index.php, change your PHP code to this:
if(isset($_POST['btn-save']))
{
$username = $_POST['Firstname'];
$password = $_POST['Lastname'];
$result = $crud->create($Firstname,$Lastname);
if($result === TRUE)
{
echo "<script type='text/javascript'>alert('Saved!');</script>";
}
else
{
echo "<script type='text/javascript'>alert(" . $result . "); </script>";
}
}
An other, better, method would be to do a separate SELECT before you do the actual insert to see if the values you are trying to insert already exist.

Entering data from form into Database PDO

I learned MySQL, created a form and had it working with the database. I was then told I should be doing it PDO with prepared statements, so I did some research on that and changed my code.
I now have the code right (I think) but I can't figure out how data gets input. As you can see on my code, I have the database creating the rows as the user submits the form. However the database just picks up on whatever is within the speech marks under //insert a row and //insert another row.
For example, right now if the user completes and submits the form, no matter what information they enter, I just get 'Joe' and 'joe#example.com' etc showing in my database. Obviously I need their answers, otherwise my form would be irrelavant (as would the data submission). Have I totally missed the mark or am I missing something silly? I've tried changing and researching but am struggling. Really new to all this.
FORM:
<form action="testsubmit-pdo.php" method="post">
<label>Student Name :</label>
<input type="text" name="stu_name" id="name" required="required" placeholder="Please Enter Name"/><br /><br />
<label>Student Email :</label>
<input type="email" name="stu_email" id="email" required="required" placeholder="john123#gmail.com"/><br/><br />
<label>Student City :</label>
<input type="text" name="stu_city" id="city" required="required" placeholder="Please Enter Your City"/><br/><br />
<input type="submit" value=" Submit " name="submit"/><br />
</form>
PHP:
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO demo (stu_name, stu_email, stu_city)
VALUES (:stu_name, :stu_email, :stu_city)");
$stmt->bindParam(':stu_name', $stu_name);
$stmt->bindParam(':stu_email', $stu_email);
$stmt->bindParam(':stu_city', $stu_city);
// insert a row
$stu_name = "Joe";
$stu_email = "joe#example.com";
$stu_city = "Joeland";
$stmt->execute();
// insert another row
$stu_name = "Mary";
$stu_email = "mary#example.com";
$stu_city = "Maryland";
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
Change this -
// insert a row
$stu_name = "Joe";
$stu_email = "joe#example.com";
$stu_city = "Joeland";
$stmt->execute();
// insert another row
$stu_name = "Mary";
$stu_email = "mary#example.com";
$stu_city = "Maryland";
$stmt->execute();
to this -
// insert a row
$stu_name = $_POST['stu_name'];
$stu_email = $_POST['stu_email'];
$stu_city = $_POST['stu_city'];
$stmt->execute();
Your form will place the values in PHP's POST array and you can access them by the name property from the form.
You post the data entered by the user to your php file
<form action="some_php_file.php" method="post">
<input type="text" name="stu_name">
<input type="email" name="stu_email">
<input type="text" name="stu_city">
<input type="submit" name="submit" value="submit">
</form>
and in php code, first you need to check if the submit button is clicked
//check if submit button is clicked
If(isset($_POST['submit'])){
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO demo (stu_name, stu_email, stu_city)
VALUES (:stu_name, :stu_email, :stu_city)");
$stmt->bindParam(':stu_name', $stu_name);
$stmt->bindParam(':stu_email', $stu_email);
$stmt->bindParam(':stu_city', $stu_city);
$stu_name = $_POST['stu_name'];
$stu_email = $_POST['stu_email'];
$stu_city = $_POST['stu_city'];
$stmt->execute();
echo "New records created successfully";
}catch(PDOException $e){
echo "Error: " . $e->getMessage();
}
$conn = null;
}

inserting data into mysql from an html textboxes. using php/mysql

I can't see where i am going wrong, it just won't let me connect to the mysql database and i only get error message when trying to save details.?????? i think there may be a problem where it shows $sql for inserting the values into the table. the first part newstudent.php works, but sql.php does not work.
//new student.php
<html>
<head>
</head>
<body>
<h2>Your details</h2>
<form name="frmdetails" action="sql.php" method="post">
ID Number :
<input name="txtid" type="text" />
<br/>
Password :
<input name="txtpassword" type="text" />
<br/>
Date of Birth :
<input name="txtdob" type="text" />
<br/>
First Name :
<input name="txtfirstname" type="text" />
<br/>
Surname :
<input name="txtlastname" type="text" />
<br/>
Number and Street :
<input name="txthouse" type="text" />
<br/>
Town :
<input name="txttown" type="text" />
<br/>
County :
<input name="txtcounty" type="text" />
<br/>
Country :
<input name="txtcountry" type="text" />
<br/>
Postcode :
<input name="txtpostcode" type="text" />
<br/>
<input type="submit" value="Save" name="submit"/>
</form>
</body>
</html>
//sql.php
$conn=mysql_connect("localhost", "20915184", "mysqluser");
mysql_select_db("db5_20915184", $conn);
// If the form has been submitted
$id=$_POST['txtstudentid'];
$password=$_POST['txtpassword'];
$dob=$_POST['txtdob'];
$firstname=$_POST['txtfirstname'];
$lastname=$_POST['txtlastname'];
$house=$_POST['txthouse'];
$town=$_POST['txttown'];
$county=$_POST['txtcounty'];
$country=$_POST['txtcountry'];
$postcode=$_POST['txtpostcode'];
// Build an sql statment to add the student details
$sql="INSERT INTO student
(studentid,password,dob,firstname,lastname,house,town,county,country,postcode) VALUES
('$id','$password','$dob','$firstname','$lastname','$house','$town','$county','$country','$postcode')";
$result = mysql_query($sql,$conn);
if($result){
echo"<br/>Your details have been updated";
echo "<BR>";
echo "<a href='Home.html'>Back to main page</a>";
}
else {
echo "ERROR";
}
// close connection
mysql_close($conn);
?>
The username comes before the password in mysql_connect();
Try running the sql statement in phpmyadmin and see if it works there!
With in your if else statement, where you echo "ERROR", try printing mysql_error() this would show that your mysql_connect() is wrong If the username/password combo is wrong.
To clean this up a bit, Here is what the if/else should look like
if($result){
echo"<br/>Your details have been updated";
echo "<BR>";
echo "<a href='Home.html'>Back to main page</a>";
} else {
echo "There has been an error <br/>";
print mysql_error();
}
EDIT :
Also, Prevent sql injection with mysql_real_escape_string() on all posted values
Well your code is incomplete, you must insert when the button is clicked also its important to check if a field isset before saving the field in the database also important to filter and sanitize user inputs before submitting. Learn to use prepared statements, with mysqli prepared or PDO whatever works for you, Also don't store passwords in plain text/md5 use password_hash() and password_verify()
Your code with mysqli prepared should look like :
<html>
<head>
</head>
<body>
<h2>Your details</h2>
<form name="frmdetails" action="sql.php" method="post">
ID Number :
<input name="txtid" type="text" />
<br/>
Password :
<input name="txtpassword" type="text" />
<br/>
Date of Birth :
<input name="txtdob" type="text" />
<br/>
First Name :
<input name="txtfirstname" type="text" />
<br/>
Surname :
<input name="txtlastname" type="text" />
<br/>
Number and Street :
<input name="txthouse" type="text" />
<br/>
Town :
<input name="txttown" type="text" />
<br/>
County :
<input name="txtcounty" type="text" />
<br/>
Country :
<input name="txtcountry" type="text" />
<br/>
Postcode :
<input name="txtpostcode" type="text" />
<br/>
<input type="submit" value="Save" name="submit"/>
</form>
</body>
</html>
sql.php
<?php
$servername = "localhost";
$username = "20915184";
$password = "mysqluser";
$dbname = "db5_20915184";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$errors = "";
if (isset($_POST['submit'])) { // submit button clicked
// validate fields
if (empty($_POST['txtstudentid'])) {
echo "enter id";
$errors++;
} else {
$id = userData($_POST['txtstudentid']);
}
if (empty($_POST['txtpassword'])) {
echo "enter password";
$errors++;
} else {
$password = userData($_POST['txtpassword']);
$hash = password_hash($password, PASSWORD_DEFAULT); //hashing password
}
if (empty($_POST['txtdob'])) {
echo "enter date of birth";
$errors++;
} else {
$dob = userData($_POST['txtdob']);
}
if (empty($_POST['txtfirstname'])) {
echo "enter first name";
$errors++;
} else {
$firstname = userData($_POST['txtfirstname']);
}
if (empty($_POST['txtlastname'])) {
echo "enter last name";
$errors++;
} else {
$lastname = userData($_POST['txtlastname']);
}
if (empty($_POST['txthouse'])) {
echo "enter house";
$errors++;
} else {
$house = userData($_POST['txthouse']);
}
if (empty($_POST['txttown'])) {
echo "enter town";
$errors++;
} else {
$town = userData($_POST['txttown']);
}
if (empty($_POST['txtcounty'])) {
echo "enter country";
$errors++;
} else {
$country = userData($_POST['txtcounty']);
}
if (empty($_POST['txtpostcode'])) {
echo "enter post code";
$errors++;
} else {
$postcode = userData($_POST['txtpostcode']);
}
if ($errors <= 0) { //all fields are set no errors
//start query
//check if user id does not exist
$statement = $conn->prepare("SELECT studentid FROM students WHERE studentid = ?");
$statement->bind_param('s', $id);
$statment->execute();
$statement->bind_result($studentID);
if ($statement->num_rows == 1) {
echo "the student Id " . $studentID . " already registered please login";
} else {
// no results then lets insert
$stmt = $conn->prepare("INSERT INTO students (studentid,password,dob,firstname,lastname,house,town,country,postcode) VALUES(?,?,?,?,?,?,?,?,?)");
$stmt->bind_param("sssssssss", $id, $hash, $dob, $firstname, $lastname, $house, $town, $country, $postcode);
$stmt->execute();
echo "<p>Your Details have been updated<br> <a href=\"Home.html\">Back to main page";
$stmt->close();
$conn->close();
}
}
}
//filter userinput
function userData($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
There are many good tutorials on the net on this, hopes this will help, I'm also open to suggestions and corrections incase I missed something.
**> Question mark (?)(placeholder) is used to assign the value.In Prepared
Statements we assign in the values in bind parameter function so that
our query is processed in secure way and prevent from SQL injections.**
In Prepared Statements we pass or attach the values to database query with the help of Bind Parameter function.
You have to attach all the variables whose value you want in your query with their appropriate Data Types just like we pass the 's' means the variable contains a string Data Type.
To execute the query in Prepared Statements you have to use execute() function with query object.
Remove the parameter from your with the inside inside and put in an empty string. i.e
VALUES('','$password','$dob',
etc etc

Categories