Reputation: 259
When I am fetching data from database in array it's showing only one element of each column. I am using below query:
$stmt = $conn_obj->select(' user ',' * ',' status = "updated" ', $order=NULL, $group=null, $fromRecordNum.','.$recordsPerPage);
and select function is below:
private function tableExists($table) {
//$this->con = $this->createconnection();
$query = 'SHOW TABLES FROM ' . $this->db . ' LIKE "'.trim($table).'"';
//echo ''.$query;
$tablesInDb = mysqli_query($this->con, $query);
if ($tablesInDb) {
if (mysqli_num_rows($tablesInDb) == 1) {
//echo ''.mysqli_num_rows($tablesInDb);
return true;
}
else {
return false;
}
}
}
public function select($table, $row = '*', $where= null,$order=null,$group=null, $limit=null, $join=null){
//$this->con = $this->createconnection();
//echo $join;
$q = 'select'.$row.' from '.$table;
//print_r($q);
if($join != null){
$q .= ' join '.$join;
}
if($where != null){
$q .= ' where '.$where;
print_r($q);
}
if($group != null){
$q .= 'group by'.$group;
//print_r($q);
}
if($order != null){
$q .= 'order by'.$order;
}
if($limit != null){
$q .= 'limit '.$limit;
print_r($q);
}
if ($this->tableExists($table)) {
$query = mysqli_query($this->con, $q) or die(mysql_error());
//print_r($query);
if ($query) {
$this->numResults = mysqli_num_rows($query);
//echo $this->numResults;
for ($i = 0; $i < $this->numResults; $i++) {
$r = mysqli_fetch_array($query);
$key = array_keys($r);
for ($x = 0; $x < count($key); $x++) {
// Sanitizes keys so only alphavalues are allowed
if (!is_int($key[$x])) {
if (mysqli_num_rows($query) > 1)
$this->result[$i][$key[$x]] = $r[$key[$x]];
else if (mysqli_num_rows($query) < 1)
$this->result = null;
else
$this->result[$key[$x]] = $r[$key[$x]];
}
}
}
//print_r($this->result);
return $this->result;
} else {
return false;
}
} else{
return false;
}
}
I am fetching it with foreach loop as follow:
foreach($stmt as $row)
{
echo $row['user_Id'];
}
output is= 7 t : 2 2 2 u W u 2
and if I print whole array with print_r($row)
then
output is= test ::1 2015-07-30 11:42:09am 2015-07-29 12:42:09pm 2015-07-30 12:28:57pm updated call_activated uninstall 2015-07-30 12:31:07pm.
If database has only one row with specified query then above problem is creating.
But in the case of two row with the specified query, its working fine as I want.
Upvotes: 0
Views: 58
Reputation: 1216
For multiple results, you are getting an array of arrays of elements.
For a single result, you are getting an array of elements.
So, for a single element, you have one foreach loop too many.
if in your example:
foreach($stmt as $row) {
echo $row['user_Id'];
}
Assuming $stmt
contains the return value of your query:
foreach($stmt as $row) {
if (isset($row['user_Id'])) {
// do something with one single result record
} else {
foreach ($row AS $innerRow) {
// do something with each result record
}
}
}
Upvotes: 1