PDO, MySQL SELECT statement returning boolean true?
Just using a SELECT in my MySQL statement, trying to get a column.
$last_visit = $db->prepare( 'SELECT `last_visit` FROM `开发者_JAVA技巧visitors` WHERE `ip` = :ip' )
->execute( $arr_ip );
var_dump( $last_visit );
The output of var_dump is bool(true)
instead of the data I need. Trying ->fetch()
only throws an error.
What can I do? This is holding up my whole project, and I can't figure out what's wrong no matter where I look. The correct data is in the database, the connection is correct and INSERT works.
as said in the documentation, execute()
returns a boolean. take a look at the eamples for fetch() to see how your should use PDO.
In your case, the code should look like this:
$stmt = $db->prepare( 'SELECT `last_visit` FROM `visitors` WHERE `ip` = :ip' );
$stmt->bindParam(':ip', $arr_ip);
$stmt->execute();
if($row = $stmt->fetch()){
$last_visit = $row['last_visit'];
}else{
// whatever you like to do if there's no result...
}
EDIT:
additional information in response to your comment:
For an UPDATE
or DELETE
, you can do a one-liner like your example, because you may not need the result (or rather just true
/false
to see if the request was successful).
For a SELECT
, you need to fetch()
the result. You can leave bindParam()
out and give the params to execute, like you tried, but without a fetch()
, you wont get your results.
精彩评论