Query result giving out more than it should - php

I have this code in my class:
public function get_data(){
$sql = "select id_especialidad, descripcion from especialidad";
foreach($this->dbh->query($sql) as $row)
{
$this->rows[] = $row;
}
return $this->rows;
}
Now I use it from HTML file like this:
<select>
<?php
$datos = $db->get_data();
for($i=0;$i<sizeof($datos);$i++)
{
?>
<option value="<?php echo $datos[$i]["id_especialidad"]?>"><?php echo $datos[$i]["descripcion"]?></option>
<?php
}
?>
</select>
Now in the browser I see the select with the rows but in the first row is says: "Notice: Undefined index: descripcion in (file_path)"
I have 9 rows in my table but when I put this "print sizeof($datos)" it shows 11 rows.
What is happening?
is there another way to show this data?
Thanks!

Since I don't know where and how you're using or re-using $this->rows[] as you haven't posted about it, I will change a bit your code:
public function get_data()
{
$sql = "SELECT id_especialidad,
descripcion
FROM especialidad";
$result = array();
foreach($this->dbh->query($sql) as $row)
{
$result = $row;
}
return $result;
}
Given $this->dbh->query is the PDO query, if you print_r the result you get from get_data it should give you something similar to:
Array(
[0]=>Array([id_especialidad]=>1
[0]=>1
[descripcion]=>test
[1]=>test
)
[1]=>Array([id_especialidad]=>2
[0]=>2
[descripcion]=>test2
[1]=>test2
)
)
And you can easily read it like this:
<select>
<?php
$data = $db->get_data();
foreach ($data as $item)
{
?>
<option value="<?php echo $item["id_especialidad"]; ?>"><?php echo $item["descripcion"]; ?></option>
<?php
}
?>
</select>
If you're getting more than 9 results where it should have been only 9 I can only think there might be a problem with $this->rows[] not being cleared after used or something alike.

Related

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

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

array of data in a drop down menu

I am trying to get the area table of my database to display in a drop down menu but I am having trouble because it is an array.
In my controller I have: $data['city'] = $this->location->fetchCity();
but in my view when I go <?php echo $city; ?> I get this Array why?
Model:
public function fetchCity(){
$this->db->select('area');
$this->db->from('suburbs');
$query = $this->db->get();
if($query->num_rows() > 0)
{
$row = $query->result();
}
Update:
<select>
<?php foreach ($city as $key => $row): ?>
<option value="<?php echo $row['area'];?>"><?php echo $row['area'];?></option>
<?php endforeach; ?>
</select>
<?php echo $city[$key]; ?>
OR
<?php echo $city['area']; ?>
Since your function call returns an Array, this is how I suggest you print it out.
foreach ($city as $key=>$row)
{
echo $row->area;
}
Since your result is an Array of Objects, I'm sure this will get things right.

php function in a while Loop

i searched all over the web or i just don't see it.
I want to do the following:
<?php
function abc(){
$sql = "SELECT * FROM table";
$result = mysql_fetch_assoc($sql);
$data = mysql_fetch_assoc($result);
}
?>
<? while(abc()) : ?>
<?=article_title()?>
<?=article_content()?>
<?=endwhile;?>
Could somebody give me a direction and/or example?
Thank you very much
PHP does not have generator/iterator functions, so you cannot do that.
You can however return an array and iterate over that array:
function abc() {
// ...
$rows = array();
while($row = mysql_fetch_assoc($result)) { $rows[] = $row; }
return $rows;
}
foreach(abc() as $row) {
// do something
}
If the functions you call need access to the row, pass it as an argument. Using global variables for it would be very bad/nasty
have you tried to do something like that?
<?php
function getData(){
//get the data from the database
//return an array where each component is an element found
}
$elems = getData();
foreach($elems as $e){
doSomethingWith($e);
}

How to iterate over an array of arrays

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.

Categories