-1

In a registration script, an error keeps popping up. The code is as such:

try {

 $dbh = new PDO("mysql:host=$hostname;dbname=booter", $username, $password);

    echo 'Connected to database<br />';

/*** INSERT data ***/
$count = $dbh->exec("INSERT INTO members(username, password, email) VALUES ('$_POST['username']', '$hashedpassword', '$_POST['email']')");


/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}

Any fixes for this (as well as any tips to help with security) would be very much appreciated.

tmello01
  • 89
  • 1
  • 2
  • 11
  • 2
    If you switch to an IDE (e.g. NetBeans, Eclipse, PHP Storm) then the line containing the syntax error will be highlighted for you in the editor automatically. – halfer Mar 28 '15 at 15:27

1 Answers1

2

The problem is with this line:

('$_POST['username']', '$hashedpassword', '$_POST['email']')

which are the quotes inside the POST arrays which need to be removed.

However, this isn't safe at all and you should be using prepared statements, as it leaves you open to SQL injection.

First assign variable to POST arrays:

$username = $_POST['username'];
$hashedpassword = "The way you're getting this from";
$email = $_POST['email'];

Then using prepared statements using ? for placeholders:

$query= "INSERT INTO members (username, password, email) VALUES (?, ?, ?)";
$result = $dbh->prepare($query);
$count = $result->execute(array($username, $hashedpassword, $email));

More on PDO prepared statements can be seen by visiting:


Footnotes:

I noticed in another question you posted https://stackoverflow.com/q/29177454/ that you are using mysqli_ functions.

If you are still using mysqli_ to connect with or mysqli_ functions exist elsewhere in your code, you cannot mix MySQL APIs.

Community
  • 1
  • 1
Funk Forty Niner
  • 73,764
  • 15
  • 63
  • 131
  • Thank you for your advice! The error has been fixed and prepared statements have been implemented. And no, after my last question I switched from mySQLi to PDO. – tmello01 Mar 28 '15 at 15:34
  • @tmello01 You're welcome and I'm glad to hear that I was able to solve the question, *cheers* – Funk Forty Niner Mar 28 '15 at 15:39