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);
Related
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
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);
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();
}
I have a dbfunctions class that has the functions to retrieve and write data to database. However, the retrieval doesn't work and I can't understand why it doesn't work.
The read functions looks like this:
public function haeParametreittaTietokannasta($f_sql) {
try {
$this->sql_lause = $this->db->prepare($f_sql);
$this->haku = $this->sql_lause->execute();
} catch (PDOException $ex) {
die("Tapahtui virhe tietoja noudettaessa : " . $ex->getMessage());
}
if(!$this->haku) {
$this->tulos = $this->haku->fetchAll();
return $this->tulos;
} else {
return false;
}
} // END FUNCTION
And this is how I call the function:
$countries = $dabase->haeParametreittaTietokannasta("SELECT * FROM countries");
The query always returns false, and I've tried showing error info and it says: array ( 0 => '00000', 1 => NULL, 2 => NULL, ) (And yes, I have created a new object in the main code.)
I've just started to learn PHP and there might be a simple error I just can't see...
You have the wrong if condition:
if(!$this->haku) {
should be
if($this->haku) {
$this->tulos = $this->sql_lause->fetchAll();
PDOStatement::execute() returns a boolean value. You can't use it for fetchAll().
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");.