Jump to content

mysql max(Id) into php variable


SN1P3R_85

Recommended Posts

function fGetMaxID()
{
$query = "PREPARE GetMaxID0 FROM 'SELECT max(Id) FROM threads'"; $result = mysql_query($query) or die(mysql_error());
$query = "EXECUTE GetMaxID0"; $result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array ($result, MYSQL_BOTH);
$query = "DEALLOCATE PREPARE GetMaxID0"; $resultDeallocate = mysql_query($query) or die(mysql_error());
return $row;
}
$maxID = fGetMaxID();
$maxID = $maxID[0];

 

untested, but should work

 

EDIT:: changed query to max(Id)

basically, max() extracts an array, so you need to use mysql_fetch_array() to get the array, then return the row... it's a single element array, but still an array... so you need to get $MaxID[0] (the result) and set $MaxID to that value...

 

hth

i dont' understand why this wont' work, this makes sense. I am using my login table to test it. it should echo the first element of the array.

 

<?php

 

$select_maxid = mysql_query("SELECT MAX(Id) FROM `login`");

 

$row1 = mysql_fetch_array($select_maxid, MYSQL_BOTH);

 

$max_id = $row1[0];

 

echo $max_id;

 

?>

i'm assuming you have a column "Id" in the login table, and that there is at least one record in the table?

 

as far as MYSQL_BOTH, check: http://us2.php.net/mysql_fetch_array

 

technically, it's not needed as it's the default value, but good practice to put it in...

 

EDIT:: Your code works fine for me (short of changing Id to ID, and login to Links to fit my db...)

hey, thanks for the help, i got it to work. The mysql code you gave me worked fine, it was a weird syntax error. I never found out what it was, my code looked fine, so i copied a piece of code from another file and it worked. Before i leave, could you tell me what that MYSQL_BOTH does?

"The type of returned array depends on how result_type  is defined. By using MYSQL_BOTH (default), you'll get an array with both associative and number indices. Using MYSQL_ASSOC, you only get associative indices (as mysql_fetch_assoc() works), using MYSQL_NUM, you only get number indices (as mysql_fetch_row() works)."

 

from: http://us2.php.net/mysql_fetch_array

 

glad i could help...

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.