Here's my current code:
function get_coins() {
global $conn;
$new_sql = "SELECT * FROM marketcaps ORDER BY cap DESC LIMIT 25";
$new_result = $conn->query($new_sql);
while ($row = $new_result->fetch_assoc()) {
$id = $row["id"];
$coin = $row["coin"];
$cap = $row["cap"];
echo $coin . '~USD,';
}
}
$coins = get_coins();
Here's what I can't figure out:
The line $coins = get_coins(); is echoing all of the data from my function and I don't understand why. I know that my function has this line: echo $coin . '~USD,';
But why is it echoing when I add $coins = get_coins();?
Shouldn't I have to add this instead?
$coins = get_coins();
$echo coins;
Basically I don't want to echo anything, I just want to assign the output to a variable. Is there a simple way to do that?
You need to add a return statement to your function, and as you are dealing with multiple rows, collate them into an array (index by ID).
http://php.net/manual/en/function.return.php
function get_coins()
{
global $conn;
$coins = array();
$new_sql = "SELECT * FROM marketcaps ORDER BY cap DESC LIMIT 25";
if( $new_result = $conn->query($new_sql) )
{
while( $row = $new_result->fetch_assoc() )
{
$coins[ $row["id"] ] = $row["coin"] . '~USD,';
}
}
return ( !empty( $coins ) ) ? $coins : null;
}
Here are the principles that I have baked in with my solution which returns the full resultset array:
Don't use global, pass $conn as a parameter to the function.
Don't declare single use variables, unless it dramatically improves readability or assists in the debugging process.
Only query for the specific columns and rows that you intend to process.
Suggested Code:
function get_coins($conn): array {
return $sql
->query("SELECT id,coin,cap
FROM marketcaps
ORDER BY cap DESC
LIMIT 25")
->fetch_all(MYSQLI_ASSOC);
}
foreach (get_coins($conn) as $row) {
// ... reference $row['id'] , $row['coin'] , $row['cap'] during your processes
}
Related
I tried doing this first:
$e = 0;
$objectsid = mysql_query("SELECT * FROM xw_char_items WHERE CharId = '$charid' AND ItemCat = 'object' ORDER BY SortOrder ASC");
while($obj = mysql_fetch_array($objectsid)) {
$e++;
if($e==9) break;
$objectsinfo = mysql_query("SELECT * FROM xw_objects WHERE ItemId = '{$obj["ItemId"]}'");
$object = mysql_fetch_array($objectsinfo);
echo "&charid$e={$char["Id"]}";
if($objectsid == end($obj)) {
echo "&intActiveObject=1";
echo "&intObjectsNum=$e";
}
}
Here it never detects the last one. I also tried this:
$e = 0;
$len = count($objectsid));
while($obj = mysql_fetch_array($objectsid)) {
$e++;
if($e==9) break;
$objectsinfo = mysql_query("SELECT * FROM xw_objects WHERE ItemId = '{$obj["ItemId"]}'");
$object = mysql_fetch_array($objectsinfo);
mysql_free_result($objectsinfo);
echo "&charid$e={$char["Id"]}";
if ($e == $len - 1) {
echo "&intActiveObject=1";
echo "&intObjectsNum=$e";
}
}
Here it detects every iteration as the last one.
Does anyone how to make it detect the last iteration?
The $objectsid variable is storing the mysql_result object not the array of your fetched rows. So even if you apply count($objectsid), you will not get the length of your fetched array.
So the right method is to use mysql_num_rows().
So Simply do this $len=mysql_num_rows($objectsid); and the rest will workout as you are expecting. :)
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.
i have a problem with php in arrays.
i have a db table like that , it shows applications to job.
What i want is to order job titles with their files for example
title must be shown :
WEB Tasarım Uzmanı
noktamedya.com/CVs/zsdfsdfsdfsdfsdf.docx
noktamedya.com/CVs/zsdfsdfsdfsdfsdf.docx
İçerik Yöneticisi
noktamedya.com/CVs/abc.docx
noktamedya.com/CVs/abc.docx
i have a class which takes to important record from db
public function getAllRec()
{
$query = "SELECT * FROM applyRecords ";
$resultDb = $this->db->query ($query);
$jobs = array ();
while ( $row = $resultDb->fetchObject () ) {
$job = new Job ();
$job->title = $row->jobTitle;
$job->url = $row->file;
$jobs [] = $job;
}
return $jobs;
}
i have here to file and jobTitle.
in admin inc. i call this function like that
$jobs3 = $jobHome->getAllRec();
and try to order with their jobTitle but have error and dont understand
foreach($jobs3 as $job)
{
$groupJobs = [$job->title][$job->url] = $job;
}
what's wrong here?
I think this is what you are trying to do:
Group job applications by title of job applying to
$groupJobs = array();
foreach($job3 as $job){
if(!isset($groupJobs[$job->title])){
$groupJobs[$job->title] = array();
}
$groupJobs[$job->title][] = $job; // add job to group
}
Instead of ordering in PHP, order in SQL, and then continue.
Instead of
"SELECT * FROM applyRecords "
try
"SELECT * FROM applyRecords ORDER BY jobtitle "
Try something like this:
$groupJobs[$job->title] = array(
$job->url => $job
);
The groupJobs Array Must be defined as Array before foreach.
And remember, $job is an object.
Just sort the records at the time of database fetch
"SELECT * FROM applyRecords ORDER BY jobTitle"
$groupJobs = [$job->title][$job->url] = $job;
This is not valid php syntax. I can't even see what are you trying to do here but I make a wild guess:
$groupJobs[] = array(
"title" => $job->title,
"urls" => array($job->url1, $job->url2)
);
About the ordering: You should add a parameter for this and let sql do to ordering:
public function getAllRec($order)
{
$query = "SELECT * FROM applyRecords ";
if ($order) $query .= " ORDER BY " . $order;
$resultDb = $this->db->query ($query);
...
My final answer is below
$groupJobs = array();
foreach($jobs3 as $job)
{
$groupJobs[$job->title][] = $job;
}
foreach($groupJobs as $key => $value){
$key . "<br />";
foreach($value as $node){
$node->url;
$node->name;
}
}
Thank you all.
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;
}
I have this code
public function getList()
{
$array = array();
$r = mysql_query( "SELECT * FROM hobby ORDER BY hobby_name ASC" );
while( $ro = mysql_fetch_object( $r ) )
{
array_push( $array , $ro );
}
if ( count( $array ) > 0 )
return $array;
else
return false;
}
And was wondering if there is an easier way of doing this?
This code first gets all out of the database, pushes it into anarray, checks its count and returns the array or false.
When I get it into my $array I need to make foreach to this object to pase it.
You should return an empty array instead of false, then you can run it through foreach without PHP generating an error. You can further use $array[] = instead of array_push():
public function getList()
{
$array = array();
$r = mysql_query( "SELECT * FROM hobby ORDER BY hobby_name ASC" );
while( $ro = mysql_fetch_object( $r ) )
{
$array[] = $ro;
}
return $array;
}
I would probably do something like you proposed.
One thing I would change : instead of this :
array_push( $array , $ro );
I would probaly use :
$array[] = $ro;
To avoid a function call, which seems useless in this case (both syntaxes should do the same).
Also, I would always return an array : the function is called "getList", so, in my opinion, it should return... a list.
Even when there is no element, it should return an empty list (ie, empty array), and not a boolean false.
This also means you can just return your $array, not having to count the number of elements it contains ; so, I suppose I would end up with something like this :
public function getList()
{
$array = array();
$r = mysql_query( "SELECT * FROM hobby ORDER BY hobby_name ASC" );
while( $ro = mysql_fetch_object( $r ) )
{
$array[] = $ro;
}
return $array;
}
$r = mysql_query("SELECT * FROM hobby ORDER BY hobby_name ASC");
return mysql_num_rows($r) > 0 ? return mysql_fetch_array($r) : false;