0

I'm not very good in OOP PHP but I'm learning by coding a backend for one of my existing websites written in procedural PHP.

I decided to do everything in proper way (or at least try to). So for the DB connection I learned mysql functions are (almost) deprecated now. So I went with PDO_Mysql.

My class class.entry.php

class Entry
{

    public function __construct() {

    }


    public function getLatestEntries()
    {
        try {

            $options = array(
                PDO::ATTR_PERSISTENT => true,
                PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
            );

            $db = new PDO("mysql:host=localhost;port=3306;dbname=xxxx", "xxxx", "******", $options);
            $stmt = $db->prepare(" SELECT xxx, yyy, zzz FROM tttt ORDER BY f_vrijeme DESC LIMIT 100 ");
            $stmt->execute(array());

            return $stmt->fetchAll(PDO::FETCH_OBJ);

        } catch (PDOException $e) {

            echo "Error: " . $e->getMessage();

        }
    }

}

My view file (calling it view although this is not MVC) - generating a row of data with a foreach loop:

$e = new Entry();
$rows = $e->getLatestEntries();

foreach ($rows as $row){ ?>

    <tr>
        <td><?php echo $row->f_id ?></td>
        <td><?php echo $row->_F_IME ?></td>
        <td><?php echo $row->_F_GRAD ?></td>
        <td><?php echo $row->_F_TEL ?></td>
    </tr>
<?php } ?>

Now, I'm OK with what I have in the view file - but I'm wondering do I have to initialize the Entry object like this in order to be able to call the function?

Regarding the class, I feel there should be a way of keeping at least this:

$options = array(
    PDO::ATTR_PERSISTENT => true,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"
);

$db = new PDO("mysql:host=localhost;port=3306;dbname=xxxx", "xxxx", "******", $options);

in one spot so that it serves all the methods I will eventually have in the class.

Or, what is the preferred way of having such a connection class so i can define all the stuff there and then just to include connections in my classes and then just do:

$stmt = $db->prepare(" SELECT xxx, yyy, zzz FROM tttt ORDER BY f_vrijeme DESC LIMIT 100 ");

as needed.

Passerby
  • 9,184
  • 2
  • 28
  • 44
developer10
  • 1,390
  • 2
  • 13
  • 30
  • 1
    Maybe try reading this: [How Not To Kill Your Testability Using Statics](http://kunststube.net/static/), this may get you towards the right mindset. – deceze Feb 12 '14 at 11:18
  • Thank you, that gave me useful advice, I will try to apply it. Nice article, I noticed it's yours. – developer10 Feb 12 '14 at 13:42
  • You might find this somewhat useful: http://stackoverflow.com/q/11369360/727208 – tereško Feb 12 '14 at 16:30

0 Answers0