tags:

views:

124

answers:

2

I have written the following db interface class:

<?php

// dbinterface.php

class db {
    private $con;
    private $host;
    private $user;
    private $pass;
    private $database;
    private $error;

    function db($host, $user, $pass, $database) {
     $this->con = mysql_connect($host, $user, $pass);
     mysql_select_db($database);
    }

    function escape($text) {
     return mysql_real_escape_string($text);
    }

    function run($query) {
     $q = mysql_query($query);
     if ($q === false) {
      $this->error = "Error " . mysql_errno() . ": " . mysql_error($this->con);
      return false;
     } elseif ($q === true) {
      return true;
     } else {
      $result = array();
      while ($row = mysql_fetch_assoc($q)) {
       array_push($result, $row);
      }
      return $result;
     }
    }

    function get_error() {
     return $this->error;
    }

    function cose() {
     mysql_close($this->con);
    }
}


?>

The problem is that for some reason, when i try to run a query with it, I get the error: No database selected. But my code selects it in the constructor. I checked and made sure i was passing the correct db name. and i made sure it was actually getting passed.

A: 

This class works fine for me... you should definitely be doing more error checking though. You can get the "No database selected" error if you specify a database that doesn't exists so that's where I would be looking next.

EDIT: Test the return value of mysql_select_db() and trigger an error or throw an exception if it doesn't return true.

Kane Wallmann
yes i just tried this and it doesnt throw any errors.
The.Anti.9
+1  A: 

You should always check the return values of builtin functions. Try something like this and you might get an answer:

function db($host, $user, $pass, $database) {
    if (($this->con = mysql_connect($host, $user, $pass)) === false) {
        throw new Exception(mysql_error());
    }
    if (!mysql_select_db($database)) {
        throw new Exception(mysql_error());
    }
}
soulmerge