How can I get PDO bindValue/bindParam to bind with MySQL? - php

I've been using mysql and mysqli in the past, but am starting a new project, so wanted to go back to OOP with PDO-mysql .. however, it doesn't want to work:
$dbh = new PDO('mysql:host='.$host.';dbname='.$database, $username, $password);
if(isset($_POST["name"]) && isset($_POST["password"]))
{
$pwdHasher = new PasswordHash(8, FALSE);
$hash = $pwdHasher->HashPassword($_POST["password"]);
//$insert = $dbh->prepare('insert into users (username,password) values ("?","?")');
$insert = $pdo->prepare("insert into users (username,password) values (?,?)");
$insert->bindParam(1,$_POST["name"]);
$insert->bindParam(2,$hash);
$insert->execute();
echo "Registration Success!";
}
edit: The above code works if I change the code from the commented line to the non-commented (i.e. single quote to double quotes) However, this doesn't work later:
$query = $pdo->prepare("select * from users where username = ?");
$query->bindParam(1,$_POST["name"]);
$result = $query->execute()

Ok, you've found the answer to your first question.
For the second one it would be
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
called right after connect.
it will tell you what's going wrong with your query.
error_reporting(E_ALL);
also always helps with such errors like misspelled variables ($pdo is not $dbh for example)

If you want to use ? for placeholders, you are supposed to send an array to the execute-method matching the positions of the question marks. $insert->execute(array('value1', 'value2'));
You could however use named placeholders .. WHERE x = :myxvalue and use $insert->bindValue(':myxvalue', 'thevalue', PDO::PARAM_STR);
Also, please have a look at the difference between bindParam and bindValue

The answer to this question is simple and embarrassing:
I need to change the single quotes surrounding the sql statement being prepared to double quotes (and remove the double quotes where the '?' mark is.
change:
$insert = $dbh->prepare('insert into users (username,password) values ("?","?")');
to
$insert = $dbh->prepare("insert into users (username,password) values (?,?)");
and everything works.

Related

MySQLi insert, successful database connection but not successfully inserted [duplicate]

This question already has answers here:
How to include a PHP variable inside a MySQL statement
(5 answers)
Closed 2 years ago.
I'm attempting to insert some data into a table using mysqli functions.
My connection works fine using the following:
function connectDB(){
// configuration
$dbuser = "root";
$dbpass = "";
// Create connection
$con=mysqli_connect("localhost",$dbuser,$dbpass,"my_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return false;
}else{
echo '<br />successfully connected<br />';
return $con;
}
}
But when I attempt to run my insert function I get nothing in the database.
function newUserInsertDB($name,$email,$password){
$con = connectDB();
// Prepare password
$password = hashEncrypt($password);
echo $password . "<br />";
// Perform queries
mysqli_query($con,"SELECT * FROM users");
mysqli_query($con,"INSERT INTO users (name,email,password,isActivated) VALUES ($name,$email,$password,0)");
// insert
mysqli_close($con);
}
I have been looking through the list of mysqli functions for the correct way to give errors but they all seem to be regarding the connection to the DB, not regarding success of an insert (and I can clearly see in my DB that it is not inserting.)
What would be the best way to debug? Which error handling shall I use for my insert?
I've tried using mysqli_sqlstate which gives a response of 42000 but I cannot see any syntax errors in my statement.
As mentioned in my comment, you would be better off using a prepared statement. For example...
$stmt = $con->prepare(
'INSERT INTO users (name, email, password, isActivated) VALUES (?, ?, ?, 0)');
$stmt->bind_param('sss', $name, $email, $password);
$stmt->execute();
Using this, you don't have to worry about escaping values or providing quotes for string types.
All in all, prepared statements are much easier and much safer than attempting to interpolate values into an SQL string.
I'd also advise you to pass the $con variable into your function instead of creating it within. For example...
function newUserInsertDB(mysqli $con, $name, $email, $password) {
// Prepare password
$password = hashEncrypt($password);
// functions that "echo" can cause unwanted side effects
//echo $password . "<br />";
// Perform queries
$stmt = $con->prepare(
'INSERT INTO users (name, email, password, isActivated) VALUES (?, ?, ?, 0)');
$stmt->bind_param('sss', $name, $email, $password);
return $stmt->execute(); // returns TRUE or FALSE based on the success of the query
}
The quotes are missing from the mysql statement from around the values. Also, you should escape the values before inserting them into the query. Do this way:
mysqli_query($con,"INSERT INTO users (name,email,password,isActivated) VALUES ('".
mysqli_real_escape_string($con,$name)."','".
mysqli_real_escape_string($con,$email)."','".
mysqli_real_escape_string($con,$password)."',0)");
Regards

Why won't this PDO code INSERT?

$sql = $db->prepare("INSERT INTO users (user_username, user_password, user_email) VALUES ($username, $password, $email)");
$sql->bindParam(':user_name', $username);
$sql->bindParam(':user_password', $password);
$sql->bindParam(':user_email', $email);
$sql->execute();
I'm trying to learn PDO rather than using mysql_ but I'm running into a problem. This doesn't seem to be inserting and I'm not sure why.
I'm not getting any error messages either so I don't know what to Google.
Also, is the $db variable being in an included file (config.php which has all the database details) a problem?
Try -
$sql = $db->prepare("INSERT INTO users (user_username, user_password, user_email) VALUES (:user_name, :user_password, :user_email)");
$sql->bindParam(':user_name', $username);
$sql->bindParam(':user_password', $password);
$sql->bindParam(':user_email', $email);
$sql->execute();
Use :user_name, ... in your $db->prepare() not $username, ...
First thing's first, when you're developing turn on error reporting so you can see any error messages.
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
Executing the code you have should be producing some sort of error because you are trying to bind to parameters that don't exist. Named parameters need to start with a : or if you would just prefer placeholder type parameters, you can use ? instead. When you do:
...VALUES ($username, $password, $email)"
The variables will be parsed into their actual values:
...VALUES (bob, $2y$14$youarehashingpasswordsright, bob#gmail.com)"
which of course, would be a syntax error in your SQL. Instead, you need to put their parameter names:
......VALUES ( :username , :password , :email )"
Then if that doesn't work, look at any errors being produced and make sure the queries are actually being committed.

prepared statement using bindValue not working

I'm new to PHP and I'm trying to get a prepared statement to work. Its for my final year project at university and I remember reading that prepared statements are good practice and also good for SQL injections. However the following code gives me a Server 500 error.
<?php
$email = "blah#blah.co.uk";
$hash = "somerandomhashedpassword";
$db = new mysqli("localhost", "root", "1234", "UEAnetwork");
$sql = "INSERT INTO Students (Email, Password) VALUES (?,?)";
$stmt = $db->prepare($sql);
$stmt->bindValue(1, $email);
$stmt->bindValue(2, $hash);
if ($stmt->execute()) {
echo "You have registered!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
}
?>
If I run the following then a row is inserted, so I'm pretty sure I'm connecting to the database properly.
<?php
$db = new mysqli("localhost", "root", "1234", "UEAnetwork");
$sql = "INSERT INTO Students (Email, Password) VALUES ('blah#blah.co.uk','somerandomhashedpassword')";
$stmt = $db->prepare($sql);
if ($stmt->execute()) {
echo "You have registered!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
}
?>
Am I using bindValue incorrectly? I've seen it used this way in many tutorials online but I must be doing something wrong.
mysqli has a very different API than PDO. There is no mysql_stmt::bindValue. You want to use mysql_stmt::bind_param, but the syntax is quite different:
$stmt->bind_param('ss', $email, $hash);

PDO and alphanumeric strings?

The current error when running this from the command line is "Call to a member function bindParam() on a non-object" which I've worked out to being a problem with the variable $orderPO. Something does not like non-numeric characters which led me to the bindParam PARAM_STR business which does not work either. The database fields are both varchar 50.
My search skills are failing me. I know this must be posted somewhere about a million times but I can't seem to find it. I am completely open to doing this another way if someone has a better idea.
Current attempt code:
try
{
$orderNum = '123456';
$orderPO = '123456-A';
$dbh = new PDO("mysql:host=localhost;dbname=dbname", 'someuser', 'somepass');
$stm = $dbh->prepare("insert into some_table (order_number, order_po)");
$stm->bindParam(':order_number', $orderNum, PDO::PARAM_STR);
$stm->bindParam(':order_po', $orderPO, PDO::PARAM_STR);
$stm->execute();
print_r($stm);
print_r($dbh);
$arr = $stm->errorInfo();
print_r($arr);
$stm->closeCursor();
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
In order to bind parameters using PDO, you will need to use placeholders, like this:
$stm = $dbh->prepare("
INSERT INTO `some_table` SET
`order_number` = :order_number,
`order_po` = :order_po
");
$stm->bindParam(':order_number', $orderNum, PDO::PARAM_STR);
$stm->bindParam(':order_po', $orderPO, PDO::PARAM_STR);
Notice the inclusion of the : character before the named placeholder. I also added column names to your query.
Read further and see examples: PDO bindParam
The correct syntax is
$stm = $dbh->prepare("insert into some_table (order_number, order_po) VALUES (?, ?)");
$stm->bindParam(1,$orderNum);
$stm->bindParam(2,$orderPO);
include the questions marks, the numbers in the bindParam call refer to which question mark you're binding the parameter to
You are trying to use bindparam, but bind param matches ? not cursors :. You have not included any parameters or values.
Also, you are missing your VALUES statement within the query, which is causing the query to fail. This is why you get the "Call to a member function bindParam() on a non-object"
To use the :value syntax, use bindValue, not bindParam. to use bindParam, switch the :value to ? in your query and number them in order is your execute array.
try
{
$orderNum = '123456';
$orderPO = '123456-A';
$dbh = new PDO("mysql:host=localhost;dbname=dbname", 'someuser', 'somepass');
$stm = $dbh->prepare("insert into some_table (order_number, order_po) VALUES (:order_number, :order_po)");
$stm->bindvalue(':order_number', $orderNum, PDO::PARAM_STR);
$stm->bindvalue(':order_po', $orderPO, PDO::PARAM_STR);
$stm->execute();
print_r($stm);
print_r($dbh);
$arr = $stm->errorInfo();
print_r($arr);
$stm->closeCursor();
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}

Make Pdo Preserve Backslash

Basically i want to store a path to an image into the database
Example:I want to save 'C:\wampp\www\project\images' into database
Instead Pdo remove all the backslash and make it into 'C:wamppwwwprojectimages'
Is there a way to make Pdo keep the backslash?
Update with code:
$sql = "INSERT INTO meal (pic_path) VALUES('C:\wamp\www\project')";
$db = new PDO( $dsn, $username, $password );
$stmt = $db->prepare( $sql );
$stmt->execute();
The reason that this is happening is because you're using double quotes (") around your query, and since the back slash (\) is the escape character, it's being dropped. You can fix this by placing two back slashes together so it will yield one (C:\\wamp\\www\\project).
However, Passing it to prepare as an argument would be a better idea, and you can keep the double quotes.
$directory = "C:\wamp\www\project";
$sql = "INSERT INTO meal (pic_path) VALUES(?)";
$db = new PDO( $dsn, $username, $password );
$stmt = $db->prepare( $sql );
$stmt->execute(array($directory));
Read more about prepared statements.
You should use PDO's variable substitution to safely insert values into the database. To edit your code, it would look like this:
$sql = "INSERT INTO meal (pic_path) VALUES(?)";
$db = new PDO( $dsn, $username, $password );
$stmt = $db->prepare( $sql );
$stmt->execute(array('C:\wamp\www\project'));
PDO will replace the ? in your query with the escaped version of the string you pass.

Categories