SQL rows to php assoc array - php

I have an SQL recordset that I wish to convert into an array that I can then change the ages without changing the db data.
I wish to be able to reference the ages by name. For example my source data is simply two columns with name and age.
// Initialise the pupils array
$query = "SELECT name, age FROM class";
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
$pupils = pg_fetch_all($result);
print_r($pupils);
This gives me:
Array
(
[0] => Array
(
[name] => Bob
[age] => 3
)
[1] => Array
(
[name] => Sue
[age] => 5
)
[2] => Array
(
[name] => Mary
[age] => 7
)
)
What I want is:
Array
(
[Bob] => 3,
[Sue] => 5,
[Mary] => 7
}

Use array_column() to build this array:
$pupils = pg_fetch_all($result);
$students = array_column($pupils, 'age', 'name');

Related

How to store MYSQLI query as multidimensional array in this format [duplicate]

This question already has answers here:
get array of rows with mysqli result
(2 answers)
Closed 4 years ago.
I'm trying to query database A and store results as an array, which I will then insert into database B. I can move simple data directly, but because of the complexity of this particular query (30+ left joins), I have to store it as an array and insert it in a separate query. The examples below contain just two fields, to keep things simple and focus on the core issue.
I have working code to insert an array stored as follows:
$data = array(
array( // record 1, or row 1
"1",
"Value for field 1.2"
),
array( // record 2, or row 2
"2",
"Value for field 2.2"
),
array( // record 3, or row 3
"3",
"Value for field 3.2"
),
// etc...
);
Unfortunately, I can't get my first query to store the data like this. I have used PHP for years, but I never messed with arrays before. I'm not sure what I'm doing wrong. Using "print_r($data), this is what the results look like for how I need the array to be (This is what the $data variable looks like with print_r() ):
Array ( [0] => Array ( [0] => 1 [1] => Value for field 1.2 ) [1] => Array ( [0] => 2 [1] => Value for field 2.2 ) [2] => Array ( [0] => 3 [1] => Value for field 3.2 ) )
My query to create the array doesn't match this pattern. A "print_r($new_array)" command yields this:
Array ( [0] => Array ( [id] => 37 [post_title] => test1 ) [1] => Array ( [id] => 38 [post_title] => test2 ) [2] => Array ( [id] => 35 [post_title] => test3 ) [3] => Array ( [id] => 42 [post_title] => test4 ) [4] => Array ( [id] => 44 [post_title] => test5 ) [5] => Array ( [id] => 46 [post_title] => test6 ) )
This is my MySQL query to put the data into an array:
$test_sql = "SELECT id, post_title FROM wp_posts where post_type LIKE 'test'";
$resultTest = mysqli_query($con, $test_sql);
//$new_array[] = $row;
while ($row = mysqli_fetch_assoc($resultTest)) {
$rows[] = $row;
}
If I understand what is going on, the array I'm creating is making key value pairs for a multidimensional array, but the format I need is not key value, just an array of values. Since I already have the insert query working, I would prefer to use a select query that stores the data in an array without the key value pairs, if that is possible, but I am open to all suggestions.
Thank you in advance for your kindness and help!
All you need to do is change fetch function to fetch_row:
while ($row = mysqli_fetch_row($resultTest)) {
$rows[] = $row;
}
Or to fetch_array with MYSQLI_NUM as second argument:
while ($row = mysqli_fetch_array($resultTest, MYSQLI_NUM)) {
$rows[] = $row;
}

Codeigniter:query results into associative array

I have two tables in database
1.main_category fields (id,main_name);
2.sub_category fields(id,main_id, sub_name)
Here main_id is used for connecting two tables from this i want to get the result like the following array
Array
(
[CCTV] => Array
(
[0] => Array
(
[id] => 1
[main_id] => 4
[name] => first
)
[1] => Array
(
[id] => 3
[main_id] => 4
[name] => second
)
[2] => Array
(
[id] => 4
[main_id] => 4
[name] => second
)
)
[Security Camera] => Array
(
[0] => Array
(
[id] => 5
[main_id] => 5
[name] => first
)
[1] => Array
(
[id] => 6
[main_id] => 5
[name] => second
)
[2] => Array
(
[id] => 7
[main_id] => 5
[name] => second
)
)
)
Here the key of the array are main_name field which is from the main_category table and the associative array for each key contains the rows which matches the condition
where main_category.id=sub_category.main_id
I want db query to achieve the above result.is it possible with a join query?
This is the structure of the join query you can change it in your own requirement.
function myfun($id){
$query = "select main_cat.*, sub_cat.* from main_category main_cat
Join sub_category sub_cat
ON main_cat.id = sub_cat.main_id
where main_cat.id = $id";
$data = $this->db->query($query);
return $data->result_array();
}
Hope this will help to you.
try to understand the query and make alteration as required.main_cat as table 1 and sub_category as table two . already you have gave half solution sub_category.employee_id = main_cat.employee_id
$this->db->select("main_cat.id,main_cat.main_id,main_cat.name,sub_category.id,sub_category.main_id,sub_category.sub_name");
$this->db->from('main_cat');
$this->db->join('sub_category', 'sub_category.employee_id = main_cat.employee_id');
$this->db->where('id', $id);
$query = $this->db->get();
return $query->result();
Hello You use codeignitor so use codeignitor mysql query structure it's best practise in future
$this->db->select("main_cat.id,main_cat.main_id,main_cat.name,sub_category.id,sub_category.main_id,sub_category.sub_name");
$this->db->from('main_cat');
$this->db->join_using('sub_category', 'employee_id');
$this->db->where(tablename.'id', $id);
$query = $this->db->get();
return $query->result();
employee_id is common in both table so use join_using other wise you use join like this
$this->db->join('sub_category', 'sub_category.employee_id = main_cat.employee_id');

Fetching data using PDO and get the data only once with its column names

When using PDO to fetch values from a mysql database I get some redundant information, and I'm wondering why. The php function below returns the values as I want them to be returned. But if I return my result array, I get double values.
public function getNames($userid) {
try {
$dbh = new PDO('mysql:host=localhost;dbname='.parent::Database(), parent::User(), parent::Password());
} catch (PDOException $e) {
var_dump("error: $e");
}
$sql = "SELECT ID, Name FROM cars WHERE userid =:UID and type=2";
$sth = $dbh->prepare($sql);
$sth->bindParam(':UID', $userid);
$sth->execute();
$result = $sth->fetchAll(); //fetches all results where there's a match
$result2 = array();
foreach($result as $res)
$result2[] = array("ID"=>$res["ID"], "Name"=>$res["Name"]);
return $result2;
}
$Result returns:
Array
(
[0] => Array
(
[ID] => 2
[0] => 2
[Name] => Volvo
[1] => Volvo
)
[1] => Array
(
[ID] => 8
[0] => 8
[Name] => Ford
[1] => Ford
)
)
$Result2 returns:
Array
(
[0] => Array
(
[ID] => 2
[Name] => Volvo
)
[1] => Array
(
[ID] => 8
[Name] => Ford
)
)
Why is $result acting like this? Its like its fetching my data multiple times. Am I using the code wrong? If possible, I want to use the result of $result2 without specifying each return array - in case the table is getting edited at some point. Possible?
You are getting the results both as an associative array and an indexed array.
To get only the associative array, you can use:
$result = $sth->fetchAll(PDO::FETCH_ASSOC);

mysql unexpected output from query [duplicate]

This question already has answers here:
mysql_fetch_array returns duplicate data
(7 answers)
Closed 9 years ago.
Maybe I have long since gotten to used to using ORM methods to pull data from a DB but I am now working up a simple little project for a buddy of mine who doesn't need all the extra guff of MVC's, ORM's and so on.. With that below is an example of the query I am putting together in a class I am building up in PHP.
$this->sqlstart();
$sql = "select label, setting from ".$this->_settings." where id <= 4";
$query = mysql_query($sql);
$result = array();
while($row = mysql_fetch_array($query))
{
$result[] = $row;
}
return $result;
The output from return $result is:
Array
(
[0] => Array
(
[0] => Week 1 Pay
[label] => Week 1 Pay
[1] => 2995
[setting] => 2995
)
[1] => Array
(
[0] => Week 2 Pay
[label] => Week 2 Pay
[1] => 2995
[setting] => 2995
)
[2] => Array
(
[0] => Week 1 Dates
[label] => Week 1 Dates
[1] => 1-15
[setting] => 1-15
)
[3] => Array
(
[0] => Week 2 Dates
[label] => Week 2 Dates
[1] => 16-31
[setting] => 16-31
)
)
And it should be
Array
(
[0] => Array
(
[label] => Week 1 Pay
[setting] => 2995
)
[1] => Array
(
[label] => Week 2 Pay
[setting] => 2995
)
[2] => Array
(
[label] => Week 1 Dates
[setting] => 1-15
)
[3] => Array
(
[label] => Week 2 Dates
[setting] => 16-31
)
)
can anyone point out to me where the additional data in the sets is coming from?
You should use mysql_fetch_assoc to get the result properly. It will provide you an associative array instead of a normal one.
From http://php.net/manual/en/function.mysql-fetch-array.php
array mysql_fetch_array ( resource $result [, int $result_type = MYSQL_BOTH ] )
Either pass MYSQL_ASSOC as the second param to just get an associative array back, or just call mysql_fetch_assoc().
You should be able to pass in a second argument which will only output the associative column names:
while($row = mysql_fetch_array($query, MYSQL_ASSOC))
mysql_fetch_array returns two ways to access values: field name and index number. You might change mysql_fetch_array to mysql_fetch_assocor change the code to:
while($row = mysql_fetch_array($query)){
$result[] = array('label' => $row['label'], 'setting' => $row['setting'];
}

Problems with array when getting data from a database

I'm trying to get some data from my database, and then pass it into an array for later use. I am using MySQLi for my driver.
Here's my code:
// Build a query to get skins from the database
$stmt = $mysqli->prepare('SELECT id, name, description, author, timestamp, url, preview_filename FROM `skins` LIMIT 0, 5');
$stmt->execute();
$stmt->bind_result($result['id'], $result['name'], $result['desc'], $result['auth'], $result['time'], $result['url'], $result['preview']);
// The skins array holds all the skins on the current page, to be passed to index.html
$skins = array();
$i = 0;
while($stmt->fetch())
{
$skins[$i] = $result;
$i++;
}
print_r($skins);
The problem is, when this executes, the $skins array contains the last result row from the query. This is the print_r of $skins:
Array
(
[0] => Array
(
[id] => 3
[name] => sdfbjh
[desc] => isdbf
[auth] => dfdf
[time] => 1299970810
[url] => http://imgur.com/XyYxs.png
[preview] => 011e5.png
)
[1] => Array
(
[id] => 3
[name] => sdfbjh
[desc] => isdbf
[auth] => dfdf
[time] => 1299970810
[url] => http://imgur.com/XyYxs.png
[preview] => 011e5.png
)
[2] => Array
(
[id] => 3
[name] => sdfbjh
[desc] => isdbf
[auth] => dfdf
[time] => 1299970810
[url] => http://imgur.com/XyYxs.png
[preview] => 011e5.png
)
)
As you can see, the last result from the query is populating all of the array entries for some reason.
Can anyone explain this behaviour and tell me what I'm doing wrong? Thanks. :)
EDIT: Here's the solution:
while($stmt->fetch())
{
foreach($result as $key=>$value)
{
$tmp[$key] = $value;
}
$skins[$i] = $tmp;
$i++;
}
Quoting the (now) first note on the mysqli::fetch manual page, emphasis mine :
the problem is that the $row returned is reference and not data.
So, when you write $array[] = $row, the $array will be filled up with the last element of the dataset.

Categories