MySQL prepared statement returns false - php

I have the following working MySQL insert:
$tableSelect = $_POST["tableSelect"];
$companyName = $_POST["companyName"];
$telephone = $_POST["telephone"];
$fax = $_POST["fax"];
$email = $_POST["email"];
$address = $_POST["address"];
$postcode = $_POST["postcode"];
$category = $_POST["category"];
$contact = $_POST["contact"];
$contactTel = $_POST["contactTel"];
$contactEmail = $_POST["contactEmail"];
$sql = "INSERT INTO $tableSelect (companyName,telephone,fax,email,address,postcode,category,contact,contactTel,
contactEmail) VALUES ('$companyName','$telephone','$fax','$email','$address','$postcode','$category',
'$contact','$contactTel','$contactEmail');";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
However, I've tried to change this into a prepared statement to protect myself from injection, like so:
$stmt = $con->prepare("INSERT INTO suppliers (companyName,telephone,fax,email,address,postcode,
category,contact,contactTel,contactEmail) VALUES(:companyName, :telephone, :fax, :email, :address,
:postcode, :category, :contact, :contactTel, :contactEmail);");
if ($stmt !== FALSE) {
$stmt->bindParam(':companyName',$companyName);
$stmt->bindParam(':telephone',$telephone);
$stmt->bindParam(':fax',$fax);
$stmt->bindParam(':email',$email);
$stmt->bindParam(':address',$address);
$stmt->bindParam(':postcode',$postcode);
$stmt->bindParam(':category',$category);
$stmt->bindParam(':contact',$contact);
$stmt->bindParam(':contactTel',$contactTel);
$stmt->bindParam(':contactEmail',$contactEmail);
$companyName = $_POST["companyName"];
$telephone = $_POST["telephone"];
$fax = $_POST["fax"];
$email = $_POST["email"];
$address = $_POST["address"];
$postcode = $_POST["postcode"];
$category = $_POST["category"];
$contact = $_POST["contact"];
$contactTel = $_POST["contactTel"];
$contactEmail = $_POST["contactEmail"];
$stmt->execute();
}
else {
echo "Could not connect";
}
Every time I run it, $stmt returns false. It's the first time I've used prepared statements and I'm fairly new to MySQL so some pointers would be greatly appreciated.

The syntax for mysqli is wrong. You have tried using PDO. For mysqli
$stmt = $con->prepare("INSERT INTO suppliers (companyName,telephone,fax,email,address,postcode,category,contact,contactTel,contactEmail) VALUES(?,?,?,?,?,?,?,?,?,?)");
if($stmt){
$stmt->bind_param('ssssssssss',$companyName,$telephone,$fax,$email,$address,$postcode,$category,$contact,$contactTel,$contactEmail);
//s for string, i for integer, d for double, b for blob
$stmt->execute();
}else{
echo($con->error); //TO display Error
}

Though your question is a sure offtopic, here are some pointers
Assuming you are using PDO for the second example (for some reason you didn't indicate it in your question)
you have to tell PDO to throw exceptions
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
it will let you to at least have an error message to think of.
a table name should never be supplied by client side.
adjust your bound variables to make them fit the query
Instead of that long and windy code just remove unnecessary members from $_POST array and pass it to execute
something like this
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql = "INSERT INTO suppliers
(companyName,telephone,fax,email,address,postcode,
category,contact,contactTel,contactEmail)
VALUES
(:companyName, :telephone, :fax, :email, :address,
:postcode, :category, :contact, :contactTel, :contactEmail)";
$stmt = $con->prepare($sql);
unset ($_POST['submit']);
// make sure you unset all the useless members
$stmt->execute($_POST);

Related

PHP code inserting empty values in SQL table after adding filter_var

After adding filter_var and then sanitizing the input, my php code now inserts empty values in SQL table. My code worked fine before hand, but now doesn't work. How come? I'm trying to sanitize input so no one can hack my data.
<?php
$servername = "localhost";
$username = "****";
$password = "*********";
$dbname = "app";
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 MyGuests (firstname, lastname, email) VALUES (:firstname, :lastname, :email)");
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
// insert a row
$firstname = filter_var($firstname, FILTER_SANITIZE_STRING, $_POST["firstname"]);
$lastname = filter_var($lastname, FILTER_SANITIZE_STRING, $_POST["lastname"]);
$email = filter_var($email, FILTER_SANITIZE_EMAIL, $_POST["email"]);
$stmt->execute();
echo "New records created successfully";
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
$conn = null;
?>
Looks like you aren't passing the right variables into filter_var and not checking if the data is valid.
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (:firstname, :lastname, :email)");
// Validate input *BEFORE* binding to statement
$firstname = filter_var($_POST["firstname"], FILTER_SANITIZE_STRING);
$lastname = filter_var($_POST["lastname"], FILTER_SANITIZE_STRING);
$email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
if ($firstname && $lastname && $email) {
$stmt->bindParam(':firstname', $firstname);
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':email', $email);
// insert a row
$stmt->execute();
echo "New records created successfully";
} else {
echo "Failed Data Check: First Name (" . $firstname . ") - Last Name (" . $lastname . ") - EMail (" . $email . ")" ;
}
You'll probably want to adjust the last debug line.

PHP fails at inserting values into database

I'm using a WordPress theme for my site, but customizing it has given me such a headache that we are trying to use our own hand written from instead of the one provided by WordPress.
I have written a php-script that should insert values from this form into a custom table in a custom database outside of the wordpress database. How ever when I try to run it I get no error messages, and no data is inserted into the database.
my PHP code, please not that I have changed the $user and $pass to not show here. I've tested the login info used in this script via terminal on my database, and it worked fine. See the full file here page.sign.php
if(isset($_POST['submit'])) {
$lastname = $_POST["lname"];
$firstname = $_POST["fname"];
$email = $_POST["email"];
$affiliation = $_POST["affiliation"];
$country = $_POST["X"];
$position = $_POST["position"];
$hindex = $_POST["scholar"];
$gender = $_POST["optionsRadios"];
$city = $_POST["city"];
$webpage = $_POST["webpage"];
$newsletter = $_POST["newsletter"];
//Source https://gist.github.com/adrian-enspired/385c6830ba2932bc36a2
$host = "localhost";
$dbname = "petition";
$user = "<username>";
$pass = "<password>";
$charset = "UTF8MB4"; // if your db does not use CHARSET=UTF8MB4, you should probably be fixing that
$dsn = "mysql:host={$host};dbname={$dbname};charset={$charset}";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
echo "<h1>Error connecting to the database </h1>";
}
$stmt = $pdo->prepare("INSERT INTO petitioners (lastname, firstname, email, affiliation, country, position, hindex, gender, city, webpage, newsletter)
VALUES
(:lastname, :firstname, :email, :affiliation, :country, :position, :hindex, :gender, :city, :webpage, :newsletter)");
$stmt->bindParam(':lastname', $lastname);
$stmt->bindParam(':firstname', $firsname);
$stmt->bindParam(':email',$email);
$stmt->bindParam(':affliation',$affiliation);
$stmt->bindParam(':country',$country);
$stmt->bindParam(':position',$position);
$stmt->bindParam(':hindex',$hindex);
$stmt->bindParam(':gender',$gender);
$stmt->bindParam(':city',$city);
$stmt->bindParam(':webpage',$webpage);
$stmt->bindParam(':newsletter',$newsletter);
$stmt->execute();
echo "<h1>Signatory succefully registered</h1>";
$stmt->close();
$conn->close();
}

Update query not updating records

I am totally confused as to why my update query is not updating the records. There are no errors in inspector console. If I run the query in phpmyadmin substituting the vars with actual values it works fine.
I have tried coding the vars like this in query: '".$name."' and also like i have it now. All field names are correct and all values are being passed to php correctly. I would be grateful if someone could point out my error as it is driving me nuts. Many thanks
<?php
$conn = mysqli_connect("localhost","root","","domain");
if($conn === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$id = mysqli_real_escape_string($conn, $_POST['idcon']);
$company = mysqli_real_escape_string($conn, $_POST['companycon']);
$name = mysqli_real_escape_string($conn, $_POST['namecon']);
$email = mysqli_real_escape_string($conn, $_POST['emailcon']);
$phone = mysqli_real_escape_string($conn, _POST['phonecon']);
$fax = mysqli_real_escape_string($conn, $_POST['faxcon']);
$mobile = mysqli_real_escape_string($conn, $_POST['mobilecon']);
$sql = mysqli_query($conn, "UPDATE contact_con SET idcode_con = '$company', name_con = '$name', email_con = '$email', phone_con = '$phone', fax_con = '$fax', mobile_con = '$mobile' WHERE id_con='$id'");
mysqli_close($conn);
?>
You should be using prepared queries, also you have a typo _POST['phonecon'].
<?php
$conn = mysqli_connect("localhost", "root", "", "domain");
// check connection
if (mysqli_connect_errno()) {
exit("Connect failed: ". mysqli_connect_error());
}
// create a prepared statement
$stmt = $conn->prepare("
UPDATE contact_con
SET idcode_con = ?,
name_con = ?,
email_con = ?,
phone_con = ?,
fax_con = ?,
mobile_con = ?
WHERE id_con= ?
");
if ($stmt) {
// bind parameters for markers
$stmt->bind_param(
"ssssssi",
$_POST['companycon'],
$_POST['namecon'],
$_POST['emailcon'],
$_POST['phonecon'],
$_POST['faxcon'],
$_POST['mobilecon'],
$_POST['idcon']
);
// execute query
$stmt->execute();
// close statement
$stmt->close();
}
// close connection
$conn->close();
?>

How do I insert with pdo by getting variables from form?

How do I to make an insert from a form by PDO it gives me the following error:
Fatal error: Call to a member function bindParam() on string
Here is my code:
$name = $_POST['name'];
$name = $_POST['subname'];
$phone= $_POST['phone'];
$sql = "INSERT INTO customers(name,subname,phone)VALUES(:name,:subname,:phone)";
$sql->bindParam(':name', $name);
$sql->bindParam(':subname', $subname);
$sql->bindParam(':phone', $phone);
$sql->bindParam(':telefono', $telefono);
$sql->execute();
You have to work with your PDO statement, and first prepare your query:
$name = $_POST['name'];
$name = $_POST['subname'];
$phone= $_POST['phone'];
$sql = "INSERT INTO customers(name,subname,phone)VALUES(:name,:subname,:phone)";
$sth = $dbh->prepare($sql);
$sth->bindParam(':name', $name);
$sth->bindParam(':subname', $subname);
$sth->bindParam(':phone', $phone);
$sth->bindParam(':telefono', $telefono);
$sth->execute();

MySQL error because of syntax in Custom PHP code

I am trying to enter user's data into a database. I think the commas in the address are causing the error.
<?php
$full_name = $_POST["fullname"];
$email = $_POST["email"];
$password = $_POST["password"];
$full_address = $_POST["address"];
$city = $_POST["city"];
$age = $_POST["age"];
$contact_number = $_POST["number"];
$gender = $_POST["gender"];
$education = $_POST["education"];
?>
<?php
$servername = "hidden";
$username = "hidden";
$password = "hidden";
$dbname = "hidden";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO users (full_name, email, password,full_address,city,age,contact_number,gender,education)
VALUES ($full_name, $email, $password,$full_address,$city,$age,$contact_number,$gender,$education)";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
As others have noted, your code is vulnerable to SQL injections. You should consider using parameterized queries:
$sql = "INSERT INTO users (full_name, email, password, full_address, city, age, contact_number, gender, education)
VALUES (?,?,?,?,?,?,?,?,?)";
$stmt = mysqli_prepare($conn, $sql);
// Bind parameters
$stmt->bind_param("s", $full_name);
$stmt->bind_param("s", $email);
$stmt->bind_param("s", $password);
$stmt->bind_param("s", $full_address);
$stmt->bind_param("s", $city);
$stmt->bind_param("s", $age);
$stmt->bind_param("s", $contact_number);
$stmt->bind_param("s", $gender);
$stmt->bind_param("s", $education);
if ($stmt->execute()) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
For more information refer to the PHP manual on MySQLi prepared statements.
You need to quote string in your SQL statement;
$sql = "INSERT INTO users (full_name, email, password,full_address,city,age,contact_number,gender,education)
VALUES ('$full_name', '$email', '$password','$full_address','$city',$age,'$contact_number','$gender','$education')";
Notice the single quotes around all the variables that contain strings. I might be a bit off because I don't know the values or table structure.
But the just quote all values that are going in to a Date or Text field.
To avoid additional problems and security risks you should be using mysqli_real_escape_string (at a minimum).
In all your assignment statements wrap the values in mysqli_real_escape_string
$full_name = mysqli_real_escape_string($conn, $_POST["fullname"]);
$email = mysqli_real_escape_string($conn, $_POST["email"]);
...
Note this requires setting up your DB connection before the variable assignments, so you'll have to reorganize your code a bit.
rink.attendant.6's answer is the proper way to adapt your code.

Categories