Apologize for the repeated question. Return multiple values from database with function. I tried executing code, the function returns one value, where I want all the values of id and name.
Database: id and name has 9 rows. Is there anything I was missing in my code.
function readdata() {
$sth = $db->execute('SELECT * FROM mynumbers m WHERE m.id>1 ORDER BY m.id ASC');
foreach ($sth as $s) {
$object = new stdClass();
$object->id = $s->id;
$object->name = $s->name;
return $object;
}
}
$rd = readdata();
echo $rd->id;
echo $rd->name;
May be something like this:
function readdata() {
$sth = $db->execute('SELECT * FROM mynumbers m WHERE m.id>1 ORDER BY m.id ASC');
$out = [];
foreach ($sth as $s) {
$object = new stdClass();
$object->id = $s->id;
$object->name = $s->name;
$out[] = $object;
}
return $out;
}
$rd = readdata();
//and here
foreach($rd as $obj){
echo $obj->id;
echo $obj->name;
}
This is more a suggestion than an answer. Why re-inventing the wheel? PDO already is capable of returning classes and also fetching all results into an array.
function readdata(PDO $db): array
{
$sth = $db->prepare('SELECT * FROM mynumbers m WHERE m.id>1 ORDER BY m.id ASC');
$sth->execute();
return $sth->fetchAll(PDO::FETCH_CLASS);
}
$objects = readdata($db);
$objects is now an array. Each element contains a stdClass object with each column name as property.
foreach($objects as $object) {
echo $object->id, PHP_EOL;
echo $object->name, PHP_EOL;
}
Your foreach loop intends to run through all values of the array $sth, but returns only with the FIRST one.
You can just return $sth to get the whole array, or build a new array and append to it:
$ret = array();
foreach ($sth as $s) {
...
$ret[] = $object;
}
and then
return $ret;
Related
Can you tell me why this returns only the last row of my query?
As you see I'm extracting as std class. Also I already tried different approaches like a foreach key=>value inside the while but it does not help. I can't populate $out correctly.
class myclass {
function Query($sql){
$results = $this->db->query($sql);
if (mysqli_num_rows($results)<1){
throw new Exception('NoResults');
}
$out = new stdClass;
while ($r = $results->fetch_object()){
$out = $r;
}
return $out;
$out = null;
}
}
}
---------------
$client = new myclass;
$sql = "SELECT * FROM books";
$q = $client->Query($sql);
print_r($q);
You just need to change those lines:
$out = new stdClass;
while ($r = $results->fetch_object()){
$out = $r;
}
to those ones:
$out = []; // array that will hold all the objects
while ($r = $results->fetch_object()){
array_push($out, $r); // add to the array the current object
}
return $out; //return the array with the objects
You are overwriting $out at every iteration of the while, so you'll have only the last result in the return. You could use an array and append the results (it could be an array of stdClass objects), and then you'll be able to work with it with a simple loop
class myclass {
function Query($sql){
$results = $this->db->query($sql);
if (mysqli_num_rows($results)<1){
throw new Exception('NoResults');
}
//copied this piece of code from #Berto99 answer from this same question
$out = []; // array that will hold all the objects
while ($r = $results->fetch_object()){
array_push($out, $r); // add to the array the current object
}
return $out; //return the array with the objects
}
}
---------------
$client = new myclass;
$sql = "SELECT * FROM books";
$q = $client->Query($sql);
foreach($q as $resultLine){
//do whatever you need to do here
}
Your $r is object. You dont need stdClass. You need to add your objects to $out array.
function Query($sql)
{
$results = $this->db->query($sql);
if (mysqli_num_rows($results) < 1) {
throw new Exception('NoResults');
}
$out = new stdClass;
$i=0;
while ($r = $results->fetch_object()){
$out->{$i} = $r;
$i++
}
return $out;
}
I'm having troubles with my function and how to retrieve the data. Here is what i got.
public function getImages()
{
$array = array();
//Test query
$query = $this->connect()->query("SELECT * from user");
while ($row = $query->fetch()) {
$array[] = $row;
return $array;
}
}
Now I'm calling this function but i can not use foreach to access the array.
include "header.html";
include "autoload.php";
spl_autoload_register('my_autoloader');
$users = new User;
$users->getImages();
foreach ($users as $value) {
echo $value["username"];
}
What am I doing wrong? I'm only getting one result but there are many in my database. Or if i call the $array in foreach it says undefined.
A couple things. First, your function is only ever returning an array with one element in it. If you want to finish populating the array, don't return until after the loop:
while ($row = $query->fetch()) {
$array[] = $row;
}
return $array;
And second, you're trying to iterate over the object which has the function, not the value returned from the function. Get the return value and iterate over that:
$userDAO = new User;
$users = $userDAO->getImages();
foreach ($users as $value) {
echo $value["username"];
}
You just need to put the return statement out of the while loop.
public function getImages() {
$array = array(); //Test query
$query = $this->connect()->query("SELECT * from user");
while ($row = $query->fetch()) {
$array[] = $row;
}
return $array;
}
I have a problem where some variables are probably (I can't know for sure) not inserted into the final statement. Here is my example:
Works:
public static function findByPageAndFieldContains($recordsPerPage, $page, $field, $searchterm) {
$query = CouchbaseN1qlQuery::fromString('SELECT * FROM `public_portal` WHERE `collection`=$collection AND TOSTRING('.$field.') LIKE "%'.$searchterm.'%" ORDER BY `_id` limit $limit offset $offset');
$query->options['$collection'] = static::COLLECTION_NAME;
//$query->options['$field'] = $field;
$query->options['$limit'] = $recordsPerPage;
$query->options['$offset'] = $recordsPerPage*($page-1);
//$query->options['$searchterm'] = $searchterm;
$result = DB::getDB()->query($query);
var_dump($query);
var_dump($result);
$objects = array();
foreach($result as $row) {
$object = new static($row->{"public_portal"});
$object->setId($row->{"public_portal"}->{"_id"});
$objects[] = $object;
}
//var_dump($objects);
return $objects;
return $result;
}
Debug Output:
debug01
Does not work:
public static function findByPageAndFieldContains($recordsPerPage, $page, $field, $searchterm) {
$query = CouchbaseN1qlQuery::fromString('SELECT * FROM `public_portal` WHERE `collection`=$collection AND TOSTRING($field) LIKE "%$searchterm%" ORDER BY `_id` limit $limit offset $offset');
$query->options['$collection'] = static::COLLECTION_NAME;
$query->options['$field'] = $field;
$query->options['$limit'] = $recordsPerPage;
$query->options['$offset'] = $recordsPerPage*($page-1);
$query->options['$searchterm'] = $searchterm;
$result = DB::getDB()->query($query);
var_dump($query);
var_dump($result);
$objects = array();
foreach($result as $row) {
$object = new static($row->{"public_portal"});
$object->setId($row->{"public_portal"}->{"_id"});
$objects[] = $object;
}
//var_dump($objects);
return $objects;
return $result;
}
Debug output:
debug02
Basically the second example returns no result, while the first one works just fine.
Any idea why?
You are not using N1QL parameters correctly. You must decide if you are evaluating your parameters in PHP or in N1QL.
The field name cannot be a N1QL parameter, so you evaluate it in PHP:
TOSTRING('.$field.') LIKE ...
The search term should be a N1QL parameter, so you add wildcards in PHP and then pass it to N1QL as a parameter:
$searchterm = '%'.$searchterm.'%'
TOSTRING('.$field.') LIKE $searchterm ...
I want to have all results from my database in one array
my function:
function GetWinkelProduct($g_Winkel) {
global $g_Conn;
$l_Stmt = $g_Conn->prepare("SELECT pd_id FROM `producten_:Winkel`");
$l_Stmt->bindValue(':Winkel', $g_Winkel, PDO::PARAM_INT);
$l_Stmt->execute();
$l_qurries = new dbquery();
$l_LastProduct = $l_qurries->GetLastProduct($g_Winkel);
while($l_Row = $l_Stmt->fetch(PDO::FETCH_ASSOC)){
$out = array();
foreach($l_Row as $product){
$out[] = $product['pd_id'];
}
}
return $out;
}
other page: <?php print_r($l_qurries->GetWinkelProduct($g_Winkel)); ?>
only I get the first result in the array and when I do $product['pd_id'] I get only the last result.
Try this...
Change fetch to fetchAll in while loop and renove foreach inside while loop
function GetWinkelProduct($g_Winkel) {
global $g_Conn;
$l_Stmt = $g_Conn->prepare("SELECT pd_id FROM `producten_:Winkel`");
$l_Stmt->bindValue(':Winkel', $g_Winkel, PDO::PARAM_INT);
$l_Stmt->execute();
$l_qurries = new dbquery();
$l_LastProduct = $l_qurries->GetLastProduct($g_Winkel);
while($l_Row = $l_Stmt->fetchAll(PDO::FETCH_ASSOC)){
$out = array();
$out[] = $l_Row ['pd_id'];
}
return $out;
}
ref:http://php.net/manual/en/pdostatement.fetchall.php
You must initialize the array outside the while loop and you don't need the foreach.
that way you are creating a new array every time the while iterates, that way you end up replacing the array.
$out = array();
while($l_Row = $l_Stmt->fetchAll(PDO::FETCH_ASSOC)){
$out[] = $l_Row['pd_id'];
}
return $out;
$stmt = $db->prepare("SELECT * FROM friend JOIN user ON friend.uId=user.uId WHERE friend.friendId= ?");
$stmt->bind_param('s',$userId);
if($stmt->execute()){
$user = $stmt->get_result();
while ($obj = $user->fetch_object()) {
$friends[] = $obj;
}
echo json_encode($friends);
}
my above code produced an array
[{"uId":"2","firstName":"Gem","lastName":"Tang"},{"uId":"3","firstName":"James","lastName":"Lebron"}]
but I wish it could be 2 object instead.
You have an array of objects with length 2. Using JavaScript you can traverse it like this.
var o = [{"uId":"2","firstName":"Gem","lastName":"Tang"},{"uId":"3","firstName":"James","lastName":"Lebron"}];
for(var i = 0; i < o.length; i++) {
var row = o[i];
console.log(row.firstName);
}
in the while loop:
You could either use foreach:
$object = new stdClass();
foreach ($obj as $key => $value)
{
$object->$key = $value;
}
$friends[$obj['uId']] = $object;
or by the json functions:
$friends[$obj['uId']] = json_decode(json_encode($obj), FALSE);