Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SQL query driving me crazy

Status
Not open for further replies.

jgd12345

Technical User
Joined
Apr 22, 2003
Messages
124
Location
GB
Hi, I can't believe I've had to resort asking for support on this but I don't know what's wrong. Here's the php code. Every time I get the value 1 printed out although in my table I have records with id's of 8, 9 etc. I'd be greatful for your help.

$query = mysql_query("SELECT id FROM $table_bdb_albums ORDER BY id DESC LIMIT 0, 1");
$nb = mysql_fetch_array($query, 0);

$filename = $nb[id] + 1;
echo $filename;
 
Hi,

You need a loop to get all the info from the table and store it in an array. You are also missing the ` around certain parts of your query.


$sql = "SELECT `id` FROM `$table_bdb_albums` ORDER BY `id` DESC";
$query = mysql_query ($sql);

while ($nb=mysql_fetch_array($query))
{
$filename = $nb["id"] + 1;
echo $filename;
}

Is that what you're after?

Hope this helps!

relax.gif


Keep up to date with my 2003 NHL Playoffs Wallpaper
 
As SPYDERIX says - you are just getting the first row.

As for the backticks:
I believe they are only necessary if you are using reserved words as database, table, or column names or if one of these items contains special characters such as hyphens etc.

However, there is no drawback besides additional typing when using the backtick.

mysql_query() returns a resource identifier which is used to retrieve rows - unless the query fails for some reason. I'd advise to add error checking to see if a valid resource_identifier is returned:
Code:
$sql = "SELECT `id` FROM `$table_bdb_albums` ORDER BY `id` DESC";
$query = mysql_query ($sql) OR die(mysql_error());

while ($row = mysql_fetch_assoc($query)){
    $filename = $row["id"] + 1;
    echo $filename;
}

Also, please note that it is safer to quote the key of an associative array. If you don't quote it is at first regarded as a constant which defaults to the string value if non existent. However, if the PHP folks ever were to introduce a constant id your reference to the column would fail unless quoted.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top