I'm trying to get the highest number and then increment it by 1. I get blank page, here is my code
$query = $pdo->prepare("SELECT max(accnum) FROM accounts");
$query->execute();
while($num = $query->fetchAll()){
if($num[1] == null){
$accnumber = "100001";
}else{
$accnumber = $num[1]++;
}
echo $accnumber;
}
what am i doing wrong here. Thanks
$query = $pdo->prepare("SELECT max(accnum) FROM accounts");
$query->execute();
while($num = $query->fetchAll()){
if($num[0] == null){
$accnumber = "100001";
}else{
$accnumber = $num[0]++;
}
echo $accnumber;
}
Maybe you need something like this ?
$query = $pdo->prepare("SELECT max(accnum)+1 as maximum FROM accounts");
$query->execute();
$result = $query->fetch(PDO::FETCH_ASSOC);
if($result['maximum'] == null) {
$result = "100001"
} else {
$result = $accnumber['maximum']
}
You're using postincrement; that is, the ++
is after the variable, so it's not updated until after the assignment is complete.
Simply use this instead:
$accnumber = $num[1] + 1;
That way, $num
isn't affected, and your value will be correct.
Since you're getting a blank page, this may not be the issue. So, you may also want to reconsider how you handle the values; you seem to be mixing strings and integers, and that probably won't end well. I'd suggest using only integers. Also, you should be using $num[0]
, since you're fetching the first value of a zero-based array:
$query = $pdo->prepare("SELECT max(accnum) FROM accounts");
$query->execute();
while($num = $query->fetchAll()){
if($num[0] == null){
$accnumber = 100001;
}else{
$accnumber = intval($num[0]) + 1;
}
echo $accnumber;
}