I have a page which creates an instance of a class. This class gets some information on the user (their badges) but when I return the object I only get the first record. Some code below.
$badges = new Badges;
$result = $badges->getBadges($userID);
$row_array[] = $result;
echo json_encode($row_array);
class Badges
{
function getBadges($userID)
{
$get_badge_query = mysqli_query($GLOBALS['connect'], "SELECT * FROM tbl_my_badges WHERE user_id = '" . $userID . "'");
while($get_badge_result = mysqli_fetch_assoc($get_badge_query)) {
$result = array("done" => "true",
"badge_icon" => $get_badge_result['badge_icon'],
"badge_text" => $get_badge_result['badge_message']);
}
return $result;
}
}
I have tried adding an array variable outside the loop and populating this with the results and returning the variable but still doesn't work.
Any help would be great.
You need to accumulate the results into an array, then return that:
$results = array();
while($get_badge_result = mysqli_fetch_assoc($get_badge_query)) {
$results[] = array("done" => "true",
"badge_icon" => $get_badge_result['badge_icon'],
"badge_text" => $get_badge_result['badge_message']);
}
return $results;
Otherwise you're just overwriting the $result variable on each iteration, and it will always be set to the last record in the DB.
Related
I'm trying to GET a JSON format back when I POST a specific ID to my database. As I get more than one result I have multiple rows, which I want to get back. I do get different arrays back, but it is not a valid JSON Format. Instead of
[{...},{...},{...}]
it comes back as
{...}{...}{...}
Therefore the [...] are missing and the arrays are not separated by commas.
My code is down below. The function "getUserBookingsKl" is defined in a different php.
//get user bookings
public function getUserBookingsKl($id) {
//sql command
$sql = "SELECT * FROM `***` WHERE `hf_id`=$id AND `alloc_to`>DATE(NOW()) AND NOT `confirmation`=0000-00-00 ORDER BY `alloc_from`";
//assign result we got from $sql to $result var
$result = $this->conn->query($sql);
// at least one result
if ($result !=null && (mysqli_num_rows($result) >= 1 ))
{
while ($row = $result->fetch_array())
{
$returArray[] = $row;
}
}
return $returArray;
}
...
...
foreach($userdb as $dataset)
{
$returnArray["group"] = $dataset["kf_id"];
$returnArray["from"] = $dataset["alloc_from"];
$returnArray["to"] = $dataset["alloc_to"];
echo json_encode($returnArray);
# return;
}
// Close connection after registration
$access->disconnect();
It looks like you're sequentially emitting the values, not pushing into an array. You need to make an array, push into it, then call json_encode on the resulting structure:
$final = [ ];
foreach ($userdb as $dataset)
{
$returnArray = [ ];
$returnArray["group"] = $dataset["kf_id"];
$returnArray["from"] = $dataset["alloc_from"];
$returnArray["to"] = $dataset["alloc_to"];
$final[] = $returnArray;
}
echo json_encode($final);
Note that it's important here to not use the same variable inside the loop each time through or you're just pushing the same array in multiple times.
As I try to consolidate my code and make it more available to other projects, I've run into a problem:
variables that were generated and available are not anymore when that routine is moved to a function:
This is the query:
$count = "SELECT eid, Count, Name, name2, Email, pay FROM h2018";
THIS WORKS FINE:
$result = $mysqli->query($count);
$row = $result->fetch_assoc();
foreach($row as $key=>$value){
$a = $key;
$$key = $value;
echo($a." and ".$value."<BR>");
}
NOT WORKING FINE:
function avar($result) {
$row = $result->fetch_assoc();
foreach($row as $key=>$value){
$a = $key;
$$key = $value;
}
}
$result = $mysqli->query($count);
avar($result);
echo($a." and ".$value."<BR>");
I thought the variable variables would be available from outside of the function. I tried doing a return, but that didn't help. I also tried to global $$key, but that didn't work either.
What am I doing wrong?
There is multiple mistakes or missing steps like return or array
function avar($result) {
$data=array();
$row = $result->fetch_assoc();
foreach($row as $key=>$value){
$a = $key;
$data[$key] = $value;//if there is multiple records then used array otherwise you should used variable
}
return $data;
}
$result = $mysqli->query($count);
$data=avar($result);//get return value
print_r($data);
Please, read the PHP documentation about the Variable Scope for more information. The variables inside your function are local so you cannot access them outside of your function. You would have to return something.
For example, this could work:
function avar($result) {
$resultArray = false;
$row = $result->fetch_assoc();
foreach ($row as $key => $value) {
$resultArray = [
'key' => $key,
'value' => $value
];
}
return $resultArray;
}
$result = $mysqli->query($count);
$queryResult = avar($result);
if ($queryResult) {
echo 'Key: ' . $queryResult['key'] . ' | Value: ' . $queryResult['value'];
}
Please do note that fetch_assoc will return an array with multiple items if there is more than one result. In my example only one (and the last) result will be returned.
Edit: As #Nigel Ren said in his comment. In this case you're basically rebuilding an array which is going to look (nearly) the same as the array which is being returned by fetch_assoc, which is pointless. My function can be used if you want to add conditions in the future, or manipulate some data. Otherwise, don't use a function and just use the results from fetch_assoc.
I can't display an array element. If I use print_r($array); it shows me something like this:
stdClass Object ([tableName1] => myValue1 [tableName2] => MyValue2 [tableName3] => myValue3 [tableName4] => myValue4)
But if I try to print the first element with echo $array[0] my site doesn't load (I get no error in IDE).
Here is the code of my function:
public function queryInfo($query) {
$database = $this->connect();
$result = $database->queryInfo($query);
while ($row = $result->fetch_object()) {
$results[] = $row;
}
return $results; // this is the array i mean!
}
Thanks for your help.
Edit:
Solution: echo $array[0]->myTableName;
You are trying to echo an object.
try to print_r($array[0]), if it's an object, you can access it's properties by using: $arrray[0]->propertyName
public function queryInfo($query) {
$database = $this->connect();
$result = $database->queryInfo($query);
$results = []
while ($row = $result->fetch_object()) {
$results.push($row);
}
return $results; // this is the array i mean!
}
You are fetching the result as an object.
$row = $result->fetch_object()
You can access object as $array[0]->tableName1 to get the value of column name tableName1 of first array.
Instead of fetch_object use fetch_all(MYSQLI_ASSOC) or fetch_array()
I can't seem to get the array to return from the function correctly, every time I run the script it just echoes out 0, even though I have checked that the MySQL query returned at least 1 row. I've also tried using $_GLOBALS["FORUM_ANSWERS"][] = ..., however it still did not work.
public function getAnswers() {
$dbh = $this->dbh;
$id = $this->question_id;
$q = $dbh->prepare("SELECT * FROM answers WHERE question_id = :id");
$q->bindParam(":id", $id);
$q->execute();
$nr = $q->rowCount();
if ($nr == 0) {
echo "No Questions";
}
$_GLOBALS["FORUM_ANSWERS"] = [];
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
array_push($_GLOBALS["FORUM_ANSWERS"], array(
"num_id" => $row["num_id"],
"question_id" => $row["question_id"],
"answer" => $row["answer"],
"name" => $row["name"],
"username" => $row["username"],
"ip" => $row["ip"],
"date" => $row["date"],
));
}
return $GLOBALS["FORUM_ANSWERS"];
}
SEPERATE FILE:
$answers = $forum->getAnswers();
echo count($answers);
You are assigning to $_GLOBALS and returning $GLOBAL.
You actually don't need to use a global array by the look of it - I would just assign the array to a variable (that you initialise in the function) and return that.
I have some data in a database column called "gcmregid".
I access this data by calling:
public function getAllUsers() {
$r = mysql_query("select * FROM table");
while ($row = mysql_fetch_array($r)) {
$result = array(
'gcmregid' => $row["gcmregid"]
);
}
return $result;
}
Correct me if I'm wrong, but this should deliver an array, due to result = array?
I took this logic from here: Getting Resource id #3 Error in MySql
.Then I thaught using a loop would be helpful, such as:
$userCount = $db->getUserCount(); // counting said table
$registation_ids = array(); // again create array
for($i=0; $i < $userCount; $i++)
{
$gcmRegId = $db->getGCMRegID($selUsers[$i]);
$row = mysql_fetch_assoc($gcmRegId);
//Add RegIds retrieved from DB to $registration_ids
array_push($registation_ids, $row['gcmregid']); // this creates an array consisting of gcmregid s ?
}
It doesn't work either.
Any input would be really appreciated right now...
Thanks
I'm not sure what's going wrong, but if the problem is that it's returning a single item: that's because you keep making a new array with every iteration, discarding the old one. If you want to collect all the rows, make a new array outside of the loop and then add the results to it:
public function getAllUsers() {
$r = mysql_query("select * FROM table");
$result = array();
while ($row = mysql_fetch_array($r)) {
$result[] = array (
'gcmregid' => $row["gcmregid"]
);
}
return $result;
}
You should consider working more on how you name your functions. If you are trying to get gcmregid, the method should not say getAllUsers. Anyway, did you try the following:
public function get_gcmregid() {
$query_result = mysql_query("select * FROM table");
$row = mysql_fetch_array($query_result);
return $result[0]['gcmregid'];
}
OR if you are trying to get all gcmregid in one shot:
public function get_gcmregid() {
$query_result = mysql_query("select * FROM table");
$i=0;
while ($row = mysql_fetch_array($query_result)){
$result[$i++] = $row['gcmregid'];
}
return $result;
}