0

I have some database classes that are using mysqli. For example:

class MyDB
{
    function __construct($db)
    {
        $this->db = $db;
    }

    function add($name)
    {
        $sql = "INSERT INTO mytable (name) VALUES ('$name');"
        $this->db->query($sql);
        if ($this->db->affected_rows) {
            return $this->db->insert_id;
        }

        return 0;
    }
...

I would like to test them with phpunit, using an sqlite in-memory database. However, as expected, I get this error:

Undefined property: PDO::$affected_rows

According to the documentation:

PDO is only required for the fixture clean- and set-up and for assertions. You can use whatever database abstraction you want inside your own code.

I suspect that just means that I have to create a wrapper for mysqli that is compatible with PDO. Or is there a way I can test my code without converting it to use PDO?

1 Answer 1

1

Mysqli objects and PDO objects are not compatible. You're passing a PDO object to code that's expecting a mysqli object. If you have mysqli code that you want to test, you have two choices:

  1. Use mysqli for the testing. This (as far as I know) rules out an in-memory database.
  2. Convert all your code to PDO. This allows you to pass any PDO object, be it MySQL, PostgreSQL, SQLite, whatever. That's kinda the point of using PDO.

I would not write a wrapper. That introduces unnecessary complexity that would itself need to be tested. And if you're going to expend that much effort, you may as well spend it converting to PDO.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.