MySQL Forums
Forum List  »  PHP

Re: mysql_insert_id(); returnig 0 Record is added and the field is auto_increment?!!
Posted by: theodor michailow
Date: February 15, 2014 03:15AM

ok i make a simple table
CREATE TABLE IF NOT EXISTS `mydb`.`service` (
`idservice` INT NOT NULL AUTO_INCREMENT ,
`locationstreet` VARCHAR(45) NOT NULL ,
`locationkvartal` VARCHAR(45) NOT NULL ,
`locationsity` VARCHAR(45) NULL ,
`streetnum` INT NULL ,
PRIMARY KEY (`idservice`) )
ENGINE = InnoDB;

after that i make a html form and php to insert it into the database
and i want to take the last incremented ID... but it isn`t working... i have tryed many ways but no luck... it allways returns 0 no matter waht.



<?php

if(isset($_POST['add']))
{
$ulica=$_POST['ulica'];
if(empty($ulica) ){
echo "The fields are blank";
die;
}
$con=mysqli_connect("localhost","root","kati2323","mydb");
//Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="INSERT INTO service (locationstreet,locationkvartal,locationsity,streetnum)
VALUES
('$_POST[ulica]','$_POST[kvartal]','$_POST[grad]','$_POST[nomer]')";

//what i tried-------------------------------------------------------------------
//$lastid ="SELECT LAST_INSERT_ID()"; // doesnt WORK

//$result = mysql_query($sql,$con); // doestt WORK
//echo "ID of last inserted record is: " . mysql_insert_id(); // gives me 0!!!

//------------------------------------------------------------------------------


if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}

echo "1 record added";
// header("location: servis.php");

mysqli_close($con);
}
?>
<html>
<head>
<title></title>

</head>
<body>
<form action="servis.php" method="post">
Ulica:<input type="text" name="ulica" value="" size="10" maxlength="23" /><br />
Kvartal:<input type="text" name="kvartal" value="" size="10" maxlength="23" /><br />
Grad<input type="text" name="grad" value="" size="10" maxlength="23" /><br />
Ulica<input type="text" name="nomer" value="" size="10" maxlength="23" /><br />
<input type="submit" name="add" value="Save" size="5" />
</form>
</body>
</html>
i tried many other ways and still i get 0 all the time... whats wrong : (?
is there another way to get the last incremented id?

Options: ReplyQuote


Subject
Written By
Posted
Re: mysql_insert_id(); returnig 0 Record is added and the field is auto_increment?!!
February 15, 2014 03:15AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.