Burning Hippo
Burning Hippo

Reputation: 805

PHP mySQL result to variable

I do not understand why this isn't working. I know it's something simple more than likely. I want the value from the 2nd query to be placed into $newowner I am getting an array to string conversion error.

$query = "INSERT INTO owners (fname, lname) VALUES ('default', 'default')";
mysqli_query( $con, $query );
echo $query;
$query = "SELECT MAX(id) FROM owners";
$result = mysqli_query( $con, $query );
$newowner = mysqli_fetch_assoc( $result );
echo $newowner;

Upvotes: 0

Views: 75

Answers (3)

Fluffeh
Fluffeh

Reputation: 33542

Assuming that your initial queries insert properly, $newowner is actually an array, so you can't just echo it out. You could show it like this:

print_r($newonwer);

But you would be better off using the following:

$query = "SELECT MAX(id) as ID FROM owners";
$result = mysqli_query($con, $query);
$newowner = mysqli_fetch_assoc($result);
echo $newowner['ID'];

Upvotes: 0

pilsetnieks
pilsetnieks

Reputation: 10430

That's because mysqli_fetch_assoc returns an array. What you need to do is get the value out of the array, e.g.:

echo $newowner['MAX(id)'];

You can simplify it by assigning an alias to the column name, for example, in your query:

select max(ID) as MaxID from owners

and then you could use echo $newowner['MaxID'].

Upvotes: 1

Mike Brant
Mike Brant

Reputation: 71422

In that case, $newowner is an array. Try to add an alias to your query like:

$query = "SELECT MAX(id) AS max_id FROM owners";
$result = mysqli_query($con, $query);
$newowner = mysqli_fetch_assoc($result);
echo $newowner['max_id'];

to see how to access the value from an associative array or simply do to get the value in a numerically indexed fashion.

$newowner = mysqli_fetch($result);
echo $newowner[0];

Upvotes: 1

Related Questions