Jump to content

[SOLVED] Help with getting a variable from outside a function!


elpaisa

Recommended Posts

Hi all!

 

I´m working on a script wich outputs xml data from values in a database, and i want to ??? reach a variable from inside a function from another function, i want to do it this way because i have set all a code for a $query variable and want to take the results from that query and use them in another function, this is my code:

 

function build_where_clause($_POST, $fields_labels_ar, $table_name)

 

//Start showing other counts

....    if ($results_type = "search"){

$order_one = str_replace('`','',$quote.$field_name_temp.$quote);

$query = "SELECT ".$table_name.'.'.$order_one.", COUNT(".$table_name.'.'.$order_one.") AS Total FROM ".$table_name." LEFT JOIN equivalences ON ".$table_name.'.'.$order_one." = equivalences.equiv GROUP BY ".$table_name.'.'.$order_one." ORDER BY ".$table_name.'.'.$order_one. " ASC LIMIT 0, 30  ";

 

     

$result = mysql_query($query) or die(mysql_error());

// Print out the contents of each row into a table

while($row = mysql_fetch_array($result)){

echo '...........

 

return $where_clause;

   

} // end function build_where_clause

 

this the another function from where i want to call the $row results from function build_where_clause()

 

 

function getSalesByYear($_POST, $fields_labels_ar, $table_name) {

 

    //Initialize <categories> element

    $strCat = "<categories>";

 

    //Initialize datasets

    $strAmtDS = "<dataset seriesname='Revenue'>";

    $strQtyDS = "<dataset seriesName='Units Sold' parentYAxis='S'>";

   

// Here is where i want to retrieve the data fetched from $query in the build_where_clause() function:

 

    build_where_clause($row);

   

$strCat .= "<category label='" . $row['Total'] . "'/>";

    //Generate the link

    $strLink = urlencode("javaScript:updateCharts(" . $row[$order_one] . ");");

    $strAmtDS .= "<set value='" . $row['Total'] . "' link='" . $strLink . "'/>";

    $strQtyDS .= "<set value='" . $row['Total'] . "'/>";

 

//Closing elements

$strCat .= "</categories>";

$strAmtDS .= "</dataset>";

$strQtyDS .= "</dataset>";

//Entire XML - concatenation

$strXML = $strCat . $strAmtDS . $strQtyDS;

 

return $strXML;

}// End function getSalesByYear

 

 

 

There are 2 methods you can use:

 

1.  Declare a variable global in BOTH functions.  Keep in mind that it will keep its value between calls to the functions.  The line "global $var" will do this.

2.  Return an array containing all the data you need, instead of a simple variable.  Eg.

 

return array(
  'where_clause' => $where_clause,
  'query_data' => $query_data,
);

Can you adjust these lines to my code for a most visual example, or all i need is just call  the variable as global?.

 

and can you tell me if there's another method without using register globals on.

 

Thanks for your help!!.

 

register_globals just makes certain variables global by default.  You can always make more variables global yourself in the script.

 

<?php
function build_where_clause($_POST, $fields_labels_ar, $table_name)
                        
            //Start showing other counts
            ....    if ($results_type = "search"){
            $order_one = str_replace('`','',$quote.$field_name_temp.$quote);
            $query = "SELECT ".$table_name.'.'.$order_one.", COUNT(".$table_name.'.'.$order_one.") AS Total FROM ".$table_name." LEFT JOIN equivalences ON ".$table_name.'.'.$order_one." = equivalences.equiv GROUP BY ".$table_name.'.'.$order_one." ORDER BY ".$table_name.'.'.$order_one. " ASC LIMIT 0, 30  ";
                     
     
            $result = mysql_query($query) or die(mysql_error());
            // Print out the contents of each row into a table, and store them too
            $results = array();
            while($row = mysql_fetch_array($result)){
              echo '...........
              $results[] = $row;
            }

   return array(
    'where_clause' => $where_clause,
    'results' => $results,
  );
   
} // end function build_where_clause

this the another function from where i want to call the $row results from function build_where_clause()


function getSalesByYear($_POST, $fields_labels_ar, $table_name) {
   
    //Initialize <categories> element
    $strCat = "<categories>";

    //Initialize datasets
    $strAmtDS = "<dataset seriesname='Revenue'>";
    $strQtyDS = "<dataset seriesName='Units Sold' parentYAxis='S'>";
   
   // Here is where i want to retrieve the data fetched from $query in the build_where_clause() function:

    $ret = build_where_clause($row);
    $where_clause = $ret['where_clause'];
    $results = $ret['results'];

   $strCat .= "<category label='" . $row['Total'] . "'/>";
    //Generate the link
    $strLink = urlencode("javaScript:updateCharts(" . $row[$order_one] . ");");
    $strAmtDS .= "<set value='" . $row['Total'] . "' link='" . $strLink . "'/>";
    $strQtyDS .= "<set value='" . $row['Total'] . "'/>";

   //Closing elements
   $strCat .= "</categories>";
   $strAmtDS .= "</dataset>";
   $strQtyDS .= "</dataset>";
   //Entire XML - concatenation
   $strXML = $strCat . $strAmtDS . $strQtyDS;

   return $strXML;
}// End function getSalesByYear
?>

it gives me a query execution error, becouse the code has later in the same function another return --> return $where_clause;, i've tried to adjust the array to the function replacing that return $where_clause; with the array and still gives an error. if it helps i will put all the function here, and if you can give me some aid i will be very thankful.

 

 

<?php

function build_where_clause($_POST, $fields_labels_ar, $table_name)
// goal: build the where clause of a select sql statement e.g. "field_1 = 'value' AND field_2 LIKE '%value'"
// input: $_POST, $fields_labels_ar, $table_name
{
global $quote, $conn, $select_type_select_suffix, $year_field_suffix, $month_field_suffix, $day_field_suffix, $year_field_suffix, $month_field_suffix, $day_field_suffix;

/*
// get the post variables of the form
reset ($_POST);
while (list($key, $value) = each ($_POST)){
	$$key = $value;
} // end while
*/

$where_clause = "";

$count_temp = count($fields_labels_ar);
// build the where clause
for ($i=0; $i<$count_temp; $i++){
	$field_type_temp = $fields_labels_ar[$i]["type_field"];
	$field_name_temp = $fields_labels_ar[$i]["name_field"];
	$field_separator_temp = $fields_labels_ar[$i]["separator_field"];
	$field_select_type_temp = $fields_labels_ar[$i]["select_type_field"];

	if ($fields_labels_ar[$i]["present_search_form_field"] == "1"){
		if ($_POST[$field_name_temp.$select_type_select_suffix] === 'is_null') { // is_null listbox option selected
			$where_clause .= $quote.$table_name.$quote.".".$quote.$field_name_temp.$quote." IS NULL"; // add the IS NULL value to the sql statement

			$where_clause .= " ".$_POST["operator"]." ";
		} // end if
		else if ($_POST[$field_name_temp.$select_type_select_suffix] === 'is_empty') { // is_empty listbox option selected
			$where_clause .= $quote.$table_name.$quote.".".$quote.$field_name_temp.$quote."  =''"; // add the = '' value to the sql statement

			$where_clause .= " ".$_POST["operator"]." ";
		} // end if
		else{
			switch ($field_type_temp){
				case "select_multiple_menu":
				case "select_multiple_checkbox":
					if (isset($_POST[$field_name_temp])){
						$count_temp_2 = count($_POST[$field_name_temp]);
						for ($j=0; $j<$count_temp_2; $j++){ // for each possible check
							if ($_POST[$field_name_temp][$j] != ""){
								$where_clause .= $quote.$table_name.$quote.'.'.$quote.$field_name_temp.$quote." LIKE '%".$field_separator_temp.$_POST[$field_name_temp][$j].$field_separator_temp."%'";
								$where_clause .= " AND ";
							} // end if
						} // end for
					} // end if
					break;
				case "date":
				case "insert_date":
				case "update_date":
					$select_type_field_name_temp = $field_name_temp.$select_type_select_suffix;
					if ($_POST[$select_type_field_name_temp] != "" || $_POST[$select_type_field_name_temp] === 'is_null'){
						$year_field = $field_name_temp.$year_field_suffix;
						$month_field = $field_name_temp.$month_field_suffix;
						$day_field = $field_name_temp.$day_field_suffix;

						$mysql_date_value = $_POST[$year_field]."-".$_POST[$month_field]."-".$_POST[$day_field];

						switch ($_POST[$select_type_field_name_temp]){
							case "is_equal":
								//$where_clause .= $quote.$table_name.$quote.'.'.$quote.$field_name_temp.$quote." = '".$mysql_date_value."'";
								$where_clause .= $quote.$table_name.$quote.'.'.$quote.$field_name_temp.$quote." = ".$conn->DBDate($mysql_date_value);
								break;
							case "greater_than":
								//$where_clause .= $quote.$table_name.$quote.'.'.$quote.$field_name_temp.$quote." > '".$mysql_date_value."'";
								$where_clause .= $quote.$table_name.$quote.'.'.$quote.$field_name_temp.$quote." > ".$conn->DBDate($mysql_date_value);
								break;
							case "less_then":
								//$where_clause .= $quote.$table_name.$quote.'.'.$quote.$field_name_temp.$quote." < '".$mysql_date_value."'";
								$where_clause .= $quote.$table_name.$quote.'.'.$quote.$field_name_temp.$quote." < ".$conn->DBDate($mysql_date_value);
								break;
						} // end switch

						//$where_clause .= $quote.$table_name.$quote.'.'.$quote.$field_name_temp.$quote." ".$_POST[$select_type_field_name_temp]." '".$mysql_date_value."' ".$_POST["operator"]." ";

						$where_clause .= " ".$_POST["operator"]." ";
					} // end if
					break;
				default:
					$select_type_field_name_temp = $field_name_temp.$select_type_select_suffix;
					if ($_POST[$field_name_temp] != "" || $_POST[$select_type_field_name_temp] === 'is_null'){ // if the user has filled the field or has selected "is_null" as operator
						//John Modified
						switch ($_POST[$select_type_field_name_temp]){
							case "is_equal":
							//Start equivalences for example estrato = 1
                            global  $conn, $db_name, $quote;
							$result = mysql_db_query("$db_name", "SELECT * FROM equivalences")
                                or die("Unable to select Database");
                                $row = mysql_num_rows($result);
                                while ($row = mysql_fetch_array($result)) {
                                $equiv_option = $row["option"];
							$equiv = $row["equiv"];
                                if ($_POST[$field_name_temp] === $equiv_option){
							$_POST[$field_name_temp] = $equiv;
								}//end if
							} //end if

							$where_clause .= $quote.$table_name.$quote.'.'.$quote.$field_name_temp.$quote." = '".$_POST[$field_name_temp]."'";
							//Start debugging


								$result_equiv = $quote.$field_name_temp.$quote . $_POST[$field_name_temp];
								$final_equiv = str_replace("`"," ",$result_equiv);

								//Start showing other counts
								if ($results_type = "search"){
								$final_clause = str_replace(array('`','=','1','2','3','4','5','6','7','8','9',"'"," "),array('',''),$where_clause);
								$order_one = str_replace('`','',$quote.$field_name_temp.$quote);

								$query = "SELECT ".$table_name.'.'.$order_one.", COUNT(".$table_name.'.'.$order_one.") AS Total FROM ".$table_name." LEFT JOIN equivalences ON ".$table_name.'.'.$order_one." = equivalences.equiv GROUP BY ".$table_name.'.'.$order_one." ORDER BY ".$table_name.'.'.$order_one. " ASC LIMIT 0, 30  ";

								$final_field = str_replace(array('`','=','1','2','3','4','5','6','7','8','9',"'"," "),array('',''),$final_equiv);
                               
								echo "<b>Estos son los resultados de tu busqueda por ",$final_equiv."</b><br><br>";
								$result = mysql_query($query) or die(mysql_error());
								// Print out the contents of each row into a table 
								while($row = mysql_fetch_array($result)){
                                    echo '<table width="350" border="0" cellspacing="1" cellpadding="0">
  <tr>
    <td bgcolor="#CCCCCC"><table width="100%" border="0" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF">
      <tr>
        <td> </td>
      </tr>
      <tr>
        <td><b>De:  </b>'. $row[$final_field].' <b>Hay:</b> '.$row['Total'].' </td>
      </tr>
    </table></td>
  </tr>
</table>';
$results[] = $row;
            }
	}									
	break;
						} // end switch
						//} // end else
						$where_clause .= " ".$_POST["operator"]." ";
					} // end if
					break;
			} //end switch
		} // end else
	} // end if
} // end for ($i=0; $i<count($fields_labels_ar); $i++)

if ($where_clause !== '') {
	$where_clause = substr($where_clause, 0, -(strlen($_POST["operator" ])+2)); // delete the last " and " or " or "
} // end if

///////////////////////////////////////////////////////////////////
  // HErE iS WHeRE the code dies and gives the error when i declare return $where_clause as an array, i want to declare the $row wich is the result retrieved from $query, as global, so i can use it later on the next function that is  getSalesByYear().
//////////////////////////////////////////////////////////////////
return $where_clause;
} // end function build_where_clause

?>

 

Thanks too much!

 

EDITED BY WILDTEEN88: Please use code tags (


) when including code within posts. Thank you

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.