3

I want to assign the max value of a column in mysql to a variable in PHP. This ultimately will be to validate form data. Having trouble as I am new to PHP.

Tried this:

$result = mysql_query("SELECT MAX(receipt_id) FROM receipts");
if (!result) {
trigger_error(mysql_error($result));
}

$row = mysql_fetch_assoc($result);
$maxid = $row["receipt_id"];

echo "The max id is $row";

(The echo is just for testing). In this case the result was:

The max id Array

When I echo the $maxid variable in the above code there is no value returned in the echo.

And with this code:

$result = mysql_query("SELECT MAX(receipt_id) FROM receipts");
if (!result) {
    trigger_error(mysql_error($result));
}

echo "The max id is $result";

I get:

The max id is Resource id #2

What am I missing here?

Thanks in advance!

1 Answer 1

5

Add an alias to the max sql function result:

SELECT MAX(receipt_id) AS max_value FROM receipts

Access it like any other value:

$row["max_value"]
Sign up to request clarification or add additional context in comments.

1 Comment

Nice. Here is me kicking myself. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.