-1

I have a database named myshop in MySQL. I am trying to create an html page (http://pastie.org/10568087) where a user enters a first name and then the php page takes that first name and looks for the name in the database and echoes it.

<?php
$firstName = $_POST["firstname"];
try {
    $dbh = new PDO('mysql:localhost=localhost;dbname=myshop', "root", "mypassword");
    $rows = $dbh->query("SELECT * FROM people WHERE firstname = $firstName");

    foreach ($rows as $row) {
        echo "First Name:  " . $row["first_name"] . "<br/>";
    }
} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}
?>

I can echo all the names when I remove "WHERE firstname = $firstName". But that's not what I want, I just want the name. There is no need to create new input. What's the problem?

Jesse Kernaghan
  • 4,544
  • 2
  • 18
  • 25
Zee
  • 31
  • 3
  • Having used proper error handling... http://php.net/manual/en/pdo.error-handling.php and http://php.net/manual/en/function.error-reporting.php – Funk Forty Niner Nov 19 '15 at 19:05

1 Answers1

0

Try

"SELECT * FROM people WHERE firstname = '{$firstName}'"

I have quoted the posted text ($firstName) so that its treated as a sting in the query.

Danila Ganchar
  • 10,266
  • 13
  • 49
  • 75
  • 2
    Lovely; leaving them open to a sweet 'ol SQL injection. *Try*.... those belong in comments. – Funk Forty Niner Nov 19 '15 at 19:08
  • @Zee you must use [bind param](http://php.net/manual/en/pdostatement.bindparam.php). It will be safe. – Danila Ganchar Nov 19 '15 at 19:18
  • @Fred-ii- Ofcourse its open to SQL injection right now but the solution was to the problem. The questioner was unable to get the result. The solution was to get the result. Rest, SQL injection is advice. –  Nov 19 '15 at 19:22
  • I was wondering if you can use "where" twice. Like if the user wants to enter a first and last name. How can you echo a matching first and last name from the database instead of a first name only? – Zee Nov 19 '15 at 19:22