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

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 (?, ?, ?, ?)");

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

bind_param doesn't replace ?s in my prepared statement

It registers the user successfully. But when I check it on my database, all of the values are 0s. What's the problem?
here's the function code:
public function insertUser($email, $firstName, $lastName, $encryptedPassword, $salt)
{
//SQL language - command to insert data
$sql = "INSERT INTO users (email, firstName, lastName, password, salt) VALUES (email=?, firstName=?, lastName=?, password=?, salt=?)";
//preparing SQL for execution by checking the validity
$statement = $this->conn->prepare($sql);
//if error
if (!$statement)
{
throw new Exception(($statement->error));
}
//assigning variables instead of '?', after checking the preparation and validity of the SQL command
$statement->bind_param('sssss', $email, $firstName, $lastName, $encryptedPassword, $salt);
//result will store the status/result of the execution of SQL command
$result = $statement->execute();
return $result;
}
The parameters for the function get set with the correct values when called, I tested it
I'm pretty new to PHP. If i correct my function, it doesn't create a new user. It doesn't even print out anything in the browser window. Here's the piece of code that calls this one (maybe it helps you with finding the solution):
$result = $access->insertUser($email, $firstName, $lastName, $encryptedPassword, $salt);
//result is positive
if ($result)
{
//throw back the user details
$return['status'] = '200';
$return['message'] = 'Successfully registered';
$return['email'] = $email;
$return['firstName'] = $firstName;
$return['lastName'] = $lastName;
echo json_encode($return);
$access->disconnect();
}
Your query is wrong.
//columns are declared here
$sql = "INSERT INTO users (email, firstName, lastName, password, salt) VALUES (email=?, firstName=?, lastName=?, password=?, salt=?)";
//you do not need to declare your columns again
Simple change your query to
$sql = "INSERT INTO users (email, firstName, lastName, password, salt) VALUES (?, ?, ?, ?, ?)";
Also, it appears as though you are storing your password and the salt separately, that tells me you are rolling your own hashing algorithm, there isn't really a need for this. I would remove your salt column, and use password_hash() for your password column.
remove the column=?
$sql = "INSERT INTO users (email, firstName, lastName, password, salt) VALUES (?, ?, ?, ?, ?)";
the code
column=?
in your value assignment is evalued as boolean condition that return false (0)

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, ?, ?, ?)");

PDO prepared statement, correctly used?

I just to need make sure I've got the PDO prepare statements correctly, will the following code be secured by SQL Injection?
$data['username'] = $username;
$data['password'] = $password;
$data['salt'] = $this->generate_salt();
$data['email'] = $email;
$sth = $this->db->prepare("INSERT INTO `user` (username, password, salt, email, created) VALUES (:username, :password, :salt, :email, NOW())");
$sth->execute($data);
Yes, your code is safe. It can be shortened however:
$data = array( $username, $password, $this->generate_salt(), $email );
// If you don't want to do anything with the returned value:
$this->db->prepare("
INSERT INTO `user` (username, password, salt, email, created)
VALUES (?, ?, ?, ?, NOW())
")->execute($data);
You could start with an empty array for your $data like
// start with an fresh array for data
$data = array();
// imagine your code here
Your code looks good so far.
EDIT: I missed your NOW() call. Imho you should add it with a bind variable as well, like
// bind date
$data['created'] = date("Y-m-d H:i:s");
// updated prepare statement
$sth = $this->db->prepare("INSERT INTO `user` (username, password, salt, email, created) VALUES (:username, :password, :salt, :email, :created)");

php pdo insert statement not working

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 (?, ?, ?, ?)'

Categories