PHP PDO FetchAll arguments to remove row number from results - php

I am building a function that acts like Drupal's variable_initialize() function that pulls all key/value pairs into a global variable. I am trying to find the proper parameters I need to put into fetchAll() to remove the row number and get basically what fetch(PDO::FETCH_ASSOC) does but for all returned rows.
I basically want fetchAll to return:
Array {
[name] = value,
[name2] = value2,
[name3] = value3,
}
The variable table is a simple 2 column table (name)|(value)
function variable_init() {
global $db, $variable;
$query = "SELECT * FROM variable";
$stmt = $db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(); //need help here
foreach($result as $name => $value) {
$variable[$name] = $value;
}
}
I have tried PDO_COLUMN/PDO_GROUP/etc... but I can't seem to offset the array to remove the row numbers. Thanks.

I think you may be getting confused about what PDOStatement::fetchAll() returns.
The method returns all rows (arrays or objects, depending on fetch style) in an array.
Try this
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$variable[$row['name']] = $row['value'];
}

Related

How to get an Int result from array in PHP /MYSQL

I have written code with the intention of getting an integer quantity but the result am getting is in an array format.How do I convert that from an array to an integer. Am getting the results from a MySQL database...
Here is my code, Instead of it returning an array I need to get the array value that is at that key
function hcQuantiy($db, $isbn)
{
$query = "SELECT num_hardcover from inventory where isbn = :isbn";
$statement = $db->prepare($query);
$statement->bindValue(':isbn', $isbn);
$statement->execute();
$result = $statement->fetchAll(PDO::FETCH_ASSOC);
$statement->closeCursor();
return $result;
}
If you need only one row dont use the method fetchAll which returns an array of rows, use only fetch, which returms an array with one row.
Use PDO::FETCH_NUM for fetch and get the index 0 of the result.
Than convert the result to an int. And there you have your quantity :)
Your code edited:
function hcQuantiy($db, $isbn) {
$query = "SELECT num_hardcover FROM inventory WHERE isbn = :isbn";
$statement = $db->prepare($query);
$statement->bindValue(':isbn', $isbn);
$statement->execute();
$result = $statement->fetch(PDO::FETCH_NUM);
$statement->closeCursor();
return intval($result[0]);
}
You can do accessing the array eg:
while ($row = $statement->fetchAll(PDO::FETCH_ASSOC)) {
echo $row["num_hardcover"] . '<br />;
}

PHP - An array called from a sql database does not implode properly, but an array created directly does? [duplicate]

This question already has answers here:
PDO fetch one column from table into 1-dimensional array
(2 answers)
Closed 2 years ago.
I am using PDO to call my database from xampp's phpmyadmin.
XAMPP version 7.0.1-0
When I create an array from scratch, and implode it, it gives me the results I want to see.
For Example:
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);
Which gives me:
Hello World! Beautiful Day!
However, when I do the same thing to my database query, this happens:
Notice: Array to string conversion in C:\xampp\htdocs\WHS_Webtour\Search_Categories\People_Search_Result\people_search.php on line 57
Array Array Array Array Array Array Array...
I have used var_dump() to see if the array actually shows and it does.
This is the code I used to call from my sql database:
function getData($db)
{
$stmt = $db->query('SELECT NAME FROM people');
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
I then added echo implode(" ",$result); which gave me the error result above.
If this helps, I had imported a database file which was converted from a .dbf to a .sql.
UPDATE
I updated this line of code: $result = $stmt->fetch(PDO::FETCH_ASSOC);
It only prints out one out of 50 names.
Another solution would be to do this right in your Query.
SELECT
GROUP_CONCAT(`NAME` SEPARATOR ' ') AS `NAMES`,
1 AS `x`
FROM `people`
WHERE 1
GROUP BY `x`
Judging by your query, I'm guessing you are wanting to implode all the names, but the problem you are running in to is that each row you fetch is going to be an array.
function getData($db)
{
$stmt = $db->query('SELECT NAME FROM people');
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$names = array();
foreach($result as $name) {
$names[] = $name['NAME'];
}
return $names;
}
This specifically will return the information in the way you are anticipating it. It will go through each row and pull the name out in to a new array that will then be returned.
fetchAll() returns an array of arrays (a multidimensional array). Multidimensional arrays cannot be converted to text straight away due to constraints in the language. Try to return your values with fetch() which will get one row as a single array. You do this in a loop:
while($row = $stmt->fetch() {
$line = implode(" ",$row);
}
PDO Fetch
Since you're only getting one column from the database could put all of the returned values in an array:
while($row = $stmt->fetch() {
$names[] = $row['NAME'];
}
$allNames = implode(" ", $names);
This way you push each returned item into an array ($names) which you can then implode.
fetchAll() returns an array of arrays. If you want to implode() your data, you may want to try something like this using fetch():
function getData($db)
{
$stmt = $db->query('SELECT NAME FROM people');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo implode(" ",$row);
}
}
That should help!
$implodedVal = implode(', ', array_map(function ($indArray) {
return implode(", ", $indArray);
}, $result));
edited function
function getData($db) {
$stmt = $db->query('SELECT NAME FROM people');
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
return implode(', ', array_map(function ($entry) {
return implode(", ", $entry);
}, $result));
}
This could help you, if I'm not wrong in understanding your question.

PHP PDO FetchAll vs Fetch

I believe I am using the PDO fetch functions completely wrong. Here is what I am trying to do:
Query a row, get the results, use a helper function to process the results into an array.
Query
function userName($db){
$q = $db->prepare("SELECT id, name FROM users WHERE id = :user");
$q->bindParam(":user", $user);
$q->execute();
$qr = $q->fetchAll(PDO::FETCH_ASSOC);
if ($qr->rowCount() > 0){
foreach($qr as $row){
$names[$row['id']] = buildArray($row);
}
return $names;
}
}
My custom array building function
function buildArray($row){
$usernames = array();
if(isset($row['id'])) $usernames['id'] = $row['id'];
if(isset($row['name'])) $usernames['name'] = $row['name'];
}
I'm actually getting exactly what I want from this, but when I echo inbetween I see that things are looping 3 times instead of once. I think I am misusing fetchAll.
Any help appreciated
If you're going to build a new array, there's not much point in having fetchAll() build an array. Write your own fetch() loop:
function userName($db){
$q = $db->prepare("SELECT id, name FROM users WHERE id = :user");
$q->bindParam(":user", $user);
$q->execute();
$names = array();
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
$names[$row['id']] = $row;
}
return $names;
}
There's also no need for buildArray(), since $row is already the associative array you want.

PHP convention in retrieving results indexed by a particular column?

I often need to retrieve results and access them by a given column.
Is there a way to write this without walking through the whole dataset each time?
I looked into various PDO fetch modes, but nothing jumped out as being simpler than that. Thanks.
function get_groups() {
$stmt = $dbc->prepare("SELECT * FROM groups ORDER BY group_name");
$stmt->execute();
$groups = $stmt->fetchAll();
$return = [];
foreach($groups as $group) {
$return[$group['id']] = $group;
}
return $return;
}
My proposed solution was pretty obsolete. The right solution comes from this answer
$stmt = $pdo->query("SELECT foo,baz FROM bar")
$groupedByFooValuesArray = $stmt->fetchAll(\PDO::FETCH_GROUP|\PDO::FETCH_UNIQUE)
to group it by another column, change the first column you select
if your goal is to have your same array indexed by different column values, I think the only option is to actually index them by different column values.
you can do that by controlling by which field the array is returned
function get_groups($sql,$key,$values='') {
if ($values != '') {
$stmt = $dbc->prepare($sql);
$stmt->execute($values);
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
else {
$rows = $dbc->query($sql)->fetchAll(PDO::FETCH_ASSOC);
}
foreach ($rows as $row) {
$indexed[$row[$key]] = $row;
}
return $indexed;
}
then, use get_groups to build an indexed array:
$sql = 'SELECT * FROM groups ORDER BY group_name'
var_dump(get_groups($sql,'id'));
There might be a way to store a resultset in some way that you can fetchAll() it multiple times, that would be awesome. but I don't know it.

Passing each row of a mysql query to a php array

i am running a mysql query to return all rows from a temp database, i then need to ammend some of the attributes in those rows so i am trying to return each row to an array so i can then reference the array and amend specific attributes of each row
im just stuck on how to get each row into its own array, im guessing i will need to use a 2d array for this however cannot figure out how to populate it from the mysql query into the 2d array. Im guessing it is something like i have tried below?
$result_array = array();
while ($row = mysql_fetch_assoc($res2)) {
$result_array[] = $var;
foreach($row as $key => $var) {
// Insert into array
echo $var;
}
however when trying this i am getting a notice saying:
Notice: Array to string conversion
any help pointing me in the right direction for this would be great
If I understand what you're asking for, you literally want each row from the SQL query to be a single index in the $result_array array?
If that's the case, you're already getting it with $row - you can add that directly to the array:
$result_array = array();
while ($row = mysql_fetch_assoc($res2)) {
$result_array[] = $row;
}
You can modify the values inside the array either when you're adding them to the global array, or after:
foreach ($result_array as $index => $row) {
$result_array[$index]['some_key'] = $row['some_key'] . ' [modified]';
}
Side-note (not answer specific)
I would recommend against using the old, deprecated mysql_ functions and instead favor MySQLi or PDO. Both of these are easy to use, more secure than the older methods and offer a large range of features such as prepared statements.
The above can be written with mysqli like:
if ($result = mysqli_query($connection, $query)) {
$results = array();
while ($row = mysqli_fetch_assoc($result)) {
$results = $row;
}
mysqli_free_result($result);
}

Categories