PHP Array not being delivered - php

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;
}

Related

PHP invalid JSON encoding

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.

Translating a database to JSON

I have a method of creating JSON into an array that looks like this:
[{"date":"","name":"","image":"","genre":"","info":"","videocode":""},{...},{...}]
I first tried getting the data from a html page (not the database) like this:
$arr = array();
$info = linkExtractor($html);
$dates = linkExtractor2($html);
$names = linkExtractor3($html);
$images = linkExtractor4($html);
$genres = linkExtractor5($html);
$videocode = linkExtractor6($html);
for ($i=0; $i<count($images); $i++) {
$arr[] = array("date" => $dates[$i], "name" => $names[$i], "image" => $images[$i], "genre" => $genres[$i], "info" => $info[$i], "videocode" => $videocode[$i]);
}
echo json_encode($arr);
Where each linkExtractor looks a bit like this - where it grabs all the text within a class videocode.
function linkExtractor6($html){
$doc = new DOMDocument();
$last = libxml_use_internal_errors(TRUE);
$doc->loadHTML($html);
libxml_use_internal_errors($last);
$xp = new DOMXPath($doc);
$result = array();
foreach ($xp->query("//*[contains(concat(' ', normalize-space(#class), ' '), ' videocode ')]") as $node)
$result[] = trim($node->textContent); // Just push the result here, don't assign it to a key (as that's why you're overwriting)
// Now return the array, rather than extracting keys from it
return $result;
}
I now want to do this instead with a database.
So I have tried to replace each linkExtractor with this - and obviously the connection:
function linkExtractor6($html){
$genre = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
foreach ($genre as $node)
$result[] = $node;
return $result;
}
But I am getting the error:
Invalid argument supplied for foreach()
Avoid redundancy and run a single SELECT
function create_json_db($con){
$result = mysqli_query($con,"SELECT date, name, image, genre, info, videocode
FROM entries
ORDER BY date DESC");
$items= array();
while ($row = mysqli_fetch_assoc($result)) {
$items[] = $row;
}
return $items ;
}
Try to use this. More info in the official PHP documentation:
function linkExtractor6($html){
$result = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
$items = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$items[] = $row;
}
return $items;
}
First, you are not iterating through your results via something like mysqli_fetch_array. So here is the function with mysqli_fetch_array in place. But there is a much larger issue. Read on.
function linkExtractor6($html){
$result = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
$ret = array();
while ($row = mysqli_fetch_array($result)) {
$items[] = $row;
}
return $ret ;
}
Okay, with that done, it still won’t work. Why? Look at your function. Specifically this line:
$result = mysqli_query($con,"SELECT genre
But where is $con coming from? Without a database connection mysqli_query will not work at all. So if you somehow have $con set outside your function, you need to pass it into your function like this:
function linkExtractor6($con, $html){
So your full function would be:
function linkExtractor6($con, $html){
$result = mysqli_query($con,"SELECT genre
FROM entries
ORDER BY date DESC");
$ret = array();
while ($row = mysqli_fetch_array($result)) {
$items[] = $row;
}
return $ret ;
}
Remember, functions are self-contained & isolated from whatever happens outside of them unless you explicitly pass data into them.

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);
}

Undefined index ONLY when using array

I want to have a SelectAll function which takes in a few arguments (class, table, sort field, and sort order.) The comments explain what is going on (or what is supposed to.)
public static function SelectAll($class, $table, $sort_field, $sort_order = "ASC")
{
/* First, the function performs a MySQL query using the provided arguments. */
$query = "SELECT * FROM " .$table. " ORDER BY " .$sort_field. " " .$sort_order;
$result = mysql_query($query);
/* Next, the function dynamically gathers the appropriate number and names of properties. */
$num_fields = mysql_num_fields($result);
for($i=0; $i < ($num_fields); $i++)
{
$fetch = mysql_fetch_field($result, $i);
$properties[$i] = "'".$fetch->name."'";
}
/*echo [$properties[0]; echo "<br />";}*/
/* Finally, the function produces and returns an array of constructed objects. */
while($row = mysql_fetch_assoc($result))
{
for($i=0; $i < ($num_fields); $i++)
{
$args[$i] = $row[$properties[$i]];
}
$array[] = call_user_func_array(new $class, $args);
} return $array; }
Now, the problem I am having is that $row[$properties[$i]] results in 'undefined index.'
Right after the function gathers the number/names of the fields and stores them in an array, I can echo the value of $properties[0] and it shows as it should, 'id', but $row[~anything here~] will simply not work unless I manually enter the value, such as $row['id']. As you can imagine very frustrating and confusing.
Why won't this work? Are there any solutions, or alternate ways of accomplishing this function?
As I see your $properties[$i] array items have quoted values like "'id'",
so $row[$properties[$i]] <==> $row["'id'"] != $row["id"];
And you might want to check $result === false after $result = mysql_query($query);
Anyway, I think you could replace your function to this (unless you constructed it for demonstration only):
public static function SelectAll($class, $method_name, $table, $sort_field, $sort_order = "ASC"){
/* First, the function performs a MySQL query using the provided arguments. */
$query = "SELECT * FROM " .$table. " ORDER BY " .$sort_field. " " .$sort_order;
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
$array[] = call_user_func_array(array($class,'__construct'), $row);
return $array;
}

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