I am trying to get the sub-sections of sections recursively from the database. Right now, my code only gets the parents but not the children though. What modification do I have to do to this code to accomplish my goal? Thanx
function getSections()
{
$this->connectToDB();
// get list of sections that has no parents
$sql ="SELECT * FROM sections WHERE parent = 0 ORDER BY id ASC";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result))
{
$thisID = $row['id'];
// recursivly get childeren
$childeren = $this->recursivlyGetSections($thisID);
// add to the final result
$toReturn .= "$thisID<br>$childeren";
}
// return final result
return $toReturn;
}
function getSections()
{
$this->connectToDB();
// get list of sections
$sql ="SELECT * FROM sections ORDER BY id ASC, parent ASC";
$result = mysql_query($sql);
$rezArray = array();
while($row=mysql_fetch_array($result))
{
if(!isset($rezArray[$row['parent']]))
$rezArray[$row['parent']] = array();
$rezArray[$row['parent']][] = $row;
}
//.. do something with the array
}
Use $rezArray which has all the results sorted by parent -- instead of doing multiple queries.
If you're wanting to store a full tree structure in your database, and it is read from more often that it is written to, you might want to consider implementing the storage as a nested set:
http://en.wikipedia.org/wiki/Nested_set_model
Related
I create as the following function. how to get all data using this array. when run this function will appear only the first record. but, i want it to appear all the records. what is the error in this code.
public function get_All_Se($stId){
$query = "SELECT * FROM session WHERE stId = '$stId'";
$result = $this->db->query($query) or die($this->db->error);
$data = $result->fetch_array(MYSQLI_ASSOC);
return $data;
}
public function get_All_Se($stId){
$rows=array();
$query = "SELECT * FROM session WHERE stId = '$stId'";
$result = $this->db->query($query) or die($this->db->error);
while($data= $result->fetch_assoc()){
$rows[]=$data;
}
return $rows;
}
Run loop over all results and add to some return array.
$rows = array();
while(($row = $result->fetch_array($result))) {
$rows[] = $row;
}
As the documentation of mysqli::fetch_array() explains, it returns only one row (and not an array containing all the rows as you might think).
The function you are looking for is mysqli::fetch_all(). It returns all the rows in an array.
public function get_All_Se($stId)
{
$query = "SELECT * FROM session WHERE stId = '$stId'";
$result = $this->db->query($query) or die($this->db->error);
return $result->fetch_all(MYSQLI_ASSOC);
}
The code above still has two big issues:
It is open to SQL injection. Use prepared statements to avoid it.
or die() is not the proper way to handle the errors. It looks nice in a tutorial but in production code it is a sign you don't care about how your code works and, by extension, what value it provides to their users. Throw an exception, catch it and handle it (log the error, put some message on screen etc) in the main program.
Try this way...
<?php
// run query
$query = mysql_query("SELECT * FROM <tableName>");
// set array
$array = array();
// look through query
while($row = mysql_fetch_assoc($query)){
// add each row returned into an array
$array[] = $row;
// OR just echo the data:
echo $row['<fieldName>']; // etc
}
// debug:
print_r($array); // show all array data
echo $array[0]['<fieldName>'];
?>
`
$poplrRec = mysql_query("SELECT * FROM ".ADD_RECIPE." ORDER BY POPULARITY DESC LIMIT 4");
while($poplrRec1=mysql_fetch_array($poplrRec))
{
$likecount=mysql_query("SELECT RECIPE_ID, COUNT(RECIPE_ID) FROM ".RECIPE_LIKE." WHERE RECIPE_ID=".$poplrRec1['RECIPE_ID']);
while($b=mysql_fetch_array($likecount))
{
$cmnt=mysql_query("SELECT RECIPE_ID, COUNT(RECIPE_ID) FROM ".RECIPE_CMMNT." WHERE RECIPE_ID=".$poplrRec1['RECIPE_ID']." AND TYPE=0");
while($c=mysql_fetch_array($cmnt))
{
}} } `
hi here i use core php while loop and MySQL query so i have to use these type of query in MVC structure of codeigniter. And like here i want result of every query separate to use in mvc structure.
each query provide some data that need to use in somewhere in that relevant .
plz suggest me how can i implement these type of php query in codeigniter or mvc structure .
Try to write query following format
$query = $this->db->get('vehicles_types');
$result = $query->result_array();
// loop through the types e.g. the parents
foreach( $result as $key => $row )
{
// add the "examples" e.g. the children to the result array
$query = $this->db->get_where('vehicles',array('type'=>$row['id']));
$row['examples'] = $query->result_array();
$result[$key] = $row;
}
return $result;
$result=$this->db->query("select * from tableName");
foreach($result->result() as $row){
// $row has the associative array
// you can again query the database with $this->db->query
}
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.
I have to make a breadcrumb menu which comes database.
So made this function
function file_list($path) {
$result = array();
$q = "SELECT staticTitle,staticId,parentId FROM tbl_static_pages WHERE staticId = $path";
$run = mysql_query($q);
while($row = mysql_fetch_array($run)) {
if($row['parentId'] > 1) {
echo $row['staticTitle'];
$result = file_list($row['parentId']);
return $result; // INSERTED
}else {
return $result;
}
}
I have a database structure like this:
id | parentId | title
3 | 1 | keyword
28 | 3 | xxx
31 | 28 | business
I want to output like this business -> xxx -> keyword
I want to run this function until $row['parentId'] = 1.When I echo the title, I got correct result.When I try it to store it in array, I always get single value.
How can I return an array in recursive array?
I REALLY don't like the idea of recursive calls on the database. If this is a "breadcrumbs" database table, how big could it possibly be? ...I mean size is probably not a concern.
I would like to suggest that you pull the full table out (3 columns, all rows) and assign the resultset to a php variable. This means you only ever make one trip to the database -- and that's a good thing.
Code: (Demo)
function breadcrumber($array,$id){
static $result=[]; // declare the storage variable without losing elements during recursion
if(isset($array[$id])){ // if target exists
$result[]=$array[$id]['title']; // store title text
$parent=$array[$id]['parentId']; // assign new target
unset($array[$id]); // remove possibility of an infinite loop
breadcrumber($array,$parent); // recurse
}
return $result;
}
$resultset=[
['id'=>3,'parentId'=>1,'title'=>'keyword'],
['id'=>28,'parentId'=>3,'title'=>'xxx'],
['id'=>31,'parentId'=>28,'title'=>'business']
];
echo implode(' -> ',breadcrumber(array_column($resultset,NULL,'id'),31));
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-assign associative keys for easy lookup
Output:
business -> xxx -> keyword
...and here is another demo using your second set of data
Try this:
function file_list($path)
{
$result = array();
$q = "SELECT staticTitle,staticId,parentId FROM tbl_static_pages WHERE staticId = $path";
$run = mysql_query($q);
$results = array();
while ($row = mysql_fetch_array($run))
{
if ($row['parentId'] > 1)
{
echo $row['staticTitle'];
$results = array_merge($results, file_list($row['parentId']));
}
else
{
$results[] = $result;
}
}
return $results;
}
Few things that are not clear from your question:
Breadcrumbs are usually not recursive, so I suppose you do NOT want to actually return a recursive array (array where every element is again array). If you want, follow comment by #midhunjose
Do you expect the query to ever return multiple records?
Swap the order of array_merge arguments, if you want the parent before child in resulting array.
Try this:
$result[] = file_list($row['parentId']);
instand of
$result = file_list($row['parentId']);
function showFields($selClient)
{
$result = mysql_query("SELECT * FROM project WHERE projectid = $selClient");
$values = array();
while($row = mysql_fetch_array($result))
{
$values[] = array($row['clientname'],$row['prospect'],$row['salesperson']);
}
return $values;
}
When i return the values to Flex, i am not able catch individual elements. When i trace i get all values stored in a single array...
I am slightly confused...,.
var editField:Array = event.result as Array;
Alert.show(editField[0]);
This returns all the values in the Array, instead of the 0th element.
you could do:
Alert.show(editField[0][0]);
if i understand it correctly...
you need to iterate over two arrays (two levels)
Also, if you are only returning specific columns, why select them all? This will function will return the same data and as it only selects what you need, will be faster. In this case the select is so simple that the time difference will be virtually 0, but it's a good habit to get into for when your db queries start getting more complex.
function showFields($selClient)
{
$result = mysql_query("SELECT clientname, prospect, salesperson FROM project WHERE projectid = $selClient");
$values = array();
while($row = mysql_fetch_array($result))
{
$values[] = $row;
}
return $values;
}