Return values for appropriate arguments - php

Is here any possible to write single return for both $strValues and $strThumbImages i need to return $strValues for every time but returning $strThumbImages is just when it is available..
function doSelectBranchRecords($objArray,$ImageId = NULL)
{
global $global_config;
$strWhereClause = '';
if ($objArray['frmNameSearch']) {
$strWhereClause.= " AND A.branch_ident = '".$objArray['frmNameSearch']."' ";
}
if ($objArray['frmLoanSearch']) {
$strWhereClause.= " AND A.loan_ident = '".$objArray['frmLoanSearch']."' ";
}
if ($objArray['frmBeneficiarySearch']) {
$strWhereClause.= " AND A.beneficiary_idents = '".$objArray['frmBeneficiarySearch']."' ";
}
if ($objArray['frmDateSearch']) {
$strDate = explode("-", $objArray['frmDateSearch']);
$strAccountstarted = $strDate[2].'-'.$strDate[1].'-'.$strDate[0];
$strWhereClause.= " AND A.account_started = '".$strAccountstarted."' ";
/*printArray($strWhereClause); exit;*/
}
if ($ImageId) {
$strThumbImages = $global_config["SiteGlobalUploadPath"].$ImageId;
return $strThumbImages;
}
$strSqlSelect = "SELECT A.*,B.branch_name FROM tbl_companydetails as A,tbl_branchdetails as B where A.branch_ident=B.branch_id $strWhereClause order by company_id DESC";
$strValues = SelectQry($strSqlSelect);
return $strValues;
}

A php function can't return more than one variable. You could get both results from the function by returning an array with either one or two keys in it, then do a check in your calling code to see what has been set. So the end of your function becomes:
...
}
$output = array();
if ($ImageId) {
$strThumbImages = $global_config["SiteGlobalUploadPath"].$ImageId;
$output['thumbImages'] = $strThumbImages;
}
$strSqlSelect = "SELECT A.*,B.branch_name FROM tbl_companydetails as A,tbl_branchdetails as B where A.branch_ident=B.branch_id $strWhereClause order by company_id DESC";
$strValues = SelectQry($strSqlSelect);
$output['strValues'] = $strValues;
return $output;
}

#Simon and #Suchit are right in that you cannot return more than one variable. But in php it is very straightforwarded to return a list with multiple items like so:
function getXYZ(){
return array(4,5,6);
}
list($x,$y,$z) = getXYZ();
So in your case this could look like so:
$strThumbImages = null;
if ($ImageId) {
$strThumbImages = $global_config["SiteGlobalUploadPath"].$ImageId;
}
$strSqlSelect = "SELECT A.*,B.branch_name FROM tbl_companydetails as A,tbl_branchdetails as B where A.branch_ident=B.branch_id $strWhereClause order by company_id DESC";
$strValues = SelectQry($strSqlSelect);
return array($strValues, $strThumbImages);

As above #Simon Brahan said you can not return more than one variable.
so you can use array with different keys.but you should also check if $ImageId is set and not null.
if (isset($ImageId) && !is_null($ImageId)) {
$strThumbImages = $global_config["SiteGlobalUploadPath"].$ImageId;
$output['thumbImages'] = $strThumbImages;
}
$strSqlSelect = "SELECT A.*,B.branch_name FROM tbl_companydetails as A,tbl_branchdetails as B where A.branch_ident=B.branch_id $strWhereClause order by company_id DESC";
$strValues = SelectQry($strSqlSelect);
$output['strValues'] = $strValues;
return $output;

Related

recursive function is not working as expected.

public function subchapt()
{
$result = $this->recursive_subchapter_id($level_title);
}
public function recursive_subchapter_id($level_title)
{
$level_data = $this->db->query("SELECT * FROM presto_project_level WHERE level_title ='". $level_title."'")->result_array();
if(count($level_data)>0){
$parentid1 = '';
$leveltitle1 = '';
$parentid1 = trim($level_data[0]['parent_id']);
$leveltitle1 = trim($level_data[0]['level_title']);
if($parentid1 == '0') {
return $leveltitle1;die;
}
else
{
$res = $this->recursive_subchapter_id($parentid1);
return $res;die;
}
}
else{
return $level_title;die;
}
}
every time getting result array is null. i tried directly in url so it was give result array and its count. but while call from other function it was give count of zero.
instead of checking the parentid in the recursive_subchapter_id(), check in subchapt() and then call again recursive_subchapter_id() if it not satisfy the condition.

Echo return mulitiple variables

I have a problem with an mysql query, I need to extract all data from my table and use him as another sql query.
This is the code I am using:
<?php
function toateMhz() {
require ('SQL.php');
$sql = "SELECT DISTINCT(performanta_cpu) FROM modele ORDER BY CAST(performanta_cpu AS UNSIGNED) DESC";
foreach ($dbh->query($sql) as $linie)
{
$mhz[] = $linie['performanta_cpu'];
}
if(isset($mhz['1']))
{
$mhz1 = "$mhz[0] OR ";
}
else $mhz['0'];
if(isset($mhz['2']))
{
$mhz2 = "$mhz[1] OR ";
}
else $mhz['1'];
if(isset($mhz['3']))
{
$mhz3 = "$mhz[2] OR ";
}
else $mhz['2'];
if(isset($mhz['4']))
{
$mhz4 = "$mhz[3] OR ";
}
else $mhz['3'];
if(isset($mhz['5']))
{
$mhz5 = "$mhz[4] OR ";
}
else $mhz['4'];
if(isset($mhz['6']))
{
$mhz6 = "$mhz[5] OR ";
}
else $mhz['5'];
if(isset($mhz['7']))
{
$mhz7 = "$mhz[6] OR ";
}
else $mhz['6'];
if(isset($mhz['8']))
{
$mhz8 = "$mhz[7] OR ";
}
else $mhz['7'];
if(isset($mhz['9']))
{
$mhz9 = "$mhz[8] OR ";
}
else $mhz['8'];
if(isset($mhz['10']))
{
$mhz10 = "$mhz[9] OR ";
}
else $mhz['9'];
if(isset($mhz['11']))
{
$mhz11 = "$mhz[10] OR ";
}
else $mhz['10'];
if(isset($mhz['12']))
{
$mhz12 = "$mhz[11] OR ";
}
else $mhz['11'];
if(isset($mhz['13']))
{
$mhz13 = "$mhz[12] OR ";
}
else $mhz['12'];
if(isset($mhz['14']))
{
$mhz14 = "$mhz[13] OR ";
}
else $mhz['13'];
if(isset($mhz['15']))
{
$mhz14 = "$mhz[14] OR ";
}
else $mhz['14'];
$frecvente = "$mhz1 $mhz2 $mhz3 $mhz4 $mhz5 $mhz6 $mhz7 $mhz8 $mhz9 $mhz10 $mhz11 $mhz12 $mhz13 $mhz14";
return $frecvente;
}
echo toateMhz();
?>
And this is the result from code:
2000 OR 1600 OR 1500 OR 1400 OR 1000 OR 800 OR
But the correct result is 2000 OR 1600 OR 1500 OR 1400 OR 1000 OR 800 OR 200
Last word must not be OR
Not quite sure but this might do the trick
foreach ($dbh->query($sql) as $linie) {
// append value of this record to the array $mhz
$mhz[] = $linie['performanta_cpu'];
}
// return the concatenation of all elements in $mhz with ' OR ' as "glue" between elements
return join(' OR ', $mhz);
join($s, $arr) is an alias of implode($s, $arr) which concatenates all (string) elements of the given array $arr and putting $s "between" the elements. E.g.
$x = array('a','b', 'c');
echo join(' - ', $x);
prints a - b - c
Use implode to join your array values into a string :
function toateMhz() {
require ('SQL.php');
$sql = "SELECT DISTINCT(performanta_cpu) FROM modele ORDER BY CAST(performanta_cpu AS UNSIGNED) DESC";
foreach ($dbh->query($sql) as $linie)
{
$mhz[] = $linie['performanta_cpu'];
}
return implode(" OR ", $mzh);
}
echo toateMhz();

Escaping issue in building query dynamic function variables

I am developing a CMS which works on template page system in a different approach.
I have this object:
$structure = new stdClass;
$structure->homepage->news->method = 'get_articles_by_page_name';
$structure->homepage->news->lang_key = translate('home_news');
$structure->homepage->news->lang = $lang;
$structure->homepage->news->add_media = true;
$structure->homepage->news->media_type = 'ibs';
$structure->homepage->news->limit = '5';
$structure->homepage->news->order_by = 'a.logical_date';
$structure->homepage->news->asc_des = 'desc';
$structure->homepage->news->result_type = 'result';
This helps to get contents as following:
foreach ($structure as $page_template => $page_contents)
{
// Call Customized Content for Homepage
if($this->data['page_data']->page_view == $page_template) // homepage comes ok.
{
foreach ($page_contents as $view_var_name => $page_cdata)
{
$method = $page_cdata->method; // method names comes
$page_cdata = substr(implode(",",(array) $page_cdata),(strlen($method)+1)) . '\'';
//Returns as expected:
//**'Haberler','tr','1','ibs','5','a.logical_date','desc','result'**
$this->data[$view_var_name] = $this->publish->$method($page_cdata);
vdebug($page_cdata);
}
}
}
It suppose to call them model function of:
function get_articles_by_page_name( $lang_key='',$lang='en',$add_media=true,
media_type='ibs',$limit='0',$order_by='a.logical_date',$asc_desc='desc',$result_type='result')
However, there is a problem with. When I return to last worked query it says:
SELECT * FROM (`page`) JOIN `page_lang` ON `page`.`id_page` = `page_lang`.`id_page` WHERE `page_lang`.`title` = '\'News\',\'tr\',\'1\',\'ibs\',\'5\',\'a.logical_date\',\'desc\',\'result\''
It souldn't be like this. every thing between commas are parameters of the method function. What cause this, any idea?
Content of get_articles_by_page_name:
function get_articles_by_page_name ($lang_key='',$lang='tr',$add_media=true,$media_type='ibs',$limit='0',$order_by='a.logical_date',$asc_desc='desc',$result_type='result')
{
// Define variables
$id_page = '';
$result = '';
// Get Page Data
$page_name = $lang_key;
$get_page = $this->vayes->getJoined('page','page_lang','id_page','','',array('page_lang.title'=>$page_name),'row');
if($get_page)
{
$id_page = $get_page->id_page;
$result = $this->publish->get_articles($lang,$id_page,null,false,'',$order_by,$asc_desc,$limit,'result');
}
else
{
$result = array('No id_page specified');
}
return $result;
}
Content of get_articles:
function get_articles($lang='tr',$id_page,$id_article=null,$incl_media=true,$media_type='',$order_by='a.logical_date',$asc_desc='desc',$limit='0',$result_type='result')
{
$this->db->select('*');
$this->db->from('article a');
$this->db->join('article_lang b','b.id_article=a.id_article','left outer');
if($incl_media) {
$this->db->join('article_media c','c.id_article=b.id_article','left outer');
$this->db->join('media d','d.id_media=c.id_media','left outer');
}
if($id_article == null) { $this->db->where('a.id_page',$id_page); }
else /*------------->*/ { $this->db->where('a.id_article',$id_article); }
$this->db->where('b.lang',$lang);
$this->db->where('b.online',1);
if(($incl_media == true) AND $media_type != '' ) $this->db->where('c.usage',$media_type);
// Order Results
$this->db->order_by($order_by,$asc_desc);
// Limit Results
if ($limit) $this->db->limit($limit);
$query = $this->db->get();
if($query->num_rows() > 0)
{
$result = $query->$result_type();
$query->free_result();
return $result;
}
return false;
}
try stripslashes()
Attempting to use stripslashes on an array in 5.2.17 returns the string "Array", but in 5.3.6 it returns NULL. So using stripslashes() on an array you will need to do it recursively;
function stripslashes_deep($value)
{
$value = is_array($value) ?
array_map('stripslashes_deep', $value) :
stripslashes($value);
return $value;
}
// Example
$array = array("f\\'oo", "b\\'ar", array("fo\\'o", "b\\'ar"));
$array = stripslashes_deep($array);
// Output
print_r($array);

MySQL two selects but totally different

ok I have to tables they are along the same lines, but one that lists all stores that sell goods and one that is products that we sell.
Think of it like Fruit and Veg totally different.
What I need to work out is if there is 7 fruit and we need 8 listings then go and get a random veg and show it in the same results.
Here is what our query currently looks like. you will notice we can send a $count which we send as 8 but we may want to increase to 10 or even make it 4.
public function realcashoffers($state,$count)
{
$this->state = $state;
$this->number = $count;
//print count($this->JSONselect("business_stores","*",NULL,NULL),1);
print $this->JSONselect("approved_business, business_stores, Real_Cash_Offers"," *, group_concat(offer ORDER BY offer ASC SEPARATOR ',') as offers"," approved_business.id = business_stores.business_id AND Real_Cash_Offers.business_id = approved_business.id AND Real_Cash_Offers.storeid = business_stores.storeid AND business_stores.state = '{$this->state}'","GROUP BY id ORDER BY RAND(), approved_business.id DESC LIMIT {$this->number} ");
}
this->JSONselect goes to
//JSON select
public function JSONselect($table,$options,$where,$orderby)
{
$options = empty($options) ? "*" : $options;
$where = empty($where) ? "1=1" : $where;
$orderby = empty($orderby) ? "" : $orderby;
$qry = "SELECT $options FROM $table WHERE $where $orderby ";
//print $qry;
$result = mysql_query($qry) or die(json_encode(array("error",mysql_error())));
while(($row = mysql_fetch_assoc($result))){ $resultArray[] = $row; }
//print json_encode($resultArray);
return count($resultArray) < 1 ? print "[".json_encode(array("error"=>"sorry"))."]" : json_encode($resultArray);
}
If I understand correctly I think what your looking for is something along the lines of this;
Update the main function to determine if there were enough results and call the secondary query if not
public function realcashoffers($state,$count)
{
$this->state = $state;
$this->number = $count;
$result = $this->JSONselect("approved_business, business_stores, Real_Cash_Offers"," *, group_concat(offer ORDER BY offer ASC SEPARATOR ',') as offers"," approved_business.id = business_stores.business_id AND Real_Cash_Offers.business_id = approved_business.id AND Real_Cash_Offers.storeid = business_stores.storeid AND business_stores.state = '{$this->state}'","GROUP BY id ORDER BY RAND(), approved_business.id DESC LIMIT {$this->number} ");
$remaining = count($result) - $count;
if ($remaining) {
$result = array_merge($result, $this->JSONselect(.. enter secondary call here using $remaining as the limit..);
}
$this->JSONprint($result);
}
Update JSONselect to return the results instead of being responsible for printing them as well
public function JSONselect($table,$options,$where,$orderby)
{
$resultArray = array();
$options = empty($options) ? "*" : $options;
$where = empty($where) ? "1=1" : $where;
$orderby = empty($orderby) ? "" : $orderby;
$qry = "SELECT $options FROM $table WHERE $where $orderby ";
//print $qry;
$result = mysql_query($qry) or die(json_encode(array("error",mysql_error())));
while(($row = mysql_fetch_assoc($result))){ $resultArray[] = $row; }
//print json_encode($resultArray);
return $resultArray;
}
create JSONprint that will print the results returned
protected function JSONprint($resultArray) {
return count($resultArray) < 1 ? print "[".json_encode(array("error"=>"sorry"))."]" : json_encode($resultArray);
}

Php: loop breaks when call a method inside a while in a class

I have a problem in a class I can't solve, the loop breaks in getAlojamiento() when I call getImagenes() inside the while. In this case getAlojamiento() returns only one row, it should return all the rows. Here are the methods involved:
//THIS GETS THE ROWS FROM A TABLE AND RETURN AN ARRAY, IF $id IS SET, CHECKS IF id_asoc == $id
public function getImagenes($table, $id=false){
$return = '';
//checks if id id == true
if($id){
$sql="SELECT * FROM $table WHERE id_asoc = '$id' ORDER BY id DESC";
}else{
$id = '';
$sql="SELECT * FROM $table ORDER BY id DESC";
}
//this make the sql request (returns an array)
if(!$this->MySQLQuery($sql)){
$return = false;
}else{
if($this->dbNumberRows == 0){ //cheks if there are results
$return = false;
}else{ //if has results makes and fills an array
$items = array();
while($f = mysql_fetch_object($this->dbResults)){
$items[$f->id]['id'] = $f->id;
$items[$f->id]['id_asoc'] = $f->id_asoc;
$items[$f->id]['comentario'] = htmlentities($f->comentario);
$items[$f->id]['nombre'] = htmlentities($f->nombre);
}
$return = $items;
}
}
return $return;
}
//THIS GETS THE ROWS FROM A TABLE AND RETURN AN ARRAY
public function getAlojamiento($id=false){
$return = '';
//checks if id id == true
if($id){
$sql="SELECT * FROM tb_alojamiento WHERE id = '$id' LIMIT 1";
}else{
$id = '';
$sql="SELECT * FROM tb_alojamiento ORDER BY titulo ASC";
}
//this make the sql request (returns an array)
if(!$this->MySQLQuery($sql)){
$return = false;
}else{
if($this->dbNumberRows == 0){ //cheks if there are results
$return = false;
}else{ //if has results makes and fills an array
$items = array();
while($f = mysql_fetch_object($this->dbResults)){
$imagenes_arr = $this->getImagenes('tb_alo_imagenes', $f->id); //this is causing the break
$items[$f->id]['id'] = $f->id;
$items[$f->id]['titulo'] = $f->titulo;
$items[$f->id]['telefono'] = $f->telefono;
$items[$f->id]['descripcion'] = $f->descripcion;
$items[$f->id]['email'] = $f->email;
$items[$f->id]['url'] = $f->url;
$items[$f->id]['direccion'] = $f->direccion;
$items[$f->id]['ubicacion'] = $f->ubicacion;
$items[$f->id]['coordenadas'] = $f->coordenadas;
$items[$f->id]['disponibilidad'] = $f->disponibilidad;
$items[$f->id]['tarifas'] = $f->tarifas;
$items[$f->id]['servicios'] = $f->servicios;
$items[$f->id]['theme'] = $f->theme;
$items[$f->id]['premium'] = $f->premium;
$items[$f->id]['img_ppal_id'] = $f->img_ppal_id;
$items[$f->id]['imagenes'] = $imagenes_arr;
}
$return = $items;
}
}
return $return;
}
The problem is that you are using $this->dbResults for both queries. When you call getImagenes you are clobbering the dbResults in getAlojamiento.
A simple solution to avoid having the first mysql query affect other queries is to complete it first:
//first loop over the result set from first query
while($f = mysql_fetch_object($this->dbResults))
{
//note: no call to $this->getImagenes here!
$items[$f->id]['id'] = $f->id;
$items[$f->id]['titulo'] = $f->titulo;
....
}
//only now you fetch the images in a second pass
foreach( $items as $id => $item )
{
$items[$id]['imagenes'] = $this->getImagenes('tb_alo_imagenes', $id);
}
//return the complete $items array
$return = $items;
while($f = mysql_fetch_object($this->dbResults)){
$items[$f->id]['id'] = $f->id;
$items[$f->id]['id_asoc'] = $f->id_asoc;
$items[$f->id]['comentario'] = htmlentities($f->comentario);
$items[$f->id]['nombre'] = htmlentities($f->nombre);
}
$return[] = $items;
You're setting the array to be the single $items array. You need to add it to the $return array.

Categories