mysql_insert_id not working across classes

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
c1t1z3n
Forum Newbie
Posts: 2
Joined: Tue Aug 18, 2009 11:51 am

mysql_insert_id not working across classes

Post by c1t1z3n »

i am using a third party class to handle database access, and when trying to use mysql_insert_id to obtain the last auto_increment value it always returns a zero - here are the .inc files i am using:

Code: Select all

/**
 * Constants.inc
 */
 
/**
 * Database Constants - these constants are required
 * in order for there to be a successful connection
 * to the MySQL database. Make sure the information is
 * correct.
 */
define("DB_SERVER", "localhost");
define("DB_USER", "username");
define("DB_PASS", "password");
define("DB_NAME", "database");

Code: Select all

/**
 * Database.inc
 */
include("constants.inc");
     
class MySQLDB
{
   var $connection;         //The MySQL database connection
 
   /* Class constructor */
   function MySQLDB(){
      /* Make connection to database */
      $this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASS) or die(mysql_error());
      mysql_select_db(DB_NAME, $this->connection) or die(mysql_error());
   }
   /**
    * query - Performs the given query on the database and
    * returns the result, which may be false, true or a
    * resource identifier.
    */
   function query($query){
      return mysql_query($query, $this->connection);
   }
};
/* Create database connection */
$database = new MySQLDB;

Code: Select all

/**
 * main.inc
 */
include ("database.inc");
 
class Main
{
   function insertQuery($data){
      global $database;
      $q = "INSERT INTO table ('data') VALUES ('$data')";
     $database->query($q);
     return mysql_insert_id($database->connection);
   }
};
 
/* Initialize main object */
$object = new Main;
the latter of the three is the code i have written to utilise the other scripts - the database table i am using (table) consists of two fields: id(int, auto_increment, primary key) and data(varchar)

can anybody shed light on why mysql_insert_id() does not appear to work as it should?
c1t1z3n
Forum Newbie
Posts: 2
Joined: Tue Aug 18, 2009 11:51 am

problem solved

Post by c1t1z3n »

i've fixed the problem by changing the query syntax from:

Code: Select all

$q = "INSERT INTO table ('data') VALUES ('$data')";
to:

Code: Select all

$q = "INSERT INTO table (data) VALUES ('$data')";
the quotes around the field element were throwing mysql, so the initial query was not processed and as a result mysql_insert_id() was rendered useless - other than that my original code worked fine thereafter...
Post Reply