Can't display array element - php

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()

Related

How do I build this array to output?

I have the following function which fetches some data from a MySQL table:
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
foreach ($query as $row) {
var_dump($row);
};
echo $data
}
How can I push all the returned data into an array, where each member is indexed by a number?
Do I need to use echo or return at the end? They seem to have the same effect.
EDIT: Is this the correct way of returning results of the query? I am passing it to the front-end.
$questionData = $controller->readQuestion($quizType, $questionId);
return $questionData;
In general your function must looks like:
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
return $query;
}
But, you have to look what is inside $query variable. If it is array - just return this array, if not - maybe it is some iterator, hence you have to check it and try to find method like toArray or something like that... Otherwise, you have to do something like:
$data = [];
foreach ($query as $row) {
$data[] = $row;
};
return $data;
Now you can use this function like:
var_dump(readQuestion($quizType, $questionId));
Take a look up here on how to secure your data.
Anyway, as I said in the comment you cannot use echo on an Array. And you can't do anything with the output of var_dump.
Change var_dump($row); for $data[] = $row;
and change echo $data; for return $data;
function readQuestion ($quizType, $questionId) {
$data = array();
$query = $this->dbConnection->query("SELECT * FROM $quizType WHERE id = $questionId");
foreach ($query as $row) {
$data=$row;
};
return $result;
}

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.

Accessing individual part of MySQL query

how can I access a particular part of my mysql_query? I'm attempting to do this with the code below, but to no avail. Any help would be most appreciated!
$rs = mysql_query("SELECT id,type FROM stuff WHERE stuffID = '$stuffID'");
echo $rs['type']; <------ tried here
// Add the rows to the array
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo $arr['type']; <----- also tried here
You cannot access the row until you've fetched it.
while($obj = mysql_fetch_object($rs)) {
// NOTE: $arr[] = $obj, is the same as array_push($arr, $obj),
// I dont think you want that
$arr = $obj; // save the row
echo $obj->type; // you are fetching an object, not an array
}
echo $arr->type; // you can access it here too

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 index the result of a mySql query as an array of array?

If I need to select and use information of every element of a table in a database the procedure would be this:
$query = "...mySql query...";
$query_result = mysql_query($query) or die (mysql_error());
Then if I wished to access the fields of the result I would use the function mysql_fetch_array() and access them like this:
$query_result_array = mysql_fetch_array($query_result);
echo $query_result_array['field_1'];
....
echo $query_result_array['field_i'];
....
But since more elements could be returned by the query I would like to access every single of them with an array indexed from 0 to mysql_num_rows($query_result).
As an example:
echo $query_result_array['field_i'][0];
....
echo $query_result_array['field_i'][mysql_num_rows($query_result)];
should print for every selected element of the table the value of field i.
Is there a function that will do the job for me?
If not, any suggestions on how to do it?
Thanks in advance for help.
This may be an alternative
$res = mysql_query("..SQL...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$arr[] = $row;
}
var_dump($arr);
Or
$res = mysql_query("..SQL...");
for
(
$arr = array();
$row = mysql_fetch_assoc($res);
$arr[] = $row
);
var_dump($arr);
I don't think there is such a method; you have to do it yourself.
try with something like:
$res = mysql_query("..mySql query...");
$arr = array();
while ($row = mysql_fetch_assoc($res)) {
$query_result_array[] = $row;
}
then you access your data like:
echo $query_result_array[0]['field_i'];
based on 2 previous answers, those authors assuming that usual SO author is familiar with such a thing as creating a function
function sqlArr($sql) { return an array consists of
$ret = array();
$res = mysql_query($sql) or trigger_error(mysql_error()." in ".$sql);
if ($res) {
while ($row = mysql_fetch_assoc($res)) {
$ret[] = $row;
}
}
return $ret;
}
$array = sqlArr("SELECT * FROM table");
foreach ($array as $row) {
echo $row['name'],$row['sex'];
}
this resulting array have different structure from what you asked, but it is way more convenient too.
if you still need yours unusual one, you have to tell how you gonna use it

Categories