Class Function does not return array properly - php

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.

Related

How to get data in array format in from php mysql database

I have the following function in PHP, I am trying to get array in a specific format mentioned below but to no success, I am selecting a specific column in the mysql table than contains a json value like
{
"lat": "-0.008668899503063161",
"lng": "0.0025903204871857714"
}
This is the function
function test()
{
$pdo = new PDO ("mysql:host=localhost;dbname=dbname","user", "secret");
$statement=$pdo->prepare("SELECT test FROM merchants WHERE user_id = 1");
$statement->execute();
$data = array();
while( $row = $statement->fetch(PDO::FETCH_ASSOC) )
{
$data[] = json_decode( $row['test'] );
}
return $data ;
}
I am expecting the following result
['lat' => -0.008668899503063161,'lng' => 0.0025903204871857714,]
But this is what I keep getting
[{"lat":"-0.008668899503063161","lng":"0.0025903204871857714"}]
Don't push onto an array if you just want a single value.
function test()
{
$pdo = new PDO ("mysql:host=localhost;dbname=dbname","user", "secret");
$statement=$pdo->prepare("SELECT test FROM merchants WHERE user_id = 1");
$statement->execute();
row = $statement->fetch(PDO::FETCH_ASSOC) )
if ($row) {
$data = json_decode( $row['test'], true );
} else {
$data = null;
}
return $data ;
}
I managed to do it like this
'merchants.location' =>
[
'lat' => $data['lat'],
'lng' => $data['lng']
]

Multidimensional array as JSON response

Aim is to return array from .php in JSON format. That array to contain another array of data (49 DB rows, each having 4 columns), which is taken form mySQL DB:
.php is below:
$json = array( //this is AJAX response
"status" => null,
"username" => null,
"population" => null,
"food" => null,
"water" => null,
"map" => null //this to be an array of tiles
);
$sql = "SELECT * FROM players_map_test WHERE player_id = :value";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':value', $value, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
foreach ($result as $row) {
$json["map"]["tile_health"] = $row["tile_health"];
$json["map"]["tile_id"] = $row["tile_id"];
$json["map"]["tile_level"] = $row["tile_level"];
$json["map"]["tile_type"] = $row["tile_type"];
}
echo json_encode($json);
In my AJAX response handler, I expect to access that sub-array as response.map and handle elements in usual manner: response.map[0].
When I console.log(response) I see that map is present there, but it is not an array and it contains "1" as values to all keys:
map:Object
tile_health:"1"
tile_id:"1"
tile_level:"1"
tile_type:"1"
What am I doing wrong?
Update your foreach loop like as below--
foreach ($result as $row) {
$json["map"][] = $row;
}
Also change the below code
#$result = $stmt->fetch(PDO::FETCH_ASSOC);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
Note: fetch() function return only 1 row. And fetchAll() function return multiple rows.
Syntax is next:
foreach ($result as $row) {
$json["map"][] = [
"tile_health" => $row["tile_health"],
"tile_id" => $row["tile_id"],
"tile_level" => $row["tile_level"],
"tile_type" => $row["tile_type"]
];
}
You were overwriting values.
You can simplify your database part like this:
// request only needed columns
$sql = "SELECT tile_health, tile_id, tile_level, tile_type
FROM players_map_test WHERE player_id = :value";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':value', $value, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
// output was already in the type of array
$json["map"] = $result;
// encode and display
echo json_encode($json);

Return a record from PHP with function and render

I have a function
function getUser($linkedInID) {
$sql = "SELECT * FROM ipadapi.users WHERE linkedInID = '".$linkedInID."'";
$results = mysql_query($sql) or die("Error in User SQL query.");
return $results;
}
and this is called via
$returnedUser = getUser($linkedInID);
// Generate the array for the JSON String
$returnedMessage = array(
'status' => 'ok',
'error' => false,
'avatar' => $returnedUser['avatar'],
'userSelectedTheme' => $returnedUser['userSelectedTheme'],
'checksum' => $checksum
);
// JSONify the string and return it
$returnedJSON = json_encode($returnedMessage);
echo $returnedJSON;
However the results of $returnedUser['(field name']Althought, are always coming up NULL. avatar, userSelectedTheme are some of the fields from the dbase. I have confirmed in the database the infomation is there
I suspect I am missing a key line from my function which involves =array() somewhere and manflu is preventing me seeing it.
Any advice greatly appreicated
First of all stop using mysql_(Why shouldn't I use mysql_* functions in PHP?) is deprecated.
mysql_query from getUser function returns a resource. you must
return an array. so have a look at mysql_fetch_array or mysql_fetch_assoc functions
basically you must return mysql_fetch_array($results) assuming that is only one result comming from db. otherwise you'll have to loop through them.
Thanks to all those who answered, and extra plaudits to those who spotted the use of the depreciated mysql commands.
Had a shot of espresso and got the answer working (albeit unsafe and unsecure and..)
function getUser($linkedInID) {
$sql = "SELECT * FROM ipadapi.users WHERE linkedInID = '".$linkedInID."'";
$results = mysql_query($sql) or die("Error in User SQL query.");
$arr = array();
while($row= mysql_fetch_assoc($results)){
$arr['avatar'] = $row['avatar'];
$arr['userSelectedIndustry'] = $row['userSelectedIndustry'];
}
return $arr;
}
and the call
$returnedUser = array();
$linkedInID = filter_var($_REQUEST['linkedInID'], FILTER_SANITIZE_STRING);
$returnedUser = getUser($linkedInID);
// Generate the array for the JSON String
$returnedMessage = array(
'status' => 'ok',
'error' => false,
'avatar' => $returnedUser['avatar'],
'userLinkedInIndustry' => $userLinkedInIndustry,
'userSelectedTheme' => $returnedUser['userSelectedTheme'],
'userSelectedIndustry' => $returnedUser['userSelectedIndustry'],
'checksum' => $checksum
);
// JSONify the string and return it
$returnedJSON = json_encode($returnedMessage);
echo $returnedJSON;
many thanks for all time spent, and apologies for not just getting my head down and figuring it out
$data=array();
while($row=$result->fetch_array(MYSQLI_ASSOC))
{
data[]=$row;
}
return $row;

update array in multiddimensional array

I have a multidimensional array, and I can not update one of these:
public function get_list($query){
if(mysql_query($query,DB::connect())){
$result = mysql_query($query);
if (mysql_affected_rows() != 0) {
while ($row = mysql_fetch_array($result)) {
$list_annunci[] = array(
"id" => $row["id"],
"title" => $row["title"]
);
if(mysql_query($immagini,DB::connect())){
$result_img = mysql_query($immagini);
if (mysql_affected_rows() != 0) {
while ($row_img = mysql_fetch_array($result_img)) {
$list_annunci[] = array(
"img" => $row_img["path_img"]
);
}
}
}
}
how do I insert the record in the array already declared?
tnx stefania
Use your ids as keys for the original array.
$list_annunci[$id] = array(
Make the database query returns those ids as well.
SELECT id, path_img
Then you can inject or update the right group.
$list_annunci[ $id ]["img"] = $row_img["path_img"];
^
|
from $row_img["id"]

PHP get array object from a class

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.

Categories