-1

I'm trying to return a max value from my table.

$link = new PDO('mysql:dbname='.$dbname.';host='.$dbhost.';charset=utf8',$dbuser, $dbpass ) or die();
$gid = $link->prepare("SELECT MAX(level) as level FROM users");
$gid->execute();
$maxLevelRes = $gid->fetch(PDO::FETCH_ASSOC);

$maxLevelVal = $maxLevelRes['level']; 
$maxLevel = ++$maxLevelRes;

I want $maxLevel to be the result of my $maxLevelVal + 1, it currently outputs...

Array

Can anybody tell me why the value in my table is an integer ?

Barry
  • 3,303
  • 7
  • 23
  • 42
Liam
  • 9,725
  • 39
  • 111
  • 209
  • 1
    Have you tried your last line being `$maxLevel = $maxLevelVal + 1;`. `$maxLevelRes` is a record which will be an array. – Nigel Ren Oct 22 '18 at 09:57
  • yes, that just returns 1 @NigelRen – Liam Oct 22 '18 at 09:58
  • 1
    Read your question again. The error is in front of you. You said *"I want `$maxLevel` to be the result of my `$maxLevelVal + 1`"* but you put something else in `$maxLevel` in the code. – axiac Oct 22 '18 at 09:59
  • You soudl try `$maxLevel =$maxLevelRes['level'] + 1 `. If it didn't work, please do `var_dump($maxLevelRes)` and show us the result ty – Mickaël Leger Oct 22 '18 at 10:00
  • You're right, thanks @axiac – Liam Oct 22 '18 at 10:03
  • `$maxLevel = ++$maxLevelVal;` is ambiguous. Maybe it has the expected outcome but it is confusing for the reader. What happen first? The pre-increment (`++`) or the assignment (`=`)? It is much clear to express it as `$maxLevel = $maxLevelVal + 1;`. If you also need to increment `$maxLevelVal` then you can do it in a separate statement (either `$maxLevelVal += 1;` or `$maxLevelVal ++;`). – axiac Oct 22 '18 at 10:12

2 Answers2

1

fetch with the flag of PDO::FETCH_ASSOC returns an array of the columns returned:

PDO::FETCH_ASSOC: returns an array indexed by column name as returned in your result set

you should use fetchColumn to return a value of the column rather than get the array.

You'd have to use (in your current code) $maxLevelRes['level'] to get your data.

treyBake
  • 6,440
  • 6
  • 26
  • 57
-1

Try this:

$maxLevelVal = $maxLevelRes['level']; 
$maxLevel = ++$maxLevelVal;

For more: How do I convert a string to a number in PHP?

Vinesh Goyal
  • 607
  • 5
  • 8