Search code examples
phppdo

mysql_query to PDO


I have the following code in the old "mysql_query"

$query = mysql_query("SELECT defe FROM information WHERE term = 1");
$fetch = $db->fetch_array($query);
print_r($fetch);

I want to transform this to the PDO way of retrieving information from database. I tried the following (did not work- does not display any result) :

$query = $db->prepare('SELECT defe FROM information WHERE term = 1');
$fetch = $query->fetch();
print_r($fetch);

the connection to the database is established and it stored in the $db variable (only the PDO).


Solution

  • You have to execute the query

    $query = $db->prepare('SELECT defe FROM information WHERE term = 1');
    $query->execute();
    $fetch = $query->fetch();
    print_r($fetch);
    

    You can also use PDO::query since you aren't using any parameters in your query

    $query = $db->query('SELECT defe FROM information WHERE term = 1');
    $fetch = $query->fetch();
    print_r($fetch);