Anna
Anna

Reputation: 53

PDO Still get result even if didn't bind any parameter

I was trying to produce some exception to test the function, so I didn't pass any array to $stmt->execute() on purpose, I expect to get an exception, or nothing (since no matching result) , but I still be able to fetch something and print it out???

    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sql='Select id from books where bookname=?';

    $stmt=$conn->prepare($sql);

    $stmt->execute();

    if($row=$stmt->fetch(PDO::FETCH_ASSOC)){

      print_array($row);  //print_array is a function can print out key and the value

    }  

it print out

[id] => 123 (just an example)

AND if I change the query to

'Select * from books where bookname= ?';

it print out the first row of data in the table.

I wonder what happen in between the execute() and fetch().... I tried those query directly in the phpmyadmin (that I can imagine how the query will be like when they arrive DB), but didn't get the same result.

Select id from books where bookname= ?
Select id from books where bookname= '?'
Select id from books where bookname= ''
Select id from books where bookname= ' '

PDO so far is full of surprise to me....

BTW I even var_dump($stmt->execute()) and it return true .

UPDATE:

I opened

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

and try to print out $conn->errorInfo()

and $stmt->errorInfo()

There was no error message. Still just got result back.

However, when I set $conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, TRUE);

I got PDOException:

SQLSTATE[HY093]: Invalid parameter number: no parameters were bound' in ...

If I turn off it, it just work anyway with or without an array in the execute().

but many articles want this attribute be false, for preventing SQL injection.

In my case set it false seem just to allow injection in someway.

Any thought ?

Upvotes: 1

Views: 48

Answers (2)

sectus
sectus

Reputation: 15464

You have executed other statement that you thought

$conn->prepare($sql); // there is no assign
$stmt->execute();

change it to

$stmt = $conn->prepare($sql); // there is assign
$stmt->execute();

Upvotes: 2

Marc B
Marc B

Reputation: 360792

PDO defaults to silent errors, e.g. returning boolean false on failure. Unless you EXPLICITLY turn on exceptions, it will never throw any.

And since your code doesn't check for return values, you'll never get any indication of failure, e.g.

$conn->prepare($sql) or die($conn:errorInfo);

would have told you something.

Try

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

to enable exceptions.

Upvotes: 0

Related Questions