So I’m pulling one column from my database by PDO and i want to echo it directly without assign a variable.
<?php echo ($db->query("SELECT name FROM categories WHERE code = '{$_GET['code']}' LIMIT 1")->fetch(PDO::FETCH_ASSOC);
This throws array to string error, when i use json_encode function it echos {"name":"Boys Games"}.
So yes i know i can just create a variable and take the element of "name" when printing. But i’m wondering if there’s a way without creating a variable and just printing it.
2
Answers
To echo the ‘name’ column directly without assigning it to a variable, you can modify the code by accessing the ‘name’ element directly from the fetched array and echoing it. Here’s an example of how you can do it:
In this example, we are fetching the row from the database and using the array index operator [ ‘name’ ] to directly access the ‘name’ element from the fetched array. Finally, we echo the value of ‘name’ column.
By accessing the element directly, you don’t need to assign it to a variable before echoing it. Instead, you can echo it directly.
Use
fetchColumn()
instead offetch()
to return a single column value. It defaults to the first column, which is what you want when the query only returns one column.