Make hierarchy from table with PHP - php

I have a table in database and in this table i have added 3 columns that is i, name,parent_id.please see below.
ID | name | parent_id
1 name1 0
2 name2 1
3 name3 1
Now i want to fetch this id from database. I have created a method in PHP and fetch data one by one from database. Please see below
function getData($id)
{
$array = array();
$db = JFactory::getDBO();
$sql = "SELECT * from table_name when id = ".$id;
$db>setQuery($sql);
$fetchAllDatas = $db->getObjectList();
foreach ($fetchAllDatas as $fetchAllData)
{
if($fetchAllData->parent_id > 0)
{
$array[$fetchAllData->parent_id] = $fetchAllData->name;
$this->getData($fetchAllData->parent_id);
}
else
{
$array[$fetchAllData->parent_id] = $fetchAllData->name;
}
}
return $array;
}
Now if i call this method with id 3 like
$this->getData(3); // has a parent
It will return like that
Array(
[0]=>name1
)
But i want like below
Array(
[1]=>name3,
[0]=>name1
)
I know i have redefine array if we have parent but how i manage it.
i have used array_push php function but its not work with my condition.

foreach ($fetchAllDatas as $fetchAllData)
{
$array[$fetchAllData->parent_id] = $fetchAllData->name;
if($fetchAllData->parent_id > 0)
array_push($array,$this->getData($fetchAllData->parent_id));
}
return $array;
1)Because you do $array[$fetchAllData->parent_id] = $fetchAllData->name; in the if and in the else, you do this in both cases so put out of if..else.
2) Try to push the result of your second call in the original array to get what you want.

you have unique ID in your table, so if you call your query it will always return only one result. Maybe you wanted to write query this way:
$sql = "SELECT * from table_name when parent_id = ".$id;
if you want to get the result with given ID and his parent, you should add this after calling $this->fetchSharedFolder(...);
$array = array_merge($array, $this->getData($fetchAllData->parent_id));

Related

How to get name from id in array using query?

I had array values as cause
Ex: $cause = $_REQUEST['cause'];
ie., $cause = 2,3,4
How to get that array value cause name from query
My table name is 'cp_cause'
How to get the 2,3,4 cause name from the above table.
My sample query model in thinkphp is
$cause_name = $GLOBALS['db']->getAll("select category from ".DB_PREFIX."category where id = '".$cause."'");
i want the name of labour, health, women
If I get it right: you get comma separated Ids and want to query this?
SELECT * FROM cp_cause WHERE id IN (2, 3, 4)
PHP:
$cpCauses = $GLOBALS['db']->getAll("select * from cp_cause where id in('".$cause."')");
The result should be a list, containing the matching rows. But we do not know, what your getAll-Method returns!
Example: if result is an array, you can iterate:
foreach($cpCauses as $cause) {
echo $cause['cause_name'];
}
You need to create string like '2','3','4' for checking with MySql in clause.
For e.g.
<?php
$cause = array();
$cause[] = '2';
$cause[] = '3';
$cause[] = '4';
$sql_where = array();
foreach($cause as $values){
$sql_where[] = "'".$values."'";
}
$sql_where = implode(",",$sql_where);
$cause_name = $GLOBALS['db']->getAll("select category from ".DB_PREFIX."category where id in '".$sql_where."'");
?>

Select value from foreach result

Hi is there a way to get the value from each foreach result.
For Example I have a table named tblsamp.
id | data |
1 | d1 |
2 | d2 |
3 | d3 |
then put some query:
$query = $this->db->query("SELECT * FROM tblsamp");
foreach ($query->result() as $row){
echo $row->data .'<br>';
}
Result is:
d1
d2
d3
Now what I want is I want to get the value of the first result and compare the value from another table, and so on...
For Example:
if('d1' == '(value from another table)'{
\\do something here
} else if ('d2' == '(value from another table)'{
\\and so on.....
}
how can I do this guys? TIA!.
It looks like you are using codeigniter based off the $this->db->query syntax. With codeigniter you can change a table into an array using $query->result_array().
If you are sure both tables have the same amount of rows, you can use something like the following.
$query = $this->db->query("SELECT * FROM tbl1");
$table1 = $query->result_array();
$query = $this->db->query("SELECT * FROM tbl2");
$table2 = $query->result_array();
for ($x = 0; $x <= count($table1); $x++) {
if ($table1[$x] === $table2[$x]) {
//DO SOMETHING HERE
}
}
If $table1 might have more rows than table2, I would change it to
$query = $this->db->query("SELECT * FROM tbl1");
$table1 = $query->result_array();
$query = $this->db->query("SELECT * FROM tbl2");
$table2 = $query->result_array();
for ($x = 0; $x <= count($table1); $x++) {
if (isset($table1[$x]) && isset($table2[$x])) {
if ($table1[$x] === $table2[$x]) {
//DO SOMETHING HERE
}
} else {
break;
}
}
You can find you have matches in 2 tables however you may want to do more research about How SQL query can return data from multiple tables
How can an SQL query return data from multiple tables
This may work for your basic example
$query = $this->db->query("SELECT * FROM tblsamp,tblother");
$rst = mysql_query($query);
if(mysql_affected_rows() > 0) {
while($row = mysql_fetch_array($rst)) :
if($row['data'] == '$row['otherdata']') {
echo 'you got a match' . $row['data'] . ' In table sample to ' . $row['otherdata'] . ' In other table<br>';
}
else {
echo ' no match found in results;
}
}
endwhile;
You could add a query within your query, but this is not recommended -- things can get REALLY slow. It might be something like this:
// your original query
$query = $this->db->query("SELECT * FROM tblsamp");
foreach ($query->result() as $row){
// for each record in your original query, we run a new query derived from the result
// OBVIOUSLY you need to change this line of code to be specific to
// your database table's structure because some_col is probably not
// the name of a column in your database
$subquery = $this->db->query("SELECT * FROM other_table WHERE foo=" . $row->some_col);
$subrows = $subquery->result();
// output $subrows here?
// note that $subrows might be an array with any number any number of records
}
the exact code will depend on the db classes you are using. It's codeigniter, if I'm not mistaken? EDIT: it is codeigniter.
The correct solution here is going to depend on your database table definitions. I would strongly suggest creating a JOIN using CodeIgniter, but can't offer much more advice without some idea of what your db structures are going to look like and how many records in the second table exist for each record in the first table.

sql results from a table matching field from another table including sub fields

using codeigniter query i am unable to get appropriate results
i need to get results of a table this way
$catid=$_POST['category'];
$new_id = select catid from categories_table where catid='$catid' and parent='$catid';
so it will add also include results of other cats have $cadid as parent
Select * from articles_table where catid = '$new_id';
i am trying in codeigniter like this
$p=$this->input->post('category');
$this->db->select('catid');
$this->db->where('parent',$p);
$this->db->where('catid',$p);
$query = $this->db->get('categories_table');
if($query->num_rows()>0)
{
foreach($query->result() as $row)
$new_id[]=$row->catid;
}
$this->db->where('catid',$new_id);
$this->db->where('status',1);
$this->db->order_by('time_added', 'desc');
$res = $this->db->get('articles_table');
$query_res= $res->result();
it gives the error Message: Trying to get property of non-object
cats table
catid -- parent -- name
1 -- 0 -- first cat
2 -- 1 -- cat child of first
Article table
id -- catid - content
1 -- 2 -- first article
2 -- 1 -- second article
if i query where cat id = 1 it should return results from catid 2 too as 2 is child of one
I would try using the model something like this:
$p = $this->input->post('category');
$query = $this->db
->select('catid')
->where('parent',$p)
->or_where('catid',$p)
->get('categories_table');
$data = array();
if($query->num_rows())
{
foreach($query->result() as $row)
{
$res = $this->db
->where('catid',$row->catid)
->where('status',1)
->order_by('time_added', 'desc')
->get('articles_table');
foreach ($res->result() as $article_data)
{
$data[] = $article_data;
}
}
}
return $data;
The code first checks for categories where $p is EITHER equal to catid OR parent in the categories_table. Then checks for articles that has the same catid as the category and adds all articles to an array, $data.

When i use if else condition in query based on condition, how can i get that value on view in PHP CODEIGNITER

I am confuse with this problem in mysql, I have two table, "A" and "B"
TableA:
S.No contact1 contact2 status
1 Blbh eeee 1
TAbleB:
S.No Phone1 phone2
1 ddd ssss
From this table i am going to get value, from TableA ia m going to check
if (status == 1)
{
run tableA;
}
else
{
run table b;
}
I am gone a return result of this query. In view, how to get value with respected column name. I have no idea of this, help me to get value in view.
public function contDetails($id){
$check = $this->db->query("SELECT contact_status FROM account WHERE id = '$id' ");
$str = $check->row();
$chk = $str->contact_status;
if($chk == 1){
$query = $this->db->query("SELECT * FROM account WHERE id = '$id'");
}else{
$query = $this->db->query("SELECT * FROM contact_details WHERE user_id = '$id'");
}
$run = $query->num_rows();
print_r($run);
}
You can use in your model
$query = $this->db->get(); //--- run the query ---//
return $query->result() //--- to get result in array of object ---//
and then in your view use foreach loop
foreach($results as $result){
echo $result->columnName;
}
have you already written the query in mysql? If yes and if you are concerned about whether the column name to use exist or not you can use isset...
in your view you can use like the following:
<?php
foreach($results as $result)
{
echo (isset($result['col1']))?$result['col1']:$result['col1_2'];
}
?>
And don't forget to use result_array() instsead of result in the controller

PHP - return SQL GROUP BY as array?

I'm trying to return a MySQL query using GROUP BY as a array.
My table looks like this:
user_id | type
--------------------
1 | test
1 | test
2 | test
1 | hello
1 | helloworld
And my code and query:
$number_of_workouts = array();
$query = mysqli_query(connect(),"SELECT type, COUNT(*) FROM `log` WHERE `user_id` = $user_id GROUP BY type");
$number_of_workouts = mysqli_fetch_assoc($query);
return $number_of_workouts;
This code above isn't returning a array with all types listed, it will only return the number of one type(assuming that $user_id = 1.
How can I return the result of the query as an array?
mysqli_fetch_assoc($query);
fetches 1 row only from the resultset
If you want ALL rows from the resultset, you have to loop for each row and add it to a stack like:
$number_of_workouts = array();
$query = mysqli_query(connect(),
"SELECT type, COUNT(*) AS count
FROM `log`
WHERE `user_id` = $user_id
GROUP BY type"
);
$array = array();
while ($number_of_workouts = mysqli_fetch_assoc($query)) {
$array[$number_of_workouts['type']] = $number_of_workouts['count'];
}
// Now you have all results like you want in the variable array:
print_r($array);
// print count of type test:
echo $array['test'];
Or you try out mysqli_fetch_all() (http://www.php.net/manual/en/mysqli-result.fetch-all.php)
(sorry for many updates)
You are fetching only first record here. Keep the fetching statement in while loop
while($number_of_workouts = mysqli_fetch_assoc($query))
{
echo "<pre>";
print_r($number_of_workouts);
}

Categories