php pdo insert statement not working - php

I have a site on host gator. I can connect with my pdo statement but the statement for the insert doesnt seem to work. Right now I have defined the values but i plan to use variabled pulled from a $_POST from a form on the previous page.
<?php
/*** mysql hostname ***/
$hostname = 'xxx.xxx.xxx.xxx';
/*** mysql username ***/
$username = 'pressgym_admin';
/*** mysql password ***/
$password = '*******'; <-started out on purpose
try {
$dbh = new PDO("mysql:host=$hostname;dbname=pressgym_press", $username, $password);
/*** echo a message saying we have connected ***/
$qry = $dbh->prepare('INSERT INTO contact (Name, Email Address, Message, Date) VALUES (?, ?, ?, ?');
$qry->execute(array('Brandon', 'Brandon.braner#gmail.com', 'test message', '3.12.12'));
echo 'entry succesfull';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
describe contact;
Name varchar(255) NO PRI
EmailAddress varchar(255) NO
Message longtext NO
Date varchar(255) YES

The SQL syntax in your prepare command contains errors:
qry = $dbh->prepare('INSERT INTO contact (Name, Email Address, Message, Date) VALUES (?, ?, ?), ?');
should be
qry = $dbh->prepare('INSERT INTO contact (Name, `Email Address`, Message, Date) VALUES (?, ?, ?, ?)');

you have a syntax error. the following line
$qry = $dbh->prepare('INSERT INTO contact (Name, Email Address, Message, Date) VALUES(?, ?, ?), ?');
should be
$qry = $dbh->prepare('INSERT INTO contact (Name, Email Address, Message, Date) VALUES (?, ?, ?, ?)');
Update:
your column name Email Address contains a space escape it by using proper quote identifier like
INSERT INTO contact (Name, `Email Address`, Message, Date) VALUES (?, ?, ?, ?)'

Related

What's wrong with this SQL INSERT prepared statement? [duplicate]

This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Reference - What does this error mean in PHP?
(38 answers)
Why does this PDO statement silently fail?
(2 answers)
Closed 2 years ago.
I'm creating a user registration system for my website. I had this working code:
$sqlQuery = "INSERT INTO GH_users (firstname, surname, email, accountConfirmed, username, passwordHash)
VALUES ('$firstname', '$surname', '$email', 0, '$usernameSignup', '$passwordHash')";
$execute = $dbConn->exec($sqlQuery);
However, I found out that this invites the risk of SQL injection. Therefore, I have tried to use a prepared statement to prevent this but I am unable to get it to work. Codes that I've tried:
$sqlQuery = "INSERT INTO GH_users (firstname, surname, email, accountConfirmed, username, passwordHash)
VALUES (?, ?, ?, ?, ?, ?)";
$stmt = $dbConn->prepare($sqlQuery);
$stmt->bindParam($firstname, $surname, $email, 0, $usernameSignup, $passwordHash);
$stmt->execute();
$sqlQuery = "INSERT INTO GH_users (firstname, surname, email, accountConfirmed, username, passwordHash)
VALUES (?, ?, ?, 0, ?, ?)";
$stmt = $dbConn->prepare($sqlQuery);
$stmt->bindParam("sssss", $firstname, $surname, $email, $usernameSignup, $passwordHash);
$stmt->execute();
// These give the following error: PDOStatement::bindParam() expects at most 5 parameters, 6 given
// So I tried this:
$sqlQuery = "INSERT INTO GH_users (firstname, surname, email, accountConfirmed, username, passwordHash)
VALUES (?, ?, ?, 0, ?, ?)";
$stmt = $dbConn->prepare($sqlQuery);
$stmt->bindParam($firstname, $surname, $email, $usernameSignup, $passwordHash);
$stmt->execute();
// But this throws: PDOStatement::bindParam() expects parameter 3 to be long, string given
I'm not sure why these are throwing the errors given, especially the "expects parameter 3 to be long" as the email field is a string (varchar) data type. Can anyone help with this and explain what is wrong(accountConfirmed is a bit if it helps)?
UPDATE
I realised that I was receiving these errors because I was not using prepared statements and bound parameters in PDO. Thanks to #tadman and #user3783243 in the comment section, I was able to shorten my code by adding my parameters to execute() to do the binding instead of using bindParam() for each of the parameters.
SOLUTION
$sqlQuery = "INSERT INTO GH_users (firstname, surname, email, accountConfirmed, username, passwordHash)
VALUES (?, ?, ?, 0, ?, ?)";
$stmt = $dbConn->prepare($sqlQuery);
$stmt->execute(array($firstname, $surname, $email, $usernameSignup, $passwordHash));

MySQL not able to execute INSERT INTO [table]. Column count doesn't match value count at row 1

I'm trying to pull information from an HTML form and put this into a database using the following code:
$link = mysqli_connect("localhost", "user", "password", "MyDB");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "INSERT INTO interest (name, email, dob, address)
VALUES ('$fullname', '$email', '$dob' '$addr')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
}else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
mysqli_close($link);
It was working, and I've managed to get 2 test runs in, but now I'm getting the following error at the top of my submission page
ERROR: Could not able to execute INSERT INTO MyDB (name, email, dob,
address) VALUES ('test name', 'test#email.com', '2003-02-01'
'address'). Column count doesn't match value count at row 1
I have another variant of this which sends a PHP email, which is the file I'm using to base this database connection on.
There is also an autoincrement on ID column which is set as the primary key in the database if that makes a difference? SQL isn't my strong point unfortunately!
Given the syntax error you have in your query, being a missing comma in '$dob' '$addr'; you are open to an SQL injection and should be using a prepared statement.
Therefore, I am submitting this complementary answer for your own safety.
Here is an example of a prepared statement using the MySQLi API.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect('localhost', 'xxx', 'xxx', 'my_db');
if (!$link) {
die('Connect Error: ' . mysqli_connect_error());
}
// assuming these are the POST arrays taken from your HTML form if you're using one.
$fullname = $_POST['fullname'];
$email = $_POST['email'];
$dob = $_POST['dob'];
$addr = $_POST['addr'];
$sql = ("INSERT INTO interest (name, email, dob, address) VALUES (?, ?, ?, ?)");
$stmt = $link->prepare($sql) or die("Failed Execution");
$stmt->bind_param('ssss', $fullname, $email, $dob, $addr);
$stmt->execute();
echo $stmt->error;
echo "SUCCESS";
exit();
References:
How can I prevent SQL injection in PHP?
http://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php
http://php.net/pdo.prepared-statements
Foonotes:
If using the following failed because of the AI'd column:
$sql = ("INSERT INTO interest (name, email, dob, address) VALUES (?, ?, ?, ?)");
You may also try: (I used id as the AI'd column as an example)
$sql = ("INSERT INTO interest (id, name, email, dob, address) VALUES ('', ?, ?, ?, ?)");
This could be the case, as I have seen this type of SQL failure behaviour before.
You have missed comma here:
VALUES ('$fullname', '$email', '$dob' '$addr')
Thus (as it was clearly said in error text) column count doesn't mach values count.
It should be
VALUES ('$fullname', '$email', '$dob', '$addr')
You missed a comma
$sql = "INSERT INTO interest (name, email, dob, address)
VALUES ('$fullname', '$email', '$dob', '$addr')";
^here
You missed a comma:
VALUES ('$fullname', '$email', '$dob' '$addr')

Insering question marks('?') into the database rather than actual values

I'm making a registration form and I am using PHP bind parameters when inserting data into the database.
$fnameclean = mysqli_real_escape_string($mysqli_conn, $_POST['first_name']);
$passwordclean = mysqli_real_escape_string($mysqli_conn, hash("sha512", $_POST['password']));
$lnameclean = mysqli_real_escape_string($mysqli_conn, $_POST['last_name']);
$emailclean= mysqli_real_escape_string($mysqli_conn, $_POST['email']);
$stmt = $mysqli_conn->prepare("INSERT INTO user (firstname, surname, email, password) VALUES ('?', '?', '?', '?')");
$stmt->bind_param("ssss", $fnameclean, $lnameclean, $emailclean, $passwordclean);
$stmt->execute();
$stmt->close();
When I press the submit button, all I can see in my database are question marks in the fields: firstname, surname, email and password.
However, when I try to add information to the database without bind parameters it works perfectly fine
code:
$query1 = "INSERT INTO user (firstname, surname, email, password) VALUES ('$fnameclean', '$lnameclean', '$emailclean', '$passwordclean')";
$mysqli_conn->query($query1);
What am I doing wrong here?
VALUES (?, ?, ?, ?)
No ' to be used in query where you use ? for binding parameter. So your query should be like
$stmt = $mysqli_conn->prepare("INSERT INTO user (firstname, surname, email, password) VALUES (?, ?, ?, ?)");

php on duplicate key

I'm having trouble trying to get the following to work:
$stmt = $mysqli->prepare("INSERT INTO member_data (member_id, name, address, telephone, mobile) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE member_data SET name = ?, address = ?, telephone = ?, mobile = ? WHERE member_id = ?");
$stmt->bind_param('ssssssssss', $_SESSION['user_id'], $_POST['new_name'], $_POST['new_address'], $_POST['new_telephone'], $_POST['new_mobile'], $_POST['new_name'], $_POST['new_address'], $_POST['new_telephone'], $_POST['new_mobile'], $_SESSION['user_id']);
$stmt->execute();
$stmt->close();
It doesn't seem to be able to update or insert any values.
I'm sure I've done something wrong, but I've searched and haven't found anything relevant to my issue. Is this the right approach?
EDIT: Working code:
$stmt = $mysqli->prepare("INSERT INTO member_data (member_id, name, address, telephone, mobile) VALUES (?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE name = ?, address = ?, telephone = ?, mobile = ?");
$stmt->bind_param('sssssssss', $_SESSION['user_id'], $_POST['new_name'], $_POST['new_address'], $_POST['new_telephone'], $_POST['new_mobile'], $_POST['new_name'], $_POST['new_address'], $_POST['new_telephone'], $_POST['new_mobile']);

Issue On Inserting Auto Incremented ID in MySQL Using Prepared Statement

I have table in MySQL database called MyGuests which has 4 fields as : id (PK and Auto Increment), name,age and email. I am using following code to insert data from user input form to the database:
<?php
$sql = mysqli('localhost','user','password','database');
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
$query = $sql->prepare("INSERT INTO MyGuests ( id, name, age, email) VALUES (?, ?, ?, ?)");
$query->bind_param("isis",$name,$age,$email);
$query->execute();
?>
now I am confused how to insert value for id which is auto incremented field using the Prepared statement! As you can see I passed 4 parameters as (?, ?, ?, ?) for data entry and used the "isis" for bind_param(); but not sure what must put in $name,$age,$email for id?
Can you please help me to figure this out?
Thanks
Just omit the id in the query i.e.
INSERT INTO MyGuests ( name, age, email) VALUES (?, ?, ?)
It will automatically add the incremented id, hence the name :)
one more option is supplying null value to the auto-increment column:
ie.
instead of $query = $sql->prepare("INSERT INTO MyGuests ( id, name, age, email) VALUES (?, ?, ?, ?)"); use $query = $sql->prepare("INSERT INTO MyGuests ( id, name, age, email) VALUES (null, ?, ?, ?)");

Categories