I am trying to migrate from mysqli procedural to PDO because my website was halfway, half in pdo, and the rest in mysqli procedural, now I want to shift to PDO completely. Here is an example of the code I run
$rowNum = 0;
foreach ($result->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_OBJ) as $row) {
$rowNum = $rowNum + 1;
$dbUsername = $row['Username'];
}
if ($row>0) {
echo $dbUsername;
}
But in some scenarios, the code gives me an error that trying to get property 'Username' of non-object
I know it was possible to use only ($result->fetchAll(PDO::FETCH_ASSOC)
But doing this ($result->fetchAll(PDO::FETCH_ASSOC|PDO::FETCH_OBJ) becomes a need as some context of the code I'm modifying use the symbol like $row->Usename and the other use $row['Username'], How can I make it accept both modes as shown above?
I tried to use PDO:: FETCH_BOTH but the problem persists.
It's not possible. You cannot get both at the same time. There would be no way to represent such a result in PHP.
When you try to use both with
PDO::FETCH_ASSOC|PDO::FETCH_OBJyou are actually fetching the result asPDO::FETCH_COLUMN. That's because fetch parameter is a bitwise flags parameter. When you do an OR operation on these flags it is the same as2|5 = 7. 7 is the value forPDO::FETCH_COLUMN.I don't know what use case you have for this, but it sounds like an XY problem. If you use
fetchAll()you cannot have it both as an array and an object. But if you are fetching it row by row withfetch(), you could fetch each row in a different way.