empty array outside function and array is ok inisde - php

I'm having problems getting my array values outside a function and from another file.
Inside the array and function i have this, those values are defined with getters and setters
Array ( [0] => XXXXXXXXXX [1] => 5ºA )
Those values are defined by setters and they working since i have the values with print_r
public function getTurmaeProfessor(){
global $myArr;
$myArr[] = $this->getProfessor();
$myArr[] = $this->getTurma();
print_r($myArr);
return $myArr;
}
Now from another file i use this
$dados = $esmaior->getTurmaeProfessor();
if(!$dados){
echo "sem dados";
}
print_r($dados);
And the result is empty, so the array is empty...why??
Thanks
UPDATE
This function is called here
$this->setTurma($nome_turma);
$this->setProfessor(($nome_professor));
$this->getTurmaeProfessor();
So if a put this
public function getTurmaeProfessor(array $myArr)
I'm gonna need to change the call method...how to do it??
UPDATE 2
Ok...
Let me put all maybe it's better to understand.
My main function is this one
public function novaAula($atividade, $turmas, $local, $dataAula, $inicio, $fim, $fundamentacao, $observacoes, $id_professor){
try{
$stmt = $this->db->prepare("INSERT INTO `aulas_exterior` (`atividade`,`id_turma`,`local`,`data_aula`,`inicio`,`fim`,`fundamentacao`,`observacoes`)
VALUES (:atividade,:id_turma,:local,:data_aula,:inicio,:fim,:fundamentacao,:observacoes);");
$stmt->bindparam(":atividade", $atividade);
$stmt->bindparam(":local", $local);
$stmt->bindparam(":data_aula", $dataAula);
$stmt->bindparam(":inicio", $inicio);
$stmt->bindparam(":fim", $fim);
$stmt->bindparam(":fundamentacao", $fundamentacao);
$stmt->bindparam(":observacoes", $observacoes);
$turma = explode(',', $turmas);
foreach ($turma as $id_turma) {
$stmt->bindParam(':id_turma', $id_turma, PDO::PARAM_INT);
$result = $stmt->execute();
$idAula = $this->db->lastInsertId();
$this->insertPedidoByLastId($idAula,$id_professor, $id_turma);
$nome_turma = $this->getTurmaById($id_turma);
$nome_professor = $this->getNomeById($id_professor);
$this->setTurma($nome_turma);
$this->setProfessor(($nome_professor));
$this->getTurmaeProfessor();
}
if (!$result) {
print_r($stmt->errorInfo());
return array('status' => 'error', 'message' => 'Problema ao gravar esta nova atividade...');
}
else{
return array('status' => 'success', 'message' => 'O pedido foi criado com sucesso...');
}
} catch (Exception $ex) {
echo $ex->getMessage();
}
}
and as you can see i'm setting these 2
$this->setTurma($nome_turma);
$this->setProfessor(($nome_professor));
and finally i call the method
$this->getTurmaeProfessor();
Entering this function i want to have names from those 2 setters
public function getTurmaeProfessor(array $myArr){
$myArr[] = $this->getProfessor();
$myArr[] = $this->getTurma();
return $myArr;
}
Until now...everything is working....the problem is when i'm trying to get the return in other file...i receive empt...why??

Do not use global. Fix your function to accept arguments:
public function getTurmaeProfessor(array $myArr){
// remove global $myArr;
....
return $myArr;
}
optionally (but I do not recommend it unless you know you want to go that way) pass your array by reference:
public function getTurmaeProfessor(array &$myArr){
// remove global $myArr;
// no return this time needed
}
Now, since getTurmaeProfessor() requires argument you must change all the invocations to do that, i.e.
$dados = $esmaior->getTurmaeProfessor($myArr);

Related

How to update record in codeigniter?

controller code
if($this->input->post('update'))
{
$n=$this->input->post('pps_pin');
$e=$this->input->post('pps_address');
$m=$this->input->post('stm_shipping_type');
$a=$this->input->post('tsm_time_slot');
$b=$this->input->post('pps_price');
$id=$this->input->post('pps_slid');
$this->Config_model->updaterecords($n,$e,$m,$id,$a,$b);
redirect('Admin_ctrl/config/view_pincode_price');
}
}
model code
function updaterecords($n,$e,$m,$id,$a,$b)
{
$id;
$qr=$this->db->query("UPDATE pincode_price_setup,shipping_type_mst,time_slot_mst SET pps_pin='$n',pps_address='$e',stm_shipping_type='$m',tsm_time_slot='$a',pps_price='$b' WHERE pps_slid='$id'");
return $qr;
}
Delivery Method and Delivery Time Slot data are same
You should modify your code to use codeigniters prepared statements. If I correctly understood relations in your DB, your update records method should looks something like this:
function updaterecords($n, $e, $m, $id, $a, $b)
{
$this->db->set('pps_pin', $n);
$this->db->set('pps_address', $e);
$this->db->set('stm_shipping_type', $m);
$this->db->set('tsm_time_slot', $a);
$this->db->set('pps_price', $b);
$this->db->join('shipping_type_mst', 'pincode_price_setup.pps_shipping_type = shipping_type_mst.stm_sqlid');
$this->db->join('time_slot_mst', 'pincode_price_setup.pps_time_slot = time_slot_mst.tsm_sqlid');
$this->db->where('pps_slid', $id);
$this->db->update('pincode_price_setup');
}
Friendly tip: give your variables some more meaningful names, it would be much easier to work with variable named $pin than $n.
Please try like this
//Controller Code
function update_record($id){
$update_array = array(
'pps_pin' => $this->input->post('pps_pin') ///add fields in array which updated
);
$this->modal_name->update($id,update_array);//pass id & array which want to be update
}
//Modal code
function update($id,$array){
return $this->db->where('id',$id)->update('TABLE_NAME',array);
}
Try This code
function updaterecords($n, $e, $m, $id, $a, $b) {
$this->db->set('pps_pin', $n);
$this->db->set('pps_address', $e);
$this->db->set('stm_shipping_type', $m);
$this->db->set('tsm_time_slot', $a);
$this->db->set('pps_price', $b);
$this->db->where('pps_slid', $id);
$this->db->update('pincode_price_setup');
return ($this->db->affected_rows() != 1) ? false : true;
}
Once codeigniter model is loaded then its default update function works
if($this->input->post('update'))
{
$data = [
'pps_pin' => $this->input->post('pps_pin'),
'pps_address' => $this->input->post('pps_address'),
'stm_shipping_type' => $this->input->post('stm_shipping_type'),
'tsm_time_slot' => $this->input->post('tsm_time_slot'),
'pps_price' => $this->input->post('pps_price'),
'pps_slid' => $this->input->post('pps_slid'),
];
$this->Config_model->id = $id;
$this->Config_model->update($data);
redirect('Admin_ctrl/config/view_pincode_price');
}
}
So I am sure we don't need to define a separate function in model for same purpose.
So as I understand it, you want to update records in your database. I will not write it for you. I will show you an example.
This code may not be perfect but it works for my localhost project.
Create a function to update records in your controller.
Example:
public function update($id){
$id = $this->input->post('id');
//create $data array and add your data to array
$data = array(
'nazov_divizia' => $this->input->post('nazov')
);
//send this $data array with $id to your update function in model
$this->Divizia_model->updateData($id, $data);
//you can create flash message if you want
$this->session->set_flashdata('message', 'Údaje upravené');
//redirect to your controller index function
redirect(base_url().'divizia');
}
Create a function to update the record in your model.
Example:
public function updateData($id, $data)
{
$this->db->where('id_divizia', $id);
$this->db->update('divizia', $data);
}

zend Framework 2 update query by TableGateway Object

public function update($table, $where = array(), $data_arr = array()){
print_r($data_arr);
$adapter = $this->tableGateway->getAdapter();
$projectTable;
if($table != null){
$projectTable = new TableGateway($table, $adapter);
}else{
$projectTable = new TableGateway('account_master', $adapter);
}
echo "158";
try {
echo "123";
$rowset = $projectTable->update(function(Update $update) use ($where, $data_arr) {
$update->set(array('statement_no' => '01010'));
$update->where($where);
echo $update->getSqlString();
});
} catch (\Exception $e) {
print_r($e);
}
print_r($rowset);
die();
}
my Output print : 158123
it's give me pass array in set() function that i already pass as argument. also i have tried to convert object to array ((arrya)$objetc) but it's not work for me.
[10-Jul-2017 05:11:34 America/Denver] PHP Catchable fatal error: Argument 1 passed to Zend\Db\Sql\Update::set() must be of the type array, object given, called in /home2/flywing1/vendor/zendframework/zend-db/src/TableGateway/AbstractTableGateway.php on line 336 and defined in /home2/flywing1/vendor/zendframework/zend-db/src/Sql/Update.php on line 93
You may do that by implementing a Zend\Db\Sql\Update object. You may create that object using the TableGateway. You should be able to do the following in your model
public function update($set, $where)
{
// Here is the catch
$update = $this->tableGateway->getSql()->update();
$update->set($set);
$update->where($where);
// Execute the query
return $this->tableGateway->updateWith($update);
}
Try it,
I was with the same issues, I tried with this, and it worked.
$rowset = $projectTable->update(array('statement_no' => '01010'), $where);

PHP/Laravel disappearing variable

I have some very strange behaviour in an app I am working on. In the example below there are 2 functions.
public function updatePhpVhostVersions(Request $r) {
$data = array(
'hostname' => $r['hostname'],
'username' => $r['username'],
'vhost' => $r['vhost'],
'php_version' => $r['php_version']
);
$result = Cpanel::setPhpVhostVersions($data)->data;
if($r->ajax()){
return Response::json($result);
}
return $result;
}
public function getInstalledPhpVersions(Request $r) {
$data = array(
'hostname' => $r['hostname'],
'username' => $r['username']
);
$result = Cpanel::getInstalledPhpVersions($data)->data;
if($r->ajax()){
return Response::json($result);
}
return $result;
}
The two functions contain Cpanel:: ... ($data)->data; this gets handeled by a __call method. In this method I use a function that prepares some vars, caching, etc. to simplify things I have combined some functions into one.
private function prepare($function, $arguments) {
// Dettirmine what will be used
$this->function = $function;
$nameSplit = preg_split('/(?=\p{Lu})/u', $function);
$this->class = 'App\\Phase\\Cpanel\\' . $this->folder($nameSplit) . '\\' . $this->file($nameSplit);
// Cache True/False
if(isset($this->arguments['cache'])) {
$this->cache = $this->arguments['cache'];
}
// Get the provided arguments
// these are used in the API post
if(isset($arguments[0]['hostname'], $arguments[0]['username'])) {
$arguments = $arguments[0];
}
$this->arguments = $arguments;
// Flush the cache when needed
if (!$this->cache || in_array($nameSplit[0], array('create', 'delete', 'add', 'install', 'set'))) {
try {
Cache::tags(['cpanel', $this->function . $arguments['username']])
->flush();
} catch (Exception $e) {
dd($arguments);
}
}
}
The prepare method is used every time the __call method gets used. In Cpanel::setPhpVhostVersion() the $arguments somehow get empty after the following if statement.
// Flush the cache when needed
if (!$this->cache || in_array($nameSplit[0], array('create', 'delete', 'add', 'install', 'set'))) {
try {
Cache::tags(['cpanel', $this->function . $arguments['username']])
->flush();
} catch (Exception $e) {
dd($e);
}
}
Before Cache::tags() the $arguments contains an array with some user information. But when Cache::tags()->flush() gets called it throws an exception that $arguments['username'] is empty. Now if I dd($arguments) after this, it returns an empty array. If I dd() before this the array still has the information. This only happens with Cpanel::setPhpVhostVersion() not with the 37 other possible Cpanel:: ... () what could be causing this?
EDIT
After some playing around with the code, I noticed that $arguments gets empty everytime after it gets used. It does not matter where, it just gets empty. (But only with setPhpVhostVersions)
Example
if(!isset($this->arguments['username'])) {
return Api::respondUnauthenticated('Account username is a required parameter');
}
Before the !isset() the $arguments['username'] exists, during and after the !isset() I get the exception:
ErrorException: Undefined index: username

Same Function Passing different parameter in same query getting the both output at same time

I am sending two parameter From=2015-08-01 and To=2015-08-31 is working fine. Then how to also passing parameter (From2=2015-04-01 and To2 =2015-08-31) and getting the both output at same time. Please do not write any other functions. Please advise me.
This is my output.php
$res1=$con->selectnonschoolround1($From,$To);
while($row=pg_fetch_array($res1))
{
$r1=$row['non_slsc_qty'];
$r2=$row['non_slst_qty'];
$r3=$row['non_slot_qty'];
$r4=$row['non_slsc_ben'];
$r5=$row['non_slst_ben'];
$r6=$row['non_slot_ben'];
$Total_qty_non_r1=$row['total_qty'];
$Total_ben_non_r1=$row['total_ben'];
}
This is the class.php
class DB_con
{
function __construct()
{
$db = pg_connect("host=localhost port=5432
dbname=mydb user=postgres password=123");
}
public function selectnonschoolround1($From,$To)
{
$res1=pg_query("SELECT
SUM(non_slsc_qty) as non_slsc_qty,
SUM(non_slst_qty) as non_slst_qty,
SUM(non_slot_qty) as non_slot_qty,
SUM(non_slsc_ben) as non_slsc_ben,
SUM(non_slst_ben) as non_slst_ben,
SUM(non_slot_ben) as non_slot_ben,
SUM(non_slsc_qty+non_slst_qty+non_slot_qty) AS total_qty,
SUM(non_slsc_ben+non_slst_ben+non_slot_ben) AS total_ben
FROM table where date BETWEEN '$From' AND '$To'");
return $res1;
}
}
Pass function parameter as an array and then you need to check if parameter is array or not using PHP function is_array(). If its an array then loop through that array and execute the query with "from" and "to" indexes but, in this case you need to return an array from the executed query. If its not an array the keep the code as it is in your else part. In this you can use the same function for multiple value or for single values. Just keep in mind that the params should be proper. Hope this will help you out :)
Try this code and make the changes as per your need :).
class DB_con
{
function __construct()
{
//code
}
public function selectNonSchoolRound1($arr, $from = '', $to = '')
{
if (is_array($arr)) {
$returnArr = array();
foreach ($arr as $ars) {
$res1 = pg_query("your query using ".$ars['from'].$ars['to']);
array_push($returnArr, $res1);
}
return $returnArr;
} else {
$res1 = pg_query("your query using ".$from.$to.'variabls');
return $res1;
}
}
}
try {
$arr = array('0' =>
array('from' => '2015-08-01', 'to' => '2015-08-31'),
'1' => array('from' => '2015-08-01', 'to' => '2015-08-31')
);
$obj = new DB_con();
$result = $obj->selectNonSchoolRound1($arr);
// loop here with the $result variable
} catch (Exception $ex) {
echo $ex->getMessage();
}

How can I pass a function as an optional variable to call_user_func in PHP

So I'd like to use the call_user_func to pass data to an optional parameter of a function.
Here's the example of a code, the optional parameter $data represents a functional called data that was declared in another file. I just want it to be called by using call_user_func that will set the parameter with the function's name and call it within the createtable function, but doesn't seem to work.
I got the example from the PHP Manual, but createTable contains many parameters. How can I make call_user_func only assign the string data to the optional parameter $data set to NULL as default?
function createTable($database, $table, $patch,$data = NULL)
{
echo "INFO: Adding '$table'in database '$database'.\n";
$sql = "SHOW TABLES FROM $database WHERE Tables_in_$database='$table';";
$result = mysql_query($sql);
$result_count = mysql_num_rows($result);
if ( $result_count != 1 ) {
echo "ERROR: Can not find table '$table' in database '$database'.\n";
$result = mysql_query($patch);
if ( false === $result ) {
echo "ERROR: Adding Table '$table' in database '$database' ... Failed\n";
return false;
}
else {
echo "INFO: Adding Table '$table'in database '$database' ... Success\n";
// using the optional parameter here
$data();
return true;
}
} else {
if ( $result_count == 1 ) {
echo "ERROR: Table '$table'already in database '$database'.\n";
return false;
}
}
}
// Now I'm passing value to the optional parameter $ data that is NULL as default.
call_user_func('createTable', "data");
Even with call_user_func you have to pass all the parameters.
Anyway, call_user_func is intended for use when the name of the function isn't necessarily known up front. For instance, you might have several functions and a variable, and the variable contains the name of the function to call.
Personally I think it's on par with eval and variable variables: A horrible idea. After all, if you have $foo = "function_name"; then you can call $foo() and it will call function_name.
Anyway, back to the point, just call it as a normal function and give it the parameters it needs. Pass null if you have to.
you must pass value like this
call_user_func('createTable', $database, $table, $patch,$data);
or this for call from class
call_user_func(array(&$objectName->{$anotherObject},$functionName), $arg1, $arg2, $arg2);
or you can use this can get arg as array
call_user_func_array("createTable", array("one", "two"));
or this for call from class can get arg as array
call_user_func_array(array($foo, "bar"), array("three", "four"));
or This can help you too it not need to pass all args
function __named($method, array $args = array())
{
$reflection = new ReflectionFunction( $method);
$pass = array();
foreach($reflection->getParameters() as $param)
{
/* #var $param ReflectionParameter */
if(isset($args[$param->getName()]))
{
$pass[] = $args[$param->getName()];
}
else
{
try{
$pass[] = $param->getDefaultValue();
}catch(Exception $e){
$pass[] = NULL;
}
}
}
return $reflection->invokeArgs( $pass);
}
I hope It Work
sample:
__named('createTable', array('data' => 'value'));
and it is for use in class
public function __named($method, array $args = array())
{
$reflection = new ReflectionMethod($this, $method);
$pass = array();
foreach($reflection->getParameters() as $param)
{
/* #var $param ReflectionParameter */
if(isset($args[$param->getName()]))
{
$pass[] = $args[$param->getName()];
}
else
{
try{
$pass[] = $param->getDefaultValue();
}catch(Exception $e){
$pass[] = NULL;
}
}
}
return $reflection->invokeArgs($this,$pass);
}
if you Don't set any value __named Put Null instead of Unset Value
It seems you just want to pass the last param, and not worry about the 1st three. I don't think call_user_func is the right tool here at all.
Why not just make a function that calls your function?
function call_createTable($data){
$database = '...';
$table = '...';
$patch = '...';
return createTable($database, $table, $patch, $data);
}
Then just simply call it like this: call_createTable("data");.

Categories