passing array value as parameter in function - php

I want to pass the array of values fetched from the database as a parameter to a php function.If I echo the value, it doesn't display it.
<?php
include "config.php";
$sql="select * from project where comp_id='1'";
$sql1=mysql_query($sql);
$rows=array();
while( $fet=mysql_fetch_array($sql1))
{
$rows[]=$fet;
}
echo fun_parameter($rows);
function fun_parameter($rows)
{
echo" rows". $rows['start_date']."values"; // not working
}
foreach($rows as $row)
{
echo $name=$row['start_date']; /working
}
?>

Simple looping can give the result,
function fun_parameter($rows)
{
foreach($rows as $row)
{
echo $row['p_id']; /working
echo" rows". $row['start_date']."values";
}
//echo" rows". $rows['start_date']."values"; // not working
}
If you want to fetch particular column from multi dimensional array then take a look into array_column() in php

in your code you are trying to echo an array $row without its index specified, you need to loop through that array as it has got mulitple value, use the following code:
<?php
include "config.php";
$sql="select * from project where comp_id='1'";
$sql1=mysql_query($sql);
$rows=array();
while( $fet=mysql_fetch_array($sql1))
{
$rows[$i]['start_date']=$fet['start_date'];
}
echo fun_parameter($rows);
function fun_parameter($rows)
{
foreach($rows as $row)
{
echo" rows". $row['start_date']."values"; // use loop it will work
}
}
foreach($rows as $row)
{
echo $name=$row['start_date']; // i left this foreach here because you had it in your code
}

Related

Filtering an array with foreach and for loop

I'm pulling data from mssql database into an array called
$results2
I need to echo out each 'Item' only one time, so this example should only echo out:
"52PTC84C25" and "0118SGUANN-R"
I can do this easily with:
$uniqueItems = array_unique(array_map(function ($i) { return $i['ITEM']; }, $results2));
The issue is when i try to echo out the other items associated with those values. I'm not sure how to even begin on echoing this data. I've tried:
foreach($uniquePids as $items)
{
echo $items."<br />";
foreach($results2 as $row)
{
echo $row['STK_ROOM']."-".$row['BIN']."<br />";
}
}
This returns close to what I need, but not exactly:
This is what I need:
Assuming your resultset is ordered by ITEM...
$item = null; // set non-matching default value
foreach ($results2 as $row) {
if($row['ITEM'] != $item) {
echo "{$row['ITEM']}<br>"; // only echo first occurrence
}
echo "{$row['STK_ROOM']}-{$row['BIN']}<br>";
$item = $row['ITEM']; // update temp variable
}
The if condition in the code will check if the ITEM has already been printed or not.
$ary = array();
foreach($results2 as $row)
{
if(!in_array($row['ITEM'], $ary))
{
echo $row['STK_ROOM']."-".$row['BIN']."<br />";
$ary[] = $row['ITEM'];
}
}

php empty result for language table

I am trying to add multiple language options with the database. I created a table as follows.
And my PHP function is:
public function Languages(){
$query=mysqli_query($this->db,"
SELECT * FROM languages") or die(mysqli_error($this->db));
while($row=mysqli_fetch_array($query,MYSQLI_ASSOC)) {
$data[]=$row;
}
if(!empty($data)) {
// Store the result into array
return $data;
}
}
So also I used the following code for showing result but I am getting the empty result:
<?php
$language = $ReSult->Languages();
$userLanguage = 'english';
echo $language['your_family'][$userLangauge];
?>
I know if I use $language['1'][$userLanguage]; then I get a result but I don't want to use id's here. Is there any way to do that to show results without using ids?
You could store the results in an associative array:
while ($row = mysqli_fetch_array($query,MYSQLI_ASSOC)) {
$data[$row['lang_key']] = $row;
}
This way, you can access the data directly by its key:
echo $language['your_family'][$userLangauge];
checkout this
function getIndex($language , $key)
{
foreach ($language as $row)
{
if (strcmp($row["lang_key"] , $key)==0) {
return $row["id"]
}
}
return null;
}
...
echo $language[getIndex($language , "your_family")][$userLanguage];
You can try like this way,
while ($row = mysqli_fetch_assoc($query)) {
$data[$row['tagKey']] = $row;
}

how to iterate arraylist in php

What my code does:
I am returning arraylist from a php method -->method name:- getSubjectInfo().
And in my (Index.php) page i am getting this arraylist values in a $results variable. Here i am stuck how to iterate the arraylist values in the index.php page?.
My Problem: How to iterate the arraylist ($results) in my index.php page? Please see my below mention code
i have used $results = $sub_info->fetchAll(PDO::FETCH_OBJ); in my method for generating list.
index.php
<?php
include_once '../../classes/conn/connection.php';
include_once '../../classes/setups/Subdetails_setup.php';
$con = new connection();
$info = new Subdetails_setup($con);
$results = $info->getSubjectInfo();
echo $results; //this is returning a list of objects. My problem is how can i iterate these values
?>
and i tried like this echo (each($results)); but this is printing my values in a single line
like this:- Subject Name 1 FIction1Non FIction2
& My Subdetails_setup.php Class is having method getSubjectInfo() :-
function getSubjectInfo()
{
$sub_info = $this->con->prepare("SELECT * FROM subjectdetails");
$sub_info->execute();
$results = $sub_info->fetchAll(PDO::FETCH_OBJ);
foreach ($results as $key)
{
echo $key->subject_name;
echo $key->subject_id;
}
// Return the result array
return $results;
}
Please help me for this.
-Ashutosh
This code in your Subdetails_setup.php needs to be removed, and put on the index.php. You don't need it in subdetails, just return the result.
foreach ($results as $key)
{
echo $key->subject_name;
echo $key->subject_id;
}
If you want to check if it's all working, change your index.php and add this line:
$results = $info->getSubjectInfo();
var_dump($results);
Now that var_dump() works, replace the line with the earlier code, modified to show a table:
foreach ($results as $key)
{
echo "<tr>";
echo "<td>".$key->subject_name."</td>";
echo "<td>"$key->subject_id."</td>";
echo "</tr>";
}

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);
}

Displaying an associative array in PHP

I am trying to build a function that extracts information from a database and inserts it into an associative array in PHP using mysql_fetch_assoc, and return the array so another function can display it. I need a way to display the returned assoc array. This should be a different function from the first one
print_r($array) will give nicely formatted (textually, not html) output.
If you just want information about what is in the array (for debugging purposes), you can use print_r($array) or var_dump($array), or var_export($array) to print it in PHP's array format.
If you want nicely formatted output, you might want to do something like:
<table border="1">
<?php
foreach($array as $name => $value) {
echo "<tr><th>".htmlspecialchars($name).
"</th><td>".htmlspecialchars($value)."</th></tr>";
}
?>
</table>
This will, as you might already see, print a nicely formatted table with the names in the left column and the values in the right column.
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $column => $value) {
//Column name is in $column, value in $value
//do displaying here
}
}
If this is a new program, consider using the mysqli extension instead.
Assuming you've made the call, and got $result back:
$array = new array();
while($row = mysql_fetch_assoc($result)){
$array[] = $row;
}
return $array;
This should get you going:
$rows = mysql_query("select * from whatever");
if ($rows) {
while ($record = mysql_fetch_array($rows)) {
echo $record["column1"];
echo $record["column2"];
// or you could just var_dump($record); to see what came back...
}
}
The following should work:
$rows = mysql_query("select * from whatever");
if ($rows) {
$header = true;
while ($record = mysql_fetch_assoc($rows)) {
if ($header) {
echo '<tr>';
foreach (array_keys($record) AS $col) {
echo '<td>'.htmlspecialchars($col).'</td>';
}
echo '</tr>';
$header = false;
}
echo '<tr>';
foreach (array_values($record) AS $col) {
echo '<td>'.htmlspecialchars($col).'</td>';
}
echo '</tr>';
}
}
(Yes, blatant mod of Fosco's code)
This should print the column headers once, then the contents after that. This would print just whatever columns were retrieved from the DB, regardless of the query.

Categories