Jump to content

Recommended Posts

Hi. I am a little confused about PDO, its classes and the general oop aspects of it. If you at the below code:

 

<?php

try {
$handler = new PDO('mysql:host=127.0.01;dbname=app', 'root','');
$handlser->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

}catc(PDOException $e) {
echo $e->getMessage():
die();

}

$query = $handler->query('SELECT * FROM table');

while($r = $query->fetch(PDO::FETCH_OBJ)) {

echo $r->message;

}

What's confusing me is that the fetch method is a method within the PDOSTATEMENT class so how come an object hasn't been created before hand in order to use the method? Furthermore it appears the method is a static method within the PDOSTATEMENT class so how come the double semi colon is being used such as: PDOSTATEMENT::FETCH?

Any help would be appreciated. Thanks.

Link to comment
https://forums.phpfreaks.com/topic/289313-pdo-and-fetch-method/
Share on other sites

 

 

What's confusing me is that the fetch method is a method within the PDOSTATEMENT class so how come an object hasn't been created before hand in order to use the method?

Because the PDO::Query method returns the PDO Statement Object.

 

 

 

Furthermore it appears the method is a static method within the PDOSTATEMENT class so how come the double semi colon is being used such as: PDOSTATEMENT::FETCH?

I think you're confused here. The fetch() method is not a static method, it is a public method that belongs to the PDO Statement Object.

 

 PDO::FETCH_OBJ on the other-hand is a static constant which returns the value of the FETCH_OBJ constant from the PDO class. This constant tells the fetch() method how you want the records in the record set represented as. In your case it'll be in a standard object form. Other types could be an associative array (PDO:FETCH_ARRAY), or as a numerically index array (PDO::FETCH_ROW).

Because the PDOStatement instance is returned by the query() method. Check your code: You call query(), put the return value into the $query variable and then call $query->fetch(). So $query is obviously an object. If you inspect the variable, you'll see that it's indeed an instance of PDOStatement.

 

The rest of the code doesn't make a lot of sense, though.

  • What's the weird try statement supposed to do? Do you realize that exceptions by default halt the script and send the error message to the appropriate device? What's the point of catching the exception only to manually halt the script and print the error message? Also, do you really think it's a good idea to show your internal database errors on the website? In general: Don't catch an exception unless you actually know how to handle it.
  • PDO needs to be configured. At the very least, you should turn on prepared statements and specify the character encoding. Otherwise, you'll easily end up with security vulnerabilities or broken characters respectively. It's also a good idea to define the default fetch mode.
  • This while loop stuff is no longer needed. You can simply use a foreach loop.

Using PDO properly might look something like this:

<?php

$database = new PDO('mysql:host=YOURHOST;dbname=YOURDB;charset=utf8mb4', 'YOURUSER', 'YOURPASSWORD', array(
    // we want actual prepared statements, not client-side escaping
    PDO::ATTR_EMULATE_PREPARES => false,
    // turn on exceptions
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    // fetch associative arrays by default
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
));

// a constant query
$blogEntriesStmt = $database->query('
    SELECT
        blog_entry_id,
        content
    FROM
        blog_entries
');

foreach ($blogEntriesStmt as $blogEntry)
{
    echo '<p>' . htmlEscape($blogEntry['content']) . '</p>';
}

// a prepared statement
$category = 1;
$categoryEntriesStmt = $database->prepare('
    SELECT
        blog_entry_id,
        content
    FROM
        blog_entries
    WHERE
        category = :category
');
$categoryEntriesStmt->execute(array(
    'category' => $category,
));

foreach ($categoryEntriesStmt as $blogEntry)
{
    echo '<p>' . htmlEscape($blogEntry['content']) . '</p>';
}

I'm using an example of someone else's code and it's not the complete code.

 

 

Because the PDOStatement instance is returned by the query() method. Check your code: You call query(), put the return value into the $query variable and then call $query->fetch(). So $query is obviously an object. If you inspect the variable, you'll see that it's indeed an instance of PDOStatement.

 


 

 

Yes I agree with that but I thought first in order to use the query() method from the PDOStatement class you first need to instantiate the class such as:

 

$object = new PDOSTATEMENT;

 

$object->query()

 

 

The only class that has been instantiated as far as I can see is the PDO class which is not the PDOSTATEMENT class.

Yes I agree with that but I thought first in order to use the query() method from the PDOStatement class you first need to instantiate the class such as:

The query method is part of the PDO class, which you have instantiated. That method will run the query and then instantiate a new PDOStatement object and return that back to you so that you can access the results.

Edited by kicken

Well I should have explained at the start that I am knew to object-oriented programming. I didn't think methods from one class could create an instance of another class. I thought for each class you have to specifically create an object by using the "new" key word.

i have to ask, did you read the documentation for the pdo ->query() method? it states three different times what it returns -
 

PDO::query — Executes an SQL statement, returning a result set as a PDOStatement object


Description
....
 
PDO::query() executes an SQL statement in a single function call, returning the result set (if any) returned by the statement as a PDOStatement object.


Return Values
PDO::query() returns a PDOStatement object, or FALSE on failure.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.