-1

I try to select data from a database, but I'm unable to get it when I have two parameters after the WHERE.

Code that works:

$conn = null;
$host = 'localhost';
$db   = 'database';
$user = 'root';
$pwd  = 'root';

$auth = 'EP';
$nr = 2007;

try {
    $conn = new \PDO('mysql:host='.$host.';dbname='.$db, $user, $pwd);      
    $stmt = $conn->prepare('SELECT family FROM table WHERE nr = :nr');
    $stmt->execute(array('nr' => $nr));

    while($row = $stmt->fetch(PDO :: FETCH_ASSOC)) {
        echo '<pre>';
        print_r($row);
        echo '</pre>';
    }
}
catch(PDOException $e) {
    echo 'ERROR: ' . $e->getMessage();
}

but when I use following select it doesn't work:

SELECT family FROM table WHERE auth = :auth AND nr = :nr

I think it's a problem in the line

    $stmt->execute(array('nr' => $nr));

When I do the following I have no result on the screen:

    $stmt->execute(array('nr' => $nr, 'auth' => $auth));

Has anybody an idea what I'm doing wrong?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Aloysia de Argenteuil
  • 833
  • 2
  • 11
  • 27

1 Answers1

0

CHANGE THIS

stmt->execute(array('nr' => $nr, 'auth' => $auth));

TO

$stmt->execute(array(':nr' => $nr, ':auth' => $auth));

: is a small typo error but PDO is Serious :( and the parameters will be empty.

CS GO
  • 914
  • 6
  • 20
  • 1
    This is incorrect - internally a colon will be added to the parameter if it's missing (https://github.com/php/php-src/blob/PHP-5.5/ext/pdo/pdo_stmt.c#L363) – dave Nov 02 '14 at 14:34
  • @dave But if i didn't add a colon PHP throws error :( why would be that ? – CS GO Nov 02 '14 at 14:37
  • Hey @AncientGeek, I followed you, but still no array on screen. Only when I use just $nr... The select in phpmysql works just fine... – Aloysia de Argenteuil Nov 02 '14 at 16:30
  • Example 2 of PHP Tutorial says the same: http://php.net/manual/en/pdostatement.execute.php It should work. @dave in the Manual it shows the solution of Ancient Geek. Is this really incorrect as you say? – Aloysia de Argenteuil Nov 02 '14 at 16:32
  • 1
    @AloysiadeArgenteuil - I linked to the PHP source code - I'm 100% sure it adds the colon for you if it's not there. – dave Nov 03 '14 at 02:38