Reputation: 328
I want to get the next auto increment id with PHP. I run the query in mysql and need the result:
column name: auto_increment value = 122
but I am getting a Notice:
Trying to get property 'auto_increment' of non-object
public function findNextAutoIncrementId()
{
$db = config::getConnexion();
$sql = 'SELECT `auto_increment` FROM INFORMATION_SCHEMA.TABLES
WHERE table_name = newsarticle';
$req = $db->prepare($sql);
$req->execute();
$result = $req->fetch(PDO::FETCH_OBJ);
return $result;
}
// when i use it i get Notice: Trying to get property 'auto_increment' of non-object
$result=$sujetC->findNextAutoIncrementId();
echo "this is : ".$result->auto_increment;
[Edit] : When I asked this question I wanted to find the next 'newsarticle' object that will be created to do some functions at it just after the insert operation and before showing it. What I should have made was to create a function that search for the specific 'newsarticle' after it has been created with the specific attributes
Upvotes: 0
Views: 150
Reputation: 54212
Read this similar question. You don't need to do so.
Since you are using auto increment I assume, you don't need to specify the next insert ID when you're performing an INSERT
query. You can skip the column and MySQL will assign the next ID for you.
For example, you have a table like this:
CREATE TABLE samples (
id INT(11) NOT NULL AUTO_INCREMENT,
sample_name VARCHAR(50) NOT NULL,
PRIMARY KEY (id)
)
ENGINE=InnoDB;
When you're going to insert a new record, you just need to execute the following SQL command:
INSERT INTO samples (sample_name) VALUES ('Some Location')
No need to explicitly specify the value of the AUTO_INCREMENT
column.
Upvotes: 2