I have Database table of Questions. I use the integer variable Id to sort all the elements of the table.
What do I want? Whenever, a new question is added. It is assigned a new id, which is 1 greated than the ID of the last question in my database.
Here is what I do:
include('dbconnect.php');
$ids = $connection->prepare('SELECT * FROM question ORDER BY id ASC');
$ids->execute(array());
$result = $ids->fetchAll(PDO::FETCH_ASSOC);
$new_id = end($result['id']); //Error in this line.
$new_id = $new_id + 1;
But, I always get the error
Warning: end() expects parameter 1 to be array, null given in /Applications/MAMP/htdocs/question/submit.php on line 20
I am using the FetchAll
statement so I feel, that an array should be returned. Can anyone figure out where is the error.
Each New Question, which is added to the database gets an ID of 1.
As documented under Using AUTO_INCREMENT
:
The
AUTO_INCREMENT
attribute can be used to generate a unique identity for new rows:CREATE TABLE animals ( id MEDIUMINT NOT NULL AUTO_INCREMENT, name CHAR(30) NOT NULL, PRIMARY KEY (id) ); INSERT INTO animals (name) VALUES ('dog'),('cat'),('penguin'), ('lax'),('whale'),('ostrich'); SELECT * FROM animals;Which returns:
+----+---------+ | id | name | +----+---------+ | 1 | dog | | 2 | cat | | 3 | penguin | | 4 | lax | | 5 | whale | | 6 | ostrich | +----+---------+No value was specified for the
AUTO_INCREMENT
column, so MySQL assigned sequence numbers automatically. You can also explicitly assignNULL
or 0 to the column to generate sequence numbers.