passing variables in a function to the external function - php - php

There are three functions. Two of the functions uses some variables exactly the same way so I created a third function but the variables aren't able to be passed into those two functions.
EDIT
What I need in more detail. Two functions are identical search() and report() but of course there will be differences too.
search()
public function search(){
if(($_POST['number'] != null) && (is_numeric($_POST['number']))){
$number = trim($_POST['number']);
}else{
$number = "";
}
if (($_POST['name'] != null)) {
$name = strtoupper(trim($_POST['name']));
}else{
$comments = "";
}
if($_POST['date'] != null){
$date = trim($_POST['date']);
$parseDate = explode("/", $date);
$newDate = $parseDate[2].$parseDate[0].$parseDate[1];
}else{
$newDate = null;
}
//something will be done here//
//will require using all 3 of the variables above
}
report()
public function report(){
if(($_POST['number'] != null) && (is_numeric($_POST['number']))){
$number = trim($_POST['number']);
}else{
$number = "";
}
if (($_POST['name'] != null)) {
$name = strtoupper(trim($_POST['name']));
}else{
$comments = "";
}
if($_POST['date'] != null){
$date = trim($_POST['date']);
$parseDate = explode("/", $date);
$newDate = $parseDate[2].$parseDate[0].$parseDate[1];
}else{
$newDate = null;
}
//something will be done here//
//will require using all 3 of the variables above
}
combine()
public function combine(){
//as can be seen. The above two functions are totally the same but after that where I commented "something will be done here" different things would be done with different output.
}
search() and report() will end up using json_encode to pass some data back to the client side.

Related

PHP Pass variable from foreach to function

I'm trying to pass variables from a foreach function that fetch a mysql query to an array, to another function.
I declare the array before the foreach to make it global but no data are passed to the function.
here is my code. If you have any idea of what i'm doing, thanks by advance for your help.
Of course if I replace the called function by what's inside it, everything works like a charm.
but as I'll have to use it several times I would prefer to set my variables in a function.
function fillStuInfos() {
global $studFName, $studLName,c$dateStart, $dateEnd;
$studFName = $EventsGt['fName'];
$studLName = $EventsGt['lName'];
$dateStart = $EventsGt['startDate'];
$dateEnd = $EventsGt['endDate'];
}
$email = $_POST['email'];
$EventsGt = array();
$getEventsQry = 'SELECT * FROM Companies WHERE Email_Company = "'.$email.'" ORDER BY startDate';
foreach ($bddPDO->query($getEventsQry) as $EventsGt) {
$intCur = date_diff(date_create($today), date_create($EventsGt['endDate']));
$intFut = date_diff(date_create($today), date_create($EventsGt['startDate']));
echo intval($intCur->format('%r%a'));
if (intval($intCur->format('%r%a')) <= 4 && intval($intCur->format('%r%a')) > 0 ) {
fillStuInfos();
} else if ( intval($intFut->format('%r%a')) <= 4 && intval($intFut->format('%r%a')) > 0 ){
fillStuInfos();
} else {
echo 'No Datas!';
exit();
}
}
echo $studLName;
Forget that exists global and pass params to function.
function fillStuInfos($data) {
$studFName = $data['fName'];
$studLName = $data['lName'];
$dateStart = $data['startDate'];
$dateEnd = $data['endDate'];
}
...
foreach (...) {
if (intval($intCur->format('%r%a')) <= 4 && intval($intCur->format('%r%a')) > 0 ) {
fillStuInfos($EventsGt);
} else if ( intval($intFut->format('%r%a')) <= 4 && intval($intFut->format('%r%a')) > 0 ){
fillStuInfos($EventsGt);
} else {
echo 'No Datas!';
exit();
}
}
Your variable you want to be global is $EventsGt, not $studFName, $studLName, $dateStart, $dateEnd
With that said, I would recommend passing the event array as a parameter or passing the individual values as parameters instead.

PHP - putting if statement coding inside of a variable

I am trying to get an if statement to dynamically code itself based on user input. So the if statement code is being inserted into a variable ($if_statement_variable), like this:
$if_statement_variable = "if (";
$price = trim($_GET["Price"]);
if (!empty($price)) {
$if_statement_variable .= " $Product->price < $price ";
}
$product_name = trim($_GET["Product_name"]);
if (!empty($product_name)) {
$if_statement_variable .= " && $Product->$product_name == 'product_name_string' ";
}
// plus many more if GET requests
$if_statement_variable .= ") ";
Then results from an XML file will be displayed based on user values submitted and the $if_statement_variable.
$XMLproducts = simplexml_load_file("products.xml");
foreach($XMLproducts->product as $Product) {
echo $if_statement_variable; // Here is where the problem is
{ // opening bracket for $variable_if_statement
echo $Product->$product_name; // products displayed based on if statement code in $if_statement_variable
} //closing bracket for $variable_if_statement
}
The echo $if_statement_variable above correctly displays $price from this variable string, but does NOT display $Product->price. Assuming $price had a value of 1000, the output is if ( == 1000 ). How can I get $Product->price to correctly insert itself into the $if_statement_variable so that it displays the $Product->price values from the XML file?
If you're trying to generate a boolean value dynamically, based on some complicated logic, just assign the true/false value to a variable, (say, $booleanValue) and then do if($booleanValue){}
Something like:
$price = trim($_GET['price']);
$product_name = trim($_GET['Product_name']);
if(!empty($price)){
$booleanValue = ($Product->price < $price);
}
if(!empty($productName)){
$booleanValue = ($booleanValue && $Product->$product_name == 'product_name_string')
}
if($booleanValue){
echo $Product->$product_name;
}
In other words, create a variable to hold the actual boolean value, not a string to hold an expression that will evaluate to a boolean value.
Do not build PHP source as a string. In this case callables are a better solution. A callable is a function inside a variable. In PHP this might be an function name, and array with an object and a method name, an anonymous function or an object implementing invoke.
Here is an example for anonymous functions:
function getCondition($parameters) {
$conditions = [];
if (isset($parameters['Price']) && trim($parameters['Price']) != '') {
$price = trim($parameters['price']);
$conditions[] = function($product) use ($price) {
return $product->price < $price;
}
}
if (isset($parameters['Product_name']) && trim($parameters['Product_name']) != '') {
$productName = trim($parameters['Product_name']);
$conditions[] = function($product) use ($productName) {
return $product->product_name == $productName;
}
}
return function($product) use ($conditions) {
foreach ($conditions as $condition) {
if (!$condition($product)) {
return FALSE;
}
}
return TRUE;
}
}
$condition = getConditon($_GET);
if ($condition($product)) {
...
}
It is important that each function can be called the same way. So if you call the condition function you not need to know, which condition it is. In the example above you can imagine that the getCondition() function can get really complex really fast if you add additional conditions.
If you encapsulate the conditions into classes, the usage becomes more readable:
$condition = new \YourCompany\Product\Conditions\Group(
new \YourCompany\Product\Conditions\PriceMaximum($_GET, 'Price'),
new \YourCompany\Product\Conditions\Name($_GET, 'Product_name')
);
if ($condition($product)) {
...
}
This way you separate the actual condition logic from the from the use. The source of all classes is some more then the anonymous function variant. But you you can put each class in it's own file and use them in any combination you need.
The classes need to implement __invoke().
class Group {
private $_conditions = array();
public function __construct() {
$this->_conditions = func_get_args();
}
public function __invoke($product) {
foreach ($this->_conditions as $condition) {
if (!$condition($product)) {
return FALSE;
}
}
return TRUE;
}
}
class Name {
private $_productName = NULL;
public function __construct($parameters, $name) {
if (isset($parameters[$name]) && trim($parameters[$name]) > 0) {
$this->_productName = trim($parameters[$name]);
}
}
public function __invoke($product) {
return (
NULL === $this->_productName ||
$product->product_name == $this->_productName
);
}
}
class PriceMaximum {
private $_maximum = NULL;
public function __construct($parameters, $name) {
if (isset($parameters[$name]) && trim($parameters[$name]) > 0) {
$this->_maximum = trim($parameters[$name]);
}
}
public function __invoke($product) {
return (
NULL === $this->_maximum ||
$product->price < $this->_maximum
);
}
}
This concept can even be used together with an anonymous function:
$condition = new \YourCompany\Product\Conditions\Group(
new \YourCompany\Product\Conditions\PriceMaximum($_GET, 'Price'),
new \YourCompany\Product\Conditions\Name($_GET, 'Product_name'),
function ($product) {
return $product->category == 'food';
}
);

Custom 404 error message not working in codeigniter

When I access the wrong function in my controller, a 404 error page is working well. But, when i access url like 'http://example.com/model/detail/116', which 116 is wrong number [are not in the database], my 404 error page not working.
I have this code in my controller:
public function detail()
{
$id['id_galeri'] = $this->uri->segment(3);
$detail = $this->app_model->getSelectedData("tbl_galeri",$id);
foreach($detail->result() as $d)
{
$bc['jdl'] = "View";
$bc['id_galeri'] = $d->id_galeri;
$bc['nama'] = $d->nama;
$bc['foto'] = $d->foto;
$bc['deskripsi'] = $d->deskripsi;
$bc['stts_input'] = "deskripsi";
}
if($this->uri->segment(3) == '' && $id['id_galeri'] == FALSE)
{
$segment_url = 0;
}else{
if(!is_numeric($this->uri->segment(3)) || !is_string($this->uri->segment(3))){
redirect('404');
}else{
$segment_url = $this->uri->segment(3);
}
}
$this->load->view('frontend/global/bg_top');
$this->load->view('frontend/page/bg_view_model',$bc);
$this->load->view('frontend/global/bg_footer');
}
Sorry for my bad english, please help :-)
Thank you..
Instead of:
redirect('404');
try using CodeIgniter's native:
show_404('page');
EDIT
Try this code, a bit cleaned up and the checks are done before they're saved for views use.
public function detail()
{
$id['id_galeri'] = $this->uri->segment(3);
// Check if the supplied ID is numeric in the first place
if ( ! is_numeric($id['id_galeri']))
{
show_404($this->uri->uri_string());
}
// Get the data
$detail = $this->app_model->getSelectedData("tbl_galeri",$id);
// Check if any records returned
if (count($detail->result()) === 0)
{
show_404($this->uri->uri_string());
}
foreach($detail->result() as $d)
{
$bc['jdl'] = "View";
$bc['id_galeri'] = $d->id_galeri;
$bc['nama'] = $d->nama;
$bc['foto'] = $d->foto;
$bc['deskripsi'] = $d->deskripsi;
$bc['stts_input'] = "deskripsi";
}
/**
* Here do whatever you want with the $segment_url which doesn't seem to be
* used in your code
*/
$this->load->view('frontend/global/bg_top');
$this->load->view('frontend/page/bg_view_model',$bc);
$this->load->view('frontend/global/bg_footer');
}

Codeigniter Search Query doesnt work correctly

Basically works by displaying a form where the user can input 2 variables $no and $first but i can only get it to display a result when i enter both fields. I need it to work so when i enter 1 variable it will display results.
I thought i could use some sort of OR statement but i'm unsure how to implement it. Any help would be appreciated and i apologize if its not clear enough i'm fairly new when it comes to codeigniter.
Controller
public function query()
{
$no = $this->input->post('no');
$first = $this->input->post('first');
$this->load->model("test");
$data['query']=$this->test->query($no,$first);
$this->load->view('query',$data);
}
Model
function query($no, $first)
{
return $query = $this->db->get_where('table', array('no' => $no,
'first' => $first ))->result();
}
View
<?php foreach($query as $row): ?>
<tr>
<td><?php echo $row->no; ?></td>
<td><?php echo $row->date; ?></td>
<td><?php echo $row->first; ?></td>
</tr>
<?php endforeach; ?>
You can try preparing the where clause first
function query($no = "", $first = "")
{
$response = array();
if($first != "" || $no != ""){
$where = "";
if($no == "") $where = 'first = '.$first;
if($first == "") $where = 'no = '.$no;
if($first != "" && $no != "") $where = 'no = '.$no.' AND first = '.$first;
$fetch = $this->db->where($where)->from('table')->get();
if($fetch->num_rows() > 0) $response = $fetch->result_array();
}
return $response;
}
Hope I get the idea you want.
You need to separate out your WHERE arguments:
function query($no, $first)
{
$this->db->select();
$this->db->from('table');
$this->db->where('no', $no);
if (!empty($first))
{
$this->db->or_where('first', $first); // or use `and_where`
}
return $query = $this->db->get()->result();
}
Source: http://ellislab.com/codeigniter/user-guide/database/active_record.html
function query($no = '%', $first = '%')
{
$this->db->where("'no' = $no OR 'first' = $first");
$query = $this->db->get('table');
if($query->num_rows() >= 0)
{
$return $query->result();
}
}
If you feed the values a wild card as default values either can be empty (in fact both can be empty to return all results) then just build the entire where statement inside double quotes.
You really don't have to feed the wildcards if you would rather not return all results if the strings are empty, but you should be doing some checking somewhere for empty results or no return.

I need a more efficient way of checking if multiple $_POST parameters isset

I have these variables, and I need to check if all of them isset(). I feel there has to be a more efficient way of checking them rather than one at a time.
$jdmMethod = $_POST['jdmMethod'];
$cmdMethod = $_POST['cmdMethod'];
$vbsMethod = $_POST['vbsMethod'];
$blankPage = $_POST['blankPage'];
$facebook = $_POST['facebook'];
$tinychat = $_POST['tinychat'];
$runescape = $_POST['runescape'];
$fileUrl = escapeshellcmd($_POST['fileUrl']);
$redirectUrl = escapeshellcmd($_POST['redirectUrl']);
$fileName = escapeshellcmd($_POST['fileName']);
$appData = $_POST['appData'];
$tempData = $_POST['tempData'];
$userProfile = $_POST['userProfile'];
$userName = $_POST['userName'];
Try this
$allOk = true;
$checkVars = array('param', 'param2', …);
foreach($checkVars as $checkVar) {
if(!isset($_POST[$checkVar]) OR !$_POST[$checkVar]) {
$allOk = false;
// break; // if you wish to break the loop
}
}
if(!$allOk) {
// error handling here
}
I like to use a function like this:
// $k is the key
// $d is a default value if it's not set
// $filter is a call back function name for filtering
function check_post($k, $d = false, $filter = false){
$v = array_key_exists($_POST[$k]) ? $_POST[$k] : $d;
return $filter !== false ? call_user_func($filter,$v) : $v;
}
$keys = array("jdmMethod", array("fileUrl", "escapeshellcmd"));
$values = array();
foreach($keys as $k){
if(is_array($k)){
$values[$k[0]] = check_post($k[0],false,$k[1]);
}else{
$values[$k] = check_post($k[0]);
}
}
You could extend the keys array to contain a different default value for each post-value if you wish.
EDIT:
If you want to make sure all of these have a non-default value you could do something like:
if(sizeof(array_filter($values)) == sizeof($keys)){
// Not all of the values are set
}
Something like this:
$jdmMethod = isset($_POST['jdmMethod']) ? $_POST['jdmMethod'] : NULL;
It's Ternary Operator.
I think this should work (not tested, from memory)
function handleEmpty($a, $b) {
if ($b === null) {
return false;
} else {
return true;
}
array_reduce($_POST, "handleEmpty");
Not really. You could make a list of expected fields:
$expected = array(
'jdmMethod',
'cmdMethod',
'fileName'
); // etc...
... then loop those and make sure all the keys are in place.
$valid = true;
foreach ($expected as $ex) {
if (!array_key_exists($ex, $_POST)) {
$valid = false;
break;
}
$_POST[$ex] = sanitize($_POST[$ex]);
}
if (!$valid) {
// handle the problem
}
If you can develop a generic sanitize function, that will help - you can just sanitize each as you loop.
Another thing I like to use is function that gives a default as it sanitizes.
function checkParam($key = false, $default = null, $type = false) {
if ($key === false)
return $default;
$found_option = null;
if (array_key_exists($key,$_REQUEST))
$found_option = $_REQUEST[$key];
if (is_null($found_option))
$found_option = $default;
if ($type !== false) {
if ($type == 'string' && !is_string($found_option))
return $default;
if ($type == 'numeric' && !is_numeric($found_option))
return $default;
if ($type == 'object' && !is_object($found_option))
return $default;
if ($type == 'array' && !is_array($found_option))
return $default;
}
return sanitize($found_option);
}
When a default is possible, you'd not want to do a loop, but rather check for each independently:
$facebook = checkParam('facebook', 'no-facebook', 'string);
It is not the answer you are looking for, but no.
You can create an array an loop through that array to check for a value, but it doesn't get any better than that.
Example:
$postValues = array("appData","tempData",... etc);
foreach($postedValues as $postedValue){
if(isset($_POST[$postedValue])){
...
}
}

Categories