MySQLi - search through an array - php

I have the following code:
function resultToArray($result) {
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
// Usage
$query = 'SELECT q17, COUNT(q17) FROM tresults GROUP BY q17';
$result = $mysqli->query($query);
$rows = resultToArray($result);
//print_r($rows); // Array of rows
$result->free();
Brings back the following (only an excerpt):
Array ( [0] => Array ( [q17] => [COUNT(q17)] => 7 ) [1] => Array ( [q17] => Admin & Clerical [COUNT(q17)] => 118 )......etc.
What I am struggling with is how to then return the data, basically, what I need is some code to pull out the data as follows:
WHERE Array = Admin & Clerical BRING BACK THE COUNT(q17) number
How do I search through the array, normally, I'd use something like:
if($rows['q17']==$q[$i]){echo$rows['COUNT(q17)'];}
But this doesn't work - I assume because there are two sets of data within each part of the array? Not sure how to deal with this.

You can achieve this by using MYSQL itself, by using HAVING clause instead of WHERE.
To do this rewrite your query like this.
$query = 'SELECT q17, COUNT(q17) as qcount FROM tresults GROUP BY q17 HAVING q17="Admin & Clerical" ';
echo $row[0]['qcount']; //return 118
if you still want to it with PHP after getting the result from the database, it's how it done:
function get_q17_count($rows, $q17){
foreach ($rows as $onerow) {
if($onerow['q17'] == $q17){
return $onerow['COUNT(q17)'];
}
}
}

function resultToArray($results) {
$rows = array();
while($row = $results->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
// Usage
$querys = 'SELECT q17, COUNT(q17) FROM tresults GROUP BY q17';
$results = $mysqli->query($querys);
$rows = resultToArray($results);
//print_r($rows); // Array of rows
$results->free();
function searchForId($id, $array) {
foreach ($array as $key => $val) {
if ($val['q17'] === $id) {
return $val['COUNT(q17)'];
}
}
return null;
}
Called the function using:
$id = searchForId($q[$i], $rows);echo " (".$id.")";

Related

Mongo db cursor count not working properly?

I have written following code in php and am using mongo db as database
$projection = array("broadcast_id" => 1,"studentList" => 1);
$query = array('broadcast_id'=> $broadcast_id);
$count = $this->collection->find($query)->count();
$cursor = $this->collection->find($query,$projection);
$result = array();
foreach($cursor as $row)
{
$idstring = trim($row["studentList"]);
$idstring = preg_replace('/\.$/', '', $idstring);
$idarray = explode('|', $idstring);
foreach($idarray as $studentId)
{
$this->StudentCollection = $this->db->studentTbl;
$StudentCursor= $this->StudentCollection->find(array("student_id" => $studentId));
if($StudentCursor->count() > 0)
{
foreach ($StudentCursor as $k => $srow) {
array_push($result, $srow);
}
}
else
{
array_push($result, array("datanotfound"=>1));
}
}
}
return json_encode($result);
After fetching "studentList" from broadcastTbl table and $idstring has "5042|5043|5044" values which are student ids of studentTbl. Now I am trying to fetch corresponding students details by splitting them one by one on the basis of "|". After that I am trying to push them in array $result.
It always displays $StudentCursor->count() as "1" and never enter in else block even if find() query fails to find record and then it displays output as [] i.e it always stay in if statement !!!
Please help me in tracking out what is wrong in the code and writting it efficiently!!!

Unable to push all expected data to an array from collection using foreach loop in PHP

I am trying to add data to an array $result where each value is a string $idstring which will contain the employees ids like "999|888|777". The data is fetched from broadcastTbl collection from a MongoDB. I need to fetch each employee's corresponding details in a loop and push to $result. I am successfully fetching the data, but the trouble I am facing is in the below code where only one employees' data is getting pushed to the $result array.
$projection = array("broadcast_id" => 1, "employeeList" => 1);
$query = array("broadcast_id" => $broadcast_id);
$count = $this->collection->find($query)->count();
$cursor = $this->collection->find($query, $projection);
$result = array();
foreach($cursor as $row)
{
$idstring = trim($row["employeeList"]);
$idstring = preg_replace('/\.$/', '', $idstring);
$idarray = explode('|', $idstring);
foreach($idarray as $employeeId)
{
$this->EmployeeCollection = $this->db->EmployeesTbl;
$EmployeeCursor= $this->EmployeeCollection->find(array("EmployeeNumber" => $employeeId));
$EmployeeCursorCount= $this->EmployeeCollection->find(array("EmployeeNumber" => $employeeId))->count();
if($EmployeeCursor->count() > 0)
{
array_push($result,$EmployeeCursorCount);
foreach ($EmployeeCursor as $k => $row) {
array_push($result, $row);
}
}
else
{
array_push($result, array("datanotfound"=>1));
}
return json_encode($result);
}
}
You are returning too early.
Move return json_encode($result);
After the outer-most foreach loop.

Return unique values from a column with multiple values per field

I have a database table with a column where multiple strings are stored in each field, separated by a ;
I need to get a list of all unique values in that column. I know there has to be an easier way to do this, but I can't find my answer anywhere. Here is what I'm doing so far:
$result = mysql_query("SELECT DISTINCT column FROM modx_scripture_table WHERE column!=''", $con);
$filter_all = array();
while($row = mysql_fetch_array($result))
{
$filter_all[] = $row;
}
function array_flatten($array) {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, array_flatten($value));
}
else {
$result[$key] = $value;
}
}
return $result;
}
$filter_flat = array_flatten($filter_all);
function array_explode($array) {
$result = array();
foreach ($array as $key => $value) {
$result[$key] = explode(';',$value);
}
return $result;
}
$filter_sploded = array_explode($filter_flat);
$filter_full = array_flatten($filter_sploded);
$filter_final = array_unique($filter_full);
print_r($filter_final);
Everything seems to be working except the array_unique. I'm still getting duplicate strings in $filter_final. What am I doing wrong?
After exploding the string use array_unique() for fnding unique values in an array.
Example:
$arr=array('1','2','3','4','5','3','1');
print_r(array_unique($arr));
Output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)

Creating Structured array by Recursive function

I have a table
Which I want show recursively like below picture
I am using a recursive function in php
function reccall($cat_id)
{
global $no,$recArray;
$sql = "SELECT a.*
FROM cat_master
WHERE
parent_id = $cat_id
ORDER BY
id ASC
";
$result = mysql_query($sql) or die("Could not fetech Recursively");
while($row = mysql_fetch_object($result))
{
$recArray[$no]['value'] = mysql_real_escape_string($row->value);
$recArray[$no]['id'] = $row->id;
++$no;
reccall($row->id);
}
return $recArray;
}
but I am not able to generate a structured array like how the order is not the picture. A simple array is created all the time. Can anyone help me with creating the structured array like the order shown above.
<?
// I identified this function separately because it is performed only once, for preparing data
// It's collect an array of all parents in the correct order for each id
function dest($array) {
foreach($array as $key=>$value) {
if($value['pid']==0) continue;
$pid = $key;
$array[$key]['dest'] = array();
while ( $pid = $array[$pid]['pid'] ) {
if($key == $pid) exit("this tree is broken");
$array[$key]['dest'][] = $pid;
}
}
return $array;
}
// Recursive function that puts the items in the correct tree. removes the parameter dest.
function tree($array) {
foreach($array as $key=>$value) {
if( is_array($value['dest']) && !empty($value['dest']) ) {
$pid = array_pop($value['dest']);
if( empty($value['dest']) ) unset($value['dest']);
$array[$pid]['childrens'][$key] = $value;
$array[$pid]['childrens'] = tree($array[$pid]['childrens']);
unset($array[$key]);
}
}
return $array;
}
$array = array(
1 => array(
'title'=>'q',
'pid'=>0,
),
2 => array(
'title'=>'w',
'pid'=>1,
),
3 => array(
'title'=>'e',
'pid'=>0,
),
4 => array(
'title'=>'r',
'pid'=>2,
),
5 => array(
'title'=>'t',
'pid'=>1,
),
);
$tree = tree( dest($array) );
echo '<pre>';
print_r($array);
print_r($tree);
?>
By the way, I should note that these arrays are not very useful. Better to use the result of the function dest().
use this function instead of your function and your problem will be solved I hope
function reccall($cat_id)
{
$sql = "SELECT a.*
FROM cat_master
WHERE
parent_id = $cat_id
ORDER BY
id ASC
";
$result = mysql_query($sql) or die("Could not fetech Recursively");
while($row = mysql_fetch_object($result))
{
$recArray[$no]['main']['value'] = mysql_real_escape_string($row->value);
$recArray[$no]['main']['id'] = $row->id;
$recArray[$no]['child'] = reccall($row->id);
++$no;
}
return $recArray;
}

Echo values of arrays?

I want to echo the values of all arrays that has been returned from a search function. Each array contains one $category, that have been gathered from my DB. The code that I've written so far to echo these as their original value (e.g. in the same form they lay in my DB.) is:
$rows = search($rows);
if (count($rows) > 0) {
foreach($rows as $row => $texts) {
foreach ($texts as $idea) {
echo $idea;
}
}
}
However, the only thing this code echoes is a long string of all the info that exists in my DB.
The function, which result I'm calling looks like this:
function search($query) {
$query = mysql_real_escape_string(preg_replace("[^A-Za-zÅÄÖåäö0-9 -_.]", "", $query));
$sql = "SELECT * FROM `text` WHERE categories LIKE '%$query%'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows['text'] = $row;
}
mysql_free_result($result);
return $rows;
}
How can I make it echo the actual text that should be the value of the array?
This line: echo $rows['categories'] = $row; in your search function is problematic. For every pass in your while loop, you are storing all rows with the same key. The effect is only successfully storing the last row from your returned query.
You should change this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
echo $rows['categories'] = $row;
}
mysql_free_result($result);
return $rows;
to this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
Then when you are accessing the returned value, you could handle it like the following...
foreach ($rows as $key => $array) {
echo $array['columnName'];
// or
foreach ($array as $column => $value) {
echo $column; // column name
echo $value; // stored value
}
}
The problem is that you have a multi-dimensional array, that is each element of your array is another array.
Instead of
echo $row['categories'];
try print_r:
print_r($row['categories']);
This will technically do what you ask, but more importantly, it will help you understand the structure of your sub-arrays, so you can print the specific indices you want instead of dumping the entire array to the screen.
What does a var_dump($rows) look like? Sounds like it's a multidimensional array. You may need to have two (or more) loops:
foreach($rows as $row => $categories) {
foreach($categories as $category) {
echo $category;
}
}
I think this should work:
foreach ($rows as $row => $categories) {
echo $categories;
}
If this will output a sequence of Array's again, try to see what in it:
foreach ($rows as $row => $categories) {
print_r($categories);
}

Categories