How to iterate over an array of arrays - php

I'm hoping someone can help.
I'm sure its just a simple one that I just can't work out for some reason.
Basically I have up a class that handles all my database functions (connect, select, insert, update).
In the select function I am returning an array.
public function getAll($table, $cols, $where, $limit, $order) {
// Set the query variables
if($cols == '') {
$cols = '*';
}
if($where!='') {
$where = ' WHERE '.$where;
}
if($limit!= '') {
$limit = ' LIMIT '.$limit;
}
if($order!='') {
$order = ' ORDER BY '.$order;
}
// Make the query string
$sql = 'SELECT '.$cols.' FROM '.$table.$where.$order.$limit;
//echo $sql;
// Set the query
$news_qry = mysql_query($sql);
// Set the array
$rows = array();
// Run a loop through the results
while($item = mysql_fetch_object($news_qry))
{
// Add each row to an array.
$rows[] = $item;
}
return $rows;
}
This function is working as I can print an array. See below:
Array ( [Gallery_id] => 1 [Gallery_Name] => Test [Gallery_FolderName] => Test Folder )
But when I go to use the object -
$arr_GalleryInfo = $dataObj->getAll('tbl_Gallery', '', '', '', '');
Within the for each loop (see below) I only get the first letter of the result from the database.
<?php
foreach ($arr_GalleryInfo[0] as $arrGallery)
{
?>
<tr>
<td>
<?php echo $arrGallery['Gallery_Name']; ?>
</td>
<td>
<?php echo $arrGallery; ?>
</td>
<td>
<?php echo $arrGallery; ?>
</td>
</tr>
<?php
}
?>
Any help would be great.
Thanks.

Replace:
foreach ($arr_GalleryInfo[0] as $arrGallery)
{
etc...
with:
foreach ($arr_GalleryInfo as $arrGallery)
{
etc...

Well, your big issue is that you're trying to iterate over the 0-index of an array.
foreach ($arr_GalleryInfo[0] as $arrGallery) // get rid of the `[0]`.
That will make it so that you actually get some legit iteraction, but there are some other things which are gotchas that you're about to hit.
// this will output `Array`. You want $artGallery['Gallery_FolderName']
// or $artGallery['Gallery_id']
echo $arrGallery;
Of course, you could avoid that whole second issue with a nested loop:
foreach ($arr_GalleryInfo as $arrGallery) {
echo '<tr>';
foreach($arrGallery as $val ) echo "<td>$val</td>";
echo '</tr>';
}
If $news_qry = mysql_query($sql); fails, you'll have nothing to warn you if something breaks. You should make it: $news_qry = mysql_query($sql) or die(mysql_error());
And, of course, you should use mysql_real_escape_string on all of your db inputs.

Related

Why is the array is always empty at this point despite the fact that I added data there?

$result = mysqli_query($con, "SELECT * FROM users");
$usersArray=[];
tableArrayPushData($result, $usersArray);
function tableArrayPushData($result, $tableArray){
while ($row = $result->fetch_assoc()) {
$str = '';
foreach ($row as $value) {
$str = $str.$value.'|';
}
$newStr = rtrim($str, "| ");
array_push($tableArray,$newStr);
}
}
for ($i=0; $i<count($usersArray); $i++){//array is always empty at this point
echo "Ok";
echo "<br>";
}
I don't understand why, but usersArray is empty despite the fact that I added data there.
The MySQL table has rows with data, so it can't be empty.
You should use the & operator to allow the function to access the outer variable, like this:
function tableArrayPushData($result, &$tableArray) {}
Or use return.

echo result from function from table in database

so i am learning to write functions. Now i know how to echo stuff into a foreach but i do not know how to print a single row outside a foreach (like i only have 1 row in my table and want to print the id and username out of it) how do i do this?
my function :
public function gegevens(){
$stmt = $this->conn->prepare("SELECT * FROM gegevens_locatie");
$stmt->execute();
$result = $stmt->fetchAll();
//Return result
return $result;
}
when i call that function on my other page i call it with :
require_once 'class/class.overig.php';
$overig = new OVERIG();
i have tried stuff like print_r($overig->gevens()) and with a echo but i cant seem to make it work. So how can i do this?
Because you are using ->fetchAll() you will always get an array of rows even if there is only one row returned. You also need to use the correct method name on your call.
So all you need to do is
$arr = $overig->gegevens();
if ( count($arr) == 1 ) {
echo $arr[0]['id'];
echo $arr[0]['username'];
}
if ( count($arr) > 1 ) {
foreach ( $arr as $row) {
echo $row['id'];
echo $row['username'];
}
}
"I have tried stuff like print_r($overig->gevens()) and with a echo but i cant seem to make it work. So how can i do this?"
The Name of the Method you called does NOT match the Name of the Method in your Class. In your Class, You have: gegevens() but in your Call: you specified: gevens(). Unless this is just a normal Typo; you should start your Debugging from there.
In other words; your Call should have been: print_r($overig->gegevens()).
THE CLASS:
<?php
class OVERIG{
public function gegevens(){
$stmt = $this->conn->prepare("SELECT * FROM gegevens_locatie");
$stmt->execute();
$result = $stmt->fetchAll();
//Return result
return $result;
}
}
USING THE CLASS:
<?php
require_once 'class/class.overig.php';
$overig = new OVERIG();
$result = $overig->gegevens();
// TRY DUMPING THE VARIABLE: $result:
var_dump($result);
// TO ECHO OUT SOME VALUES:
if($result){
foreach($result as $key=>$item){
if(is_string($item)){
echo $item;
}
}
}

html php echo on div

here i have a simple function but this show me data fom sql only in 1 div i want to show [ on div 1 show 1 data, in other div show 2 data, etc etc]...
function load_post($added_by)
{
global $Connection;
$SQL_3 = mysqli_query($Connection, "SELECT * FROM posts WHERE added_by='$added_by'");
$NumPosts = mysqli_num_rows($SQL_3);
$out['num_posts'] = $NumPosts;
while($Fetch_3 = mysqli_fetch_array($SQL_3))
{
$out['id'] = $Fetch_3['id'];
$out['text'] = $Fetch_3['text'];
$out['added_by'] = $Fetch_3['added_by'];
$out['mp4'] = $Fetch_3['mp4'];
$out['likes'] = $Fetch_3['likes'];
$out['youtube'] = $Fetch_3['youtube'];
$out['image'] = $Fetch_3['image'];
$out['date_added'] = $Fetch_3['date_added'];
return $out;
}
}
index.php.
$posts = load_post('gentritabazi');
<div class="settings_forms_content">
<?php echo $posts['text']; ?>
</div>
return finish immediately your function so only one iteration is done. You need to save your results in array and then after loop return that array, sth like this:
$out = array();
while($Fetch_3 = mysqli_fetch_array($SQL_3))
{
$out[] = $Fetch_3;
}
return $out;
and display:
$posts = load_post('gentritabazi');
foreach ($posts as $post) {
echo '<div class="settings_forms_content">';
echo $post['text'];
echo '</div>';
}
Lots to amend, so I commented the code rather than write an essay
function load_post($con, $added_by)
{
// dont use globals, use parameters
//global $Connection;
// select only what you want to see not `*`
$SQL_3 = mysqli_query($con, "SELECT id, text, added_by, mp4,
likes, youtube, image, data_added
FROM posts
WHERE added_by='$added_by'");
// not needed
//$NumPosts = mysqli_num_rows($SQL_3);
//$out['num_posts'] = $NumPosts;
while($Fetch_3 = mysqli_fetch_array($SQL_3))
{
/*
* THsi code would overwrite the last iteration of the while loop
$out['id'] = $Fetch_3['id'];
$out['text'] = $Fetch_3['text'];
$out['added_by'] = $Fetch_3['added_by'];
$out['mp4'] = $Fetch_3['mp4'];
$out['likes'] = $Fetch_3['likes'];
$out['youtube'] = $Fetch_3['youtube'];
$out['image'] = $Fetch_3['image'];
$out['date_added'] = $Fetch_3['date_added'];
*/
// now as you SELECT only what you want yo can simply do
$out[] = $Fetch_3;
//return $out; instantly terminates the function
}
return $out; // return the array
}
Now call your function
// pass the connection as a parameter
$posts = load_post($Connection, 'gentritabazi');
// if you want to know how many results were returned
$result_count = count($posts);
// process the returned array
foreach ( $posts as $post ) {
echo '<div class="settings_forms_content">';
echo $post['text'];
echo '</div>';
}
Your script is at risk of SQL Injection Attack
Have a look at what happened to Little Bobby Tables Even
if you are escaping inputs, its not safe!
Use prepared statement and parameterized statements
$posts = load_post('gentritabazi');
foreach ($posts ['text'] as $postText){
echo "<div class='settings_forms_content'>$postText</div>";
}
first line calls your function which returns the array $posts
this array looks like:
$posts = array(
"id" => array of ids
"text" => array of texts
...
);
if you want to access the third text it would be like this:
$posts ['text'][3]
the foreach iterates to your $post array with index "text" -> which is also an array
every value in this array, $post['text'] will be referenced with $postText -> that means:
$post['text'][1] = $postText (first time looping through foreach-loop)
$post['text'][2] = $postText (secondtime looping through foreach-loop)
..
if you are familiar with loops, a foreach is just the short version for
for(var $i=0;$i<length($posts['text'];$i++){
echo "<div class='settings_forms_content'>$posts['text'][i]</div>";
}

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.

Alphabetical lists in CodeIgniter

Wondering how I can do this with CodeIgniter?
Any help is greatly appreciated!
Thanks.
There's no built in function to do this. You'll have to loop through an sql query to do this...
Select * from table order by field asc
foreach ( $result as $thing ) {
if ( $thing['name'][0] != $first_letter) {
echo '<h2>' . $thing['name'][0] . '</h2>';
$first_letter = $thing['name'][0];
}
echo $result['thing'];
}
this is just a rough example...never echo html like that.
//in model
public function alphaDirectory(){
// Query for data
$sql = "SELECT SUBSTRING(column_name,1,1) AS letter, column_name,column_link FROM table ORDER BY column_name";
$query = $this->db->query($sql);
$columnByName="";
foreach ($query->result() as $row)
{
$columnByName[$row->letter][] = array($row->column_name,$row->column_link);
}
return $columnByName;
}
//in controller call the model and pass the return array to view
in view
$V){
echo "".strtoupper($k)."";
foreach($v as $links){
echo "".$links[0]."";
}
echo ''
}
?>
use css to decorate to get exact match as you are looking

Categories