Why won't this PDO code INSERT? - php

$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.

Related

mysqli conversion PDO

How can I turn this to PDO? I tried, but I don't know how.
It was MySQLi at first and I tried to turn it to PDO and so, that was the result:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $conn-> prepare("SELECT * FROM resident WHERE '$username' = ? AND '$password' = ?");
//mysqli_stmt_bind_param($sql, "ss", $username, $password);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt ->execute();
mysqli_stmt_store_result($sql);
$stmt-> BindParam($sql, $name, $username, $password);
$response=array();
$response["succes"] = false;
while (mysqli_stmt_fetch($sql)) {
$response["success"] = true;
$response["name"]= $name;
}
echo json_encode ($response);
?>
You're confusing variables with column names. It's extremely important to note the difference. In a query '$username' is a string with a value in it, and probably a SQL injection bug. username without quotes is probably a column name.
You're also using named placeholders but you haven't named them. ? is an unnamed one. If you want a placeholder named :x then :x must appear in the query.
Your fixed code should look like:
$stmt = $conn-> prepare("SELECT * FROM resident WHERE username=:username AND password=:password");
//mysqli_stmt_bind_param($sql, "ss", $username, $password);
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt ->execute();
That is technically functional but VERY, VERY WRONG. Passwords must be properly hashed using, at the absolute least, password_hash. If you do that you can no longer fetch based on username and password, you need to fetch based on username and use password_verify to check if it's correct or not.
Disclaimer: Don't Write Your Own Login System
Unless this is strictly for academic purposes, all of this code is pretty much a waste of time. Any development framework has a solution for this. One example is Laravel where out of the box you get a full-featured authentication system.
You can use answer of tadman, also this:
$stmt = $conn-> prepare("SELECT `id` FROM resident WHERE username=:username AND password=:password");
$stmt->execute(array(':username' => $username, ':password' => $password);
And hash your passwords.
You can learn some basics of pdo Here, W3schools

$mysqli->prepare returns false if data fields are blank

There are 4 fields in the form and 2 of them are allow null, so if a user doesn't fill those fields, INSERT would fail as $mysqli->prepare will return false.
Email address and phone number are not cumpolsary in following form.
So, is there any way to send the blank fields and still insert the data for other filled fields.
function newcontact()
{
$mysqli = connect();
$query = "INSERT INTO contacts( first_name, last_name, email, phone_no, contact_by )Values( '$this->first_name', '$this->last_name',
'$this->email', $this->phone, $this->user_id)";
//die( $query );
$stmt = $mysqli->prepare( $query );
if( $stmt->execute() )
{
$mysqli->close();
return true;
}
}
if user don't fill these fields, not NULLS but empty strings will be put into query.
and thus cause syntax error, as Values('', '', '', , ) is a sure error.
you are using prepare wrong way.
you don't have mysqli error reporting set
Add this line right before mysqli_connect
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
and make your query actually use placeholders and bind param.
And everything will work. Yet if not, you will be notified of the exact error.
when using an prepared statement you don't put the values in the query you provide placheholders instead and bind the parameters.
http://php.net/manual/en/mysqli.prepare.php
if you want to put the values in the query use the function query()
http://www.php.net/manual/en/mysqli.query.php

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

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.

PDO: Problems with binding, all queries return false

I cannot for the life of me get binding to work with PDO queries, they always return false.
On this example, it checks that the value of a field is between 2 other values.
This works:
$query = $db->query("SELECT * FROM table WHERE field1 > '$start' AND field1 < '$finish'");
This doesn't:
$query = $db->query("SELECT * FROM table WHERE field1 > :start AND field1 < :finish");
$query->bindParam(":start", $start);
$query->bindParam(":finish", $finish);
UPDATE: The above query now works thanks to the help. The following still doesn't.
I have been trawling through various PDO posts on here but I have not found a solution, and I don't know what else to try.
UPDATE2: Okay, it seems it is not finding $db and therefore not connecting and returning false. The $db connection line is in a connect.php file that is required on all main pages. The content on those pages is called by a function that then includes the relevant file/page. Because PDO does not work by itself in functions, is it losing the $db through the function to include the file containing the query? I may not have explained myself clearly enough.
Basically, example function in functions.php:
function getRegistration() {
include("registration.php");
}
main.php
require_once("connect.php");
require_once("functions.php");
getRegistration();
registration.php contains:
$sql = $db->prepare("INSERT INTO tempus_members(username, email, password, activation_code, registration_date, registered_ip, name) VALUES(:username, :email, :password, :activation_code, :registration_date, :registered_ip, :name)");
$sql->bindParam(":username", $username);
$sql->bindParam(":email", $email);
$sql->bindParam(":password", $hash);
$sql->bindParam(":activation_code", $activation_code);
$sql->bindParam(":registration_date", $registration_date);
$sql->bindParam(":registered_ip", $registered_ip);
$sql->bindParam(":name", $name);
$sql->execute();
Is it losing the $db variable through the function to include the page? If so, how do I carry $db through all functions?
Try:
$stmt = $db->prepare("SELECT * FROM table WHERE field1 > :start AND field1 < :finish");
$stmt->bindParam(":start", $start);
$stmt->bindParam(":finish", $finish);
$stmt->execute();
You were using PDO::query instead of PDO::prepare.
As for the other query, what errors are you getting back? Try the following code and see if any errors are spit out onto the page:
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try{
$sql = $db->prepare("INSERT INTO tempus_members(username, email, password, activation_code, registration_date, registered_ip, name) VALUES(:username, :email, :password, :activation_code, :registration_date, :registered_ip, :name)");
$sql->bindParam(":username", $username);
$sql->bindParam(":email", $email);
$sql->bindParam(":password", $hash);
$sql->bindParam(":activation_code", $activation_code);
$sql->bindParam(":registration_date", $registration_date);
$sql->bindParam(":registered_ip", $registered_ip);
$sql->bindParam(":name", $name);
$sql->execute();
}
catch(PDOException $e){
echo $e->getMessage();
}

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

Categories