If you are expecting a non-zero value to appear from mysql_insert_id when you have not run any queries to insert something, you are always going to be disappointed.
You should also rethink your connect function. It does more than just connect. It connects, runs a query, and then returns the result resource of that query.
Consider rewriting your dal class to have two distinct routines, connect (which connects and selects the db and NOTHING ELSE) and query (which runs the supplied sql query and either returns or stores the result). Your class should probably have a property in which to store the db link. Maybe something like this:
class DAL {
private $username; // the username for db connect
private $pwd; // the pwd to use when connecting
private $host; // the host to which one connects
private $dbname; // the db to select
public $conn; // reference to the db link resource
public $db; // result of db_select
public $query_result; // the stored result of the last query you ran
public function __construct($username_arg, $pwd_arg, $host_arg, $dbname_arg) {
$this->username = $username_arg;
$this->pwd = $pwd_arg;
$this->host = $host_arg;
$this->dbname = $dbname_arg;
}
function connect() {
if (!($this->conn=mysql_connect($this->host, $this->username, $this->pwd))) {
die("error connecting to DB by user = " . $this->username . " and pwd=" . $this->pwd);
}
$this->db = mysql_select_db($this->dbname,$this->conn)
or die("Unable to connect to database " . $this->dbname);
} // connect()
public function query($sql) {
$this->result = mysql_query($sql, $conn)or die("Unable to query local database <b>". mysql_error()."</b><br>$sql");
if (!$this->result){
die("database query failed.");
} else {
return $result;
}
}
public function lastID() {
return mysql_insert_id($this->conn);
} // lastID()
} class DAL
then you could use it like this:
$myDB = new DAL("root", "", "localhost", "mydatabase");
$myDB->connect(); // your script will die if this fails
$sql = "INSERT INTO some_table (field1, field2, field3) VALUES ('value 1', 'value 2', 'value 3')";
$myDB->query($sql); // this will also die on failure
echo "last insert id:" . $myDB->lastID();