Link to home
Start Free TrialLog in
Avatar of QuintusSmit
QuintusSmit

asked on

mysql_insert_id() gives a 0 return

Hi

I am trying to get an auto increment ID for a user from a DB after inserting it with mysql_insert_id() but it keeps giving me a zero result.


This is the code:

                  
	$query = "INSERT INTO tbl_users (name, middlename, surname, id, email, cell_no, password) VALUES ('".$this->name."',
				'".$this->middlename."', '".$this->surname."', '".$this->id."','".$this->email."', '".$this->cellNumber."', '')";
				$result = mysqli_query($dbc, $query) or die("Could not exectute query");
				$idResult = mysql_insert_id();
				echo $idResult;

Open in new window


$idResult give me a "0"

in the Db the users_id field is a primary key and auto increment.
ASKER CERTIFIED SOLUTION
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Just adding a comment that might help you debug in the future.  When I'm having trouble with mySQL, I use echo to show me the query command my program constructed.  If the problem isn't obvious (and it often is), I open command line mySQL and copy/paste the command to it so that I can see an error message coming from mySQL.  If the error is still not obvious, you have something pretty useful to post to Experts Exchange.

However, that won't help much if you are trying to mix 2 different DB engines except to say that you'll get an error that useful to include in your post to EE.
Avatar of QuintusSmit
QuintusSmit

ASKER

Dave you friggin rock!

I am designing a statue in your honour as we speak.

I learnt from a book and they failed to explain that when using mysqli the connection actually becomes an object (it was a beginners book so can't blame them)

To anyone else with the same problem. The help manual on this is very sparse so I hope this helps. This is what worked for me:

$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die('Can not connect to Database');
$query = "INSERT INTO tbl_users (name, middlename, surname, id, email, cell_no, password) VALUES ('".$this->name."',
                        '".$this->middlename."', '".$this->surname."', '".$this->id."','".$this->email."', '".$this->cellNumber."', '')";
                        $result = mysqli_query($dbc, $query) or die("Could not exectute query");
                        $idResult = $dbc->insert_id;
@hmccurdy

tx I will keep that in mind - I usually type the command in mySQL but using echo to copy paste makes a lot more sense.