I have been trying to store the results of a MySQL query in a PHP array, however I have been struggling to access the values after they have been stored.
I used this to store the query:
while($row = mysqli_fetch_assoc($result)) {
array_push($array, $row);
}
Which when showing the array with var_dump gives an output similar to this, just with more values:
array(147) { [0]=> array(1) { ["TABLE_NAME"]=> string(8) "_3085515" } }
I want to be able to access the value with the _NUMBER, but I can't figure out how to do this?
1st : Declare the variable as a array
$array = array();
while($row = mysqli_fetch_assoc($result)) {
array_push($array, $row);
}
2nd : Access the value like this
$array[0]['TABLE_NAME']
Do like that.
$array = [];
while($row = mysqli_fetch_assoc($result)) {
array_push($array, $row);
}
Related
hopefully a easy one for you,
my sql query is returning a mulit-dimensional array, I need to access only one key the is nested on the second level but cant figure out how.
here is my function.
public function get_visitor_id($id)
{
$this->db->where('mobile',$id);
$this->db->or_where('email',$id);
$this->db->select('uid');
$result = $this->db->get('visitors');
if ($result)
{
foreach ($result->result() as $key=>$value){
$array[$key] = $value;
}
var_dump($array);
return $array;
}
}
The array returned is
{ [0]=> object(stdClass)#20 (1) { ["uid"]=> string(2) "24" } }
I only need the value of ['uid'] so in essence if I was to echo get_visitor_id() it would evaluate to "24".
Thanks for you help.
Cheers
try changing foreach() func to:
foreach($result as $res){
$res = $res->fetch_assoc();
$array['uid'] = $res['uid'];}
EDIT: in case of this didn't work then try while loop:
while($res = $result->fetch_assoc()){
$array['uid'] = $res['uid'];
}
The below code has only array like ["a","b","c"] but returns [Object,Object,Object]. The result of which I need to use nested $each loop in ajax success function. Is there any better way to do it?
if($_GET['semValue'])
{
$sem_value = $_GET['semValue'];
try
{
$stmt = $dbConn->prepare("SELECT Semester FROM CourseInfo");
$semArray = array();
if ($stmt->execute())
{
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$semArray[] = $row;
}
}
echo json_encode($semArray);
exit();
}
catch(PDOException $e)
{
echo 'Exception -> ';
var_dump($e->getMessage());
}
You're inserting entire row in main array so it will return multidimensional array instead of array of string.
To get the array of string replace the following lines.
while ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
$semArray[] = $row["Semester"];
}
Explanation:
$row would be like this,
$row= Array("semester"=>1);
$row= Array("semester"=>2);
// And so on
If you follow your current code then your final array would be like this,
$semArray = Array ( [0]=> Array("semester"=>1), [1]=> Array("semester"=>2));
So it becomes multidimensional array, that's why we use $row["Semester"] to make it single dimensional array of string/integer values.
Is there any reason why this code would avoid the first value in an array?
$rappels = array();
$i = 0;
while($row = $result->fetch_assoc()) {
foreach($row as $key=>$val) {
$rappels[$i][$key] = $val;
}
$i++;
}
return $rappels;
When I return the rappels, it always seems to avoid returning the very first item, which should be [0] in the array.
You have a number of redundancies in your code. You don't need $i nor do you need the foreach loop.
$rappels = array();
while($row = $result->fetch_assoc()) {
$rappels[] = $row;
}
return $rappels;
Your code as you posted it shouldn't remove any rows. You may need to look at the code you haven't posted to see if there's something there that's skipping the first row.
I want to echo the values of all arrays that has been returned from a search function. Each array contains one $category, that have been gathered from my DB. The code that I've written so far to echo these as their original value (e.g. in the same form they lay in my DB.) is:
$rows = search($rows);
if (count($rows) > 0) {
foreach($rows as $row => $texts) {
foreach ($texts as $idea) {
echo $idea;
}
}
}
However, the only thing this code echoes is a long string of all the info that exists in my DB.
The function, which result I'm calling looks like this:
function search($query) {
$query = mysql_real_escape_string(preg_replace("[^A-Za-zÅÄÖåäö0-9 -_.]", "", $query));
$sql = "SELECT * FROM `text` WHERE categories LIKE '%$query%'";
$result = mysql_query($sql);
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows['text'] = $row;
}
mysql_free_result($result);
return $rows;
}
How can I make it echo the actual text that should be the value of the array?
This line: echo $rows['categories'] = $row; in your search function is problematic. For every pass in your while loop, you are storing all rows with the same key. The effect is only successfully storing the last row from your returned query.
You should change this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
echo $rows['categories'] = $row;
}
mysql_free_result($result);
return $rows;
to this...
$rows = array();
while ($row = mysql_fetch_assoc($result)) {
$rows[] = $row;
}
return $rows;
Then when you are accessing the returned value, you could handle it like the following...
foreach ($rows as $key => $array) {
echo $array['columnName'];
// or
foreach ($array as $column => $value) {
echo $column; // column name
echo $value; // stored value
}
}
The problem is that you have a multi-dimensional array, that is each element of your array is another array.
Instead of
echo $row['categories'];
try print_r:
print_r($row['categories']);
This will technically do what you ask, but more importantly, it will help you understand the structure of your sub-arrays, so you can print the specific indices you want instead of dumping the entire array to the screen.
What does a var_dump($rows) look like? Sounds like it's a multidimensional array. You may need to have two (or more) loops:
foreach($rows as $row => $categories) {
foreach($categories as $category) {
echo $category;
}
}
I think this should work:
foreach ($rows as $row => $categories) {
echo $categories;
}
If this will output a sequence of Array's again, try to see what in it:
foreach ($rows as $row => $categories) {
print_r($categories);
}
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