Jump to content

Recommended Posts

Hello:

 

I am having a problem and I am not sure my method is correct.  I know my sub-query isn't.  What I need is to get the Max-Autonum, or last record for a specific record. Please see the example for a better understanding:

 

 

 

part_id_num part_manufac_code part_number

1 36 18547

2 36 57847

3 35 79811

4 36 57914

5 35 74992

 

 

If I am looking for part_manufac_code 36, then the last record (part_id_num) for that is 4.  Here is the code that I have:

//
//
//
require("connect.php");
//
//
//
$query1 = "SELECT part_id_num, part_manufac_code, part_number FROM tblparts WHERE (part_manufac_code = '$frmfindpart')";
$result1 = mysql_query($query1) or die(mysql_error());
//
//
$query2 = "SELECT MAX(part_id_num) FROM '$result1'";
$result2 = mysql_query($query2) or die(mysql_error()); 
if(mysql_num_rows($result2) > 0) 
{ 
    while($row = mysql_fetch_assoc($result2)) 
    { 
        $names[] = $row['name']; 
    } 
} 
else 
{ 
    echo 'query returned no results'; 
}

Link to comment
https://forums.phpfreaks.com/topic/251270-problem-with-second-query/
Share on other sites

The main problem is you're not using the right code. After a mysql_query() comes one of the mysql_fetch_*() functions, like mysql_fetch_array. That's the function that gives you the actual data; mysql_query() only returns an identifier - no data.

 

The second problem is in your query, as you guessed. All you're doing now is getting the highest value - what you want is to retrieve the entire row. Use an ORDER BY + LIMIT instead.

SELECT * FROM tblparts WHERE part_manufac_code = '$frmfindpart' ORDER BY part_date DESC LIMIT 1

 

The third problem is that you're assuming the highest auto_increment value is the latest. Don't do that. Include a date column for when the record was added and do the ORDER BY on that instead. I did so in the query above using the name "part_date".

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.