user1801060
user1801060

Reputation: 2821

Error in simple MySQL query

I'm executing a query on my db. I want to fetch the largest value of the table's primary key. I get a null result and an error in my log of:

"PHP Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource"

Here's my code:

$mysqli = new mysqli(MYSQL_HOSTNAME, 'xxx', 'xxx', MYSQL_DATABASE);
if (mysqli_connect_errno()) 
    exit();

$sql = "SELECT MAX(id) FROM `Invoice`";
//$sql = "SELECT id FROM `invoice`";
$res = mysqli_query($mysqli, $sql);

var_dump(get_object_vars($res));

if ($res) {
    $row = mysql_fetch_object($res);
    var_dump($row);
    //echo $row->MAX(id);    
}  else {
    printf("Could not retrieve records: %s\n", mysqli_error($mysqli));
}

mysqli_close($mysqli);

When I var_dump, I get NULL values. Here's what I've tried so far: (1). I've executed the SQL query directly in phpmyadmin. I get a result with a column header of 'Max(id)' (2). I've tried using mysql_fetch_array(). I get a log error of:

"PHP Warning: mysql_fetch_array() expects parameter 1 to be resource, object given"

What am I doing wrong?

Upvotes: 0

Views: 60

Answers (2)

Samuel Cook
Samuel Cook

Reputation: 16828

$row = mysql_fetch_object($res);

should be:

$row = mysqli_fetch_object($res);

You are trying to fetch an object of mysql, which you haven't set up

Upvotes: 1

eggyal
eggyal

Reputation: 125845

Functions prefixed mysql_ are from the old ext/mysql extension, which is completely separate (and incompatible) with the improved MySQLi extension (whose functions have the mysqli_ prefix). You are mixing the two, which won't work.

Upvotes: 0

Related Questions