Easier way of doing this? - php

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;

Related

Assign output of PHP function to a variable

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
}

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

Create a php array with keys and values from mysql query

I'm trying to store my mysql query in an array like this :
$arr = array ( "field1"=>"value" , "field2"=>"value" , "field3"=>"value" , ... );
I've tried this but don't work like I need :
$row_selectProduct = array();
$sResult = $db->query( 'SELECT * FROM tbl' )
while ( $aRow = $sResult->fetch_assoc() )
{
$sInfo = $sResult->fetch_field();
// General output
$row_selectProduct[ $sInfo->name ] = $aRow;
}
$sResult->close();
Thx for help
EDIT :
Sorry for misunderstanding...
I'd like to name keys by the field name in database.
I try to reproduce this :
$result = array();
while ($row_selectProduct = mysql_fetch_assoc($selectProduct));
{
$row_array= array();
$row_array['field_name1_In_DB'] = $row_selectProduct['field_name1_In_DB'];
$row_array['field_name2_In_DB'] = $row_selectProduct['field_name2_In_DB'];
$row_array['field_name3_In_DB'] = $row_selectProduct['field_name3_In_DB'];
$row_array['field_name4_In_DB'] = $row_selectProduct['field_name4_In_DB'];
$row_array['field_name5_In_DB'] = $row_selectProduct['field_name5_In_DB'];
...
array_push($result,$row_array);
};
Using PDO connection functions, it's quite simple --
foreach($db->query('SELECT field_name1,field_name2 FROM table') as $row) {
echo $row['field_name1'].' '.$row['field_name2']; //etc...
}
Here's a good tutorial for PDO in PHP if you want more.
while ( $aRow = $sResult->fetch_assoc() )
{
foreach($aRow as $fieldname => $fieldvalue) {
$row_selectProduct[$fieldname] = $fieldvalue;
}
}
but you will overwrite your $row_selectedProduct with every record and the var at the end will only have stored the last record
if you would like to have all results in one array you should:
$results = array();
while ( $aRow = $sResult->fetch_assoc() )
{
$results[] = $aRow;
}
if you know that there will be only one result you need only:
$result = $sResult->fetch_assoc();

array to string php

Hy every one I have this problem with an array I start like this...
$name = array($_POST['names']);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
$nameId[] = array('ids' => $row['id'] );
}
which gives me arrays like this..
$name:
array('0'=>'name1,name2,name3')
$names:
array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
how can I bring this in an string/form like this..
array('0'=>'61,6,1')
The idea is to save the ids to the Database.
Or is the a better more efficent way to get names from a form compare them with a database and get the ids back to save them to the Database?
many thanks in advance.
Change your assignment to this:
$nameId[] = $row['id'];
$name = array(name1,name2,name3);
$nameId = array();
$query = mysql_query("SELECT id FROM types WHERE find_in_set (name, '$name')");
while($row = mysql_fetch_assoc($query)){
//below line changed
$nameId[] = $row['id'] ;
}
$string = implode(',',$nameId);
Try this :
$array = array(0=>array(0=>'61'),1=>array(0=>'6'),2=>array(0=>'1'));
$result = implode(",",call_user_func_array('array_merge', $array));
Please note : Here all are numeric keys, so change your code to :
$nameId[] = array($row['id'] ); , remove key 'ids' from here
Output :
61,6,1
Thats what I think
$nameId[] = $row['id'];
$stringId = implode(',',$name);
Use following function that will loop through array and find ids key and merge it into other array and after that when you calling this function it will impload it.
function CustomFindJoinArray( $needly, $array )
{
$results = array();
foreach ( $array as $key => $value )
{
if ( is_array( $value ) )
{
$results = array_merge($results, foo( $needly, $value ));
}
else if ( $key == $needly )
{
$results[] = $value;
}
}
return $results;
}
echo implode( ",", CustomFindJoinArray( "ids", $your_array ) );
where $your_array will be array('0'=>array('ids'=>'61'), '1'=>array('ids'=>'6'), '2'=>array('ids'=>'1'))
OR More simple
foreach ($your_array as $key => $ids) {
$newArray[] = $array[$key]["ids"];
}
$string = implode(',', $newArray);
$ids = array();
foreach($nameId as $curr) {
$ids[] = $curr['ids'];
}
$str = "(".implode(",",$ids).")";

Creating Structured array by Recursive function

I have a table
Which I want show recursively like below picture
I am using a recursive function in php
function reccall($cat_id)
{
global $no,$recArray;
$sql = "SELECT a.*
FROM cat_master
WHERE
parent_id = $cat_id
ORDER BY
id ASC
";
$result = mysql_query($sql) or die("Could not fetech Recursively");
while($row = mysql_fetch_object($result))
{
$recArray[$no]['value'] = mysql_real_escape_string($row->value);
$recArray[$no]['id'] = $row->id;
++$no;
reccall($row->id);
}
return $recArray;
}
but I am not able to generate a structured array like how the order is not the picture. A simple array is created all the time. Can anyone help me with creating the structured array like the order shown above.
<?
// I identified this function separately because it is performed only once, for preparing data
// It's collect an array of all parents in the correct order for each id
function dest($array) {
foreach($array as $key=>$value) {
if($value['pid']==0) continue;
$pid = $key;
$array[$key]['dest'] = array();
while ( $pid = $array[$pid]['pid'] ) {
if($key == $pid) exit("this tree is broken");
$array[$key]['dest'][] = $pid;
}
}
return $array;
}
// Recursive function that puts the items in the correct tree. removes the parameter dest.
function tree($array) {
foreach($array as $key=>$value) {
if( is_array($value['dest']) && !empty($value['dest']) ) {
$pid = array_pop($value['dest']);
if( empty($value['dest']) ) unset($value['dest']);
$array[$pid]['childrens'][$key] = $value;
$array[$pid]['childrens'] = tree($array[$pid]['childrens']);
unset($array[$key]);
}
}
return $array;
}
$array = array(
1 => array(
'title'=>'q',
'pid'=>0,
),
2 => array(
'title'=>'w',
'pid'=>1,
),
3 => array(
'title'=>'e',
'pid'=>0,
),
4 => array(
'title'=>'r',
'pid'=>2,
),
5 => array(
'title'=>'t',
'pid'=>1,
),
);
$tree = tree( dest($array) );
echo '<pre>';
print_r($array);
print_r($tree);
?>
By the way, I should note that these arrays are not very useful. Better to use the result of the function dest().
use this function instead of your function and your problem will be solved I hope
function reccall($cat_id)
{
$sql = "SELECT a.*
FROM cat_master
WHERE
parent_id = $cat_id
ORDER BY
id ASC
";
$result = mysql_query($sql) or die("Could not fetech Recursively");
while($row = mysql_fetch_object($result))
{
$recArray[$no]['main']['value'] = mysql_real_escape_string($row->value);
$recArray[$no]['main']['id'] = $row->id;
$recArray[$no]['child'] = reccall($row->id);
++$no;
}
return $recArray;
}

Categories