Jump to content

[SOLVED] mysql_insert_id not working across classes


c1t1z3n

Recommended Posts

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:

/**
* 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");

/**
* 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;

/**
* 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?

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

 

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

 

to:

 

$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...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.