mysql result retrieving a column name and value - php

I am trying to make a function which converts a mysql query result in to an array
In the function below i'm assuming to have fields isbn, title and rank but this will not always be the case.
Is there a way to retrieve a fields name along with the value without actually knowing any of this information prior? so that this function can be used with any mysql query result.
function
function mysqlToArray($result){
$arr = array();
$numRows = mysql_num_rows($result);//count
if($numRows>0){
for($i=0; $i<$numRows; $i++){
$arr[] = array(
"isbn" => mysql_result($result, $i, "isbn"),
"title" => mysql_result($result, $i, "title"),
"rank" => mysql_result($result, $i, "rank"),
);
}
}
return $arr;
}
example in use
function getProfitableBooks(){
$q = "SELECT isbn, title, rank FROM ".TBL_BOOKS;
$result = mysql_query($q, $this->connection);
if(!$result || (mysql_numrows($result) < 1)){
return null;
}
return $this->mysqlToArray($result);
}

Try looking at this mysql_fetch_array

There is a great PHP function for this mysql_fetch_array
You can view examples mysql_fetch_array in the PHP manual.

Try something like this to get the names of the cols.
my $table = 'name';
my $sth = $dbh->prepare("SELECT * FROM $table WHERE 1=0;");
$sth->execute;
my #cols = #{$sth->{NAME}}; # or NAME_lc if needed
$sth->finish;
foreach ( #cols ) {
printf( "Note: col : %s\n", $_ );
}

Did you check the PHP manual?
mysql_fetch_assoc will be helpful here:
function mysqlToArray($result)
{
$arr = array();
while($arr[] = mysql_fetch_assoc($result));
return $arr;
}

Related

How to use recursive function to produce a 1-D array in PHP that contains a hierarchical comment reply system?

I have 2 tables. Table 'comments' contains all the comments with cid ,comment as fields. and another table 'reply' which consists of cid and rpid which stores which comment is the reply of which comment.
function array_gen($c, $array, $total, $conn, $f) {
$array[] = $c;
$sql = "SELECT rpid FROM reply WHERE cmid = '$c';";
$st = $conn->query($sql);
$st->setFetchMode(PDO::FETCH_ASSOC);
$rpid = $st->fetchAll();
$count = $st -> rowCount();
if ($count > 0) {
foreach ($rpid as $r) {
$array = array_gen($r['rpid'], $array, $total, $conn, $f);
}
}
else {
echo $c;
return $array;
}
while ($f <= $total) {
if (! in_array($f, $array)) {
$array = array_gen($f, $array, $total, $conn, $f);
}
$f++;
}
return $array;
}
I tried out a function with parameters total number of comments ($total), first comment ($c), empty array ($array), a flag variable $f initialised to value of $c and a PDO connection variable $conn.
It works perfectly upto 2 level of comment-reply. But when it comes to 3rd level i.e, a reply is given to another reply, it starts misbehaving. Function return is not working properly inside foreach loop.

PHP Array not being delivered

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

PHP Reference for MySQL query

My function:
function sql_query($s, $x) {
$query = mysql_query($s);
global $mysql;
while($mysql = mysql_fetch_array($query)) {
return;
}
}
Now it's work only with $mysql variable:
echo $mysql['username'];
How to make it works only with:
sql_query("select * from users where id = '1' limit 1", "varname");
$varname['username'];
I want to set a SQL Query and Variable name in function, like:
sql_query("sqlquery", "variable");
echo $variable['id'];
Thanks for reply!
function sql_query($s, &$x) {
global $mysql;
$query = mysql_query($s);
$result = mysql_fetch_array($query);
foreach($result as $key => $value) {
$x[$key] = $value;
}
}
This should assign each variable that is returned by the query to a key in array $x (assuming it is an array). Notice that I am passing $x by reference instead of by value, eliminating the need to return anything.

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