Db prob

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
raziel666
Forum Newbie
Posts: 5
Joined: Sat Jul 17, 2004 8:04 am

Db prob

Post by raziel666 »

Hi
I'm new to this forum and quite new to PHP. I'm trying to insert records into a table and I want to determine if this is the first record (question_id=NULL) or there are more. If this is the first record then I want the value for question_id to become 1, else I want it to become the maximum question_id value plus 1. Here is the code :

$query_for_max = "SELECT MAX(question_id) FROM questions";
if (mysql_query($query_for_max) == NULL)
{
$query_insert = "INSERT INTO questions (question_id) VALUES (1)";
mysql_query($query_insert);
$question_id = 1;
}
else
{
$question_id = (mysql_query($query_for_max) + 1);
$query_insert = "INSERT INTO questions (question_id) VALUES ($question_id)";

I've tried both cases by altering the table data, but I haven't accomplished anything yet. Any ideas appreciated
?>
raziel666
Forum Newbie
Posts: 5
Joined: Sat Jul 17, 2004 8:04 am

Post by raziel666 »

I've also tried this simple code :

$query = "SELECT MAX(question_id) FROM questions";
echo(mysql_query($query));

The result I get in any case is Result id #2
kettle_drum
DevNet Resident
Posts: 1150
Joined: Sun Jul 20, 2003 9:25 pm
Location: West Yorkshire, England

Post by kettle_drum »

Code: Select all

$query = "SELECT MAX(question_id) FROM questions"; 
$result = mysql_query($query);
$value = mysql_fetch_array($result);

echo $value[0];
If you set your field to auto increment in the sql syntax, then you dont have to find this value and all you have to do is insert the data.
Post Reply