Related
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);
Using the ONGR/ElasticsearchDSL I'm trying to add a Parent child inner hit query. The example documentation indicates that the proper way to do this is to
{
"inner_hits" : {
"children" : {
"type" : {
"article" : {
"query" : {
"match" : {"title" : "[actual query]"}
}
}
}
}
}
}
And now the query via DSL:
$matchQuery = new MatchQuery('title', '[actual query]');
$innerHit = new ParentInnerHit('children', 'article', $matchQuery);
$search = new Search();
$search->addInnerHit($innerHit);
$search->toArray();
So for my scenario I did:
$termQuery = new TermQuery('user', $query);
$innerHit = new ParentInnerHit('child_type', 'parent_type', $termQuery);
$search->addInnerHit($innerHit);
My problem is that I'm getting the error message:
Catchable fatal error: Argument 3 passed to
ONGR\ElasticsearchDSL\InerHit\NestedInnerHit::__construct()
must be an instance of ONGR\ElasticsearchDSL\Search,
instance of ONGR\ElasticsearchDSL\Query\TermLevel\TermQuery
give defined in ../ongr/elasticsearch-dsl/src/InnerHit/NestedInnerHit.php
on line 46
Any thoughts or suggestions?
As you can see from exception ParentInnerHit is expecting Search instead of Query, which makes sense. To build desired query you have to:
$termQuery = new TermQuery('user', $query);
$searchObject = new Search();
$search->addQuery($termQuery);
$innerHit = new ParentInnerHit('child_type', 'parent_type', $searchObject);
$search->addInnerHit($innerHit);
Did not test this, but you should get the idea.
I have worked a lot on codeigniter. In codeigniter , if there is need to get query string that is executed last, we can get it using:
echo $this->db->last_query();
exit;
But currently I am working on phalcon and I am just at beginner level in this framework. I am curious if there is a way to echo last query string in phalcon.
Thank you.
Using Raw Queries
Let us have the following query:
$phql = 'UPDATE `news` SET `category_id` = 5 WHERE `id` = :id';
$this->db->execute($phql, ['id' => 1]);
We can get debug query info with the following methods:
print_r($this->db->getSQLStatement());
UPDATE news SET category_id = 5 WHERE id = :id
print_r($this->db->getSqlVariables());
Array (
[id] => 1 )
More info about DB methods you can find here: https://docs.phalconphp.com/en/latest/api/Phalcon_Db_Adapter_Pdo.html
Working with Models
Setting up your DB connection and profiler service:
use Phalcon\Db\Profiler as ProfilerDb;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Db\Adapter\Pdo\Mysql as MysqlPdo;
$di->set('profiler', function () {
return new ProfilerDb();
}, true);
$di->set('db', function () use ($di) {
$eventsManager = new EventsManager();
// Get a shared instance of the DbProfiler
$profiler = $di->getProfiler();
// Listen all the database events
$eventsManager->attach('db', function ($event, $connection) use ($profiler) {
if ($event->getType() == 'beforeQuery') {
$profiler->startProfile($connection->getSQLStatement());
}
if ($event->getType() == 'afterQuery') {
$profiler->stopProfile();
}
});
$connection = new MysqlPdo(
array(
"host" => "localhost",
"username" => "root",
"password" => "secret",
"dbname" => "invo"
)
);
// Assign the eventsManager to the db adapter instance
$connection->setEventsManager($eventsManager);
return $connection;
});
Using it to debug your Queries:
// Send some SQL statements to the database
Robots::find();
Robots::find(
array(
"order" => "name"
)
);
Robots::find(
array(
"limit" => 30
)
);
// Get the generated profiles from the profiler
$profiles = $di->get('profiler')->getProfiles();
foreach ($profiles as $profile) {
echo "SQL Statement: ", $profile->getSQLStatement(), "\n";
echo "Start Time: ", $profile->getInitialTime(), "\n";
echo "Final Time: ", $profile->getFinalTime(), "\n";
echo "Total Elapsed Time: ", $profile->getTotalElapsedSeconds(), "\n";
}
More info on Profiler service: https://docs.phalconphp.com/en/latest/reference/models.html#profiling-sql-statements
Phalcon Prophiler Widget
I'm using a lovely debug widget for Phalcon made by Fabian Fülling. You can check the repository here: https://github.com/fabfuel/prophiler A sample screen shot of the widget in action below:
If you are running queries directly on your model instance and you are lazy, you can also do it like this:
$result = $this->_userEntriesEntries->find(array("conditions" => "FeaturedPost = 1 and FeaturedPostStatus = 1", "order" => "ID DESC", "limit" => 4))
var_dump($result);
var_dump the result object of your query. Within the PDO dump you will notice a key named _pdoStatement. This is your generated SQL query.
This is not the recommended way, just a dirty trick.
Hi I'm new with PHP usually I work with Java, how actually the right way to write an array of many arguments/parameters in this insertSQL function as I have a lot SQL objects have to be inserted. Thank you
//Store User into MySQL DB
$res = $db->insertSQL(
$data[$i]->id,
$data[$i]->location_id,
$data[$i]->section_id,
$data[$i]->inspection_date,
$data[$i]->photo_entire_path,
$data[$i]->photo_isolator_path,
$data[$i]->pole_no,
$data[$i]->pole_iron,
$data[$i]->pole_iron,
$data[$i]->pole_iron);
//Based on inserttion, create JSON response
if($res){
$b["id"] = $data[$i]->id;
$b["status"] = 'yes';
array_push($a,$b);
}else{
$b["id"] = $data[$i]->id;
$b["status"] = 'no';
array_push($a,$b);
}
Right now it looks like this
$res = $db->insertSQL(
$data[$i]->id,
$data[$i]->location_id,
$data[$i]->section_id,
$data[$i]->inspection_date,
$data[$i]->photo_entire_path,
$data[$i]->photo_isolator_path,
$data[$i]->pole_no,
$data[$i]->pole_iron,
$data[$i]->pole_concrete,
$data[$i]->pole_wood,
$data[$i]->pole_condition_broken,
$data[$i]->pole_condition_tilt,
$data[$i]->pole_condition_shift,
$data[$i]->cros_arm_twist,
$data[$i]->cross_arm_rust,
$data[$i]->cross_arm_tilt,
$data[$i]->arm_tie_repair,
$data[$i]->arm_tie_rust,
$data[$i]->arm_tie_brace,
$data[$i]->isolator_fulcrum_r_leak,
$data[$i]->isolator_fulcrum_r_broken,
$data[$i]->isolator_fulcrum_s_leak,
$data[$i]->isolator_fulcrum_s_broken,
$data[$i]->isolator_fulcrum_t_leak,
$data[$i]->isolator_fulcrum_t_broken,
$data[$i]->isolator_pull_r_leak,
$data[$i]->isolator_pull_r_broken,
$data[$i]->isolator_pull_s_leak,
$data[$i]->isolator_pull_s_broken,
$data[$i]->isolator_pull_t_leak,
$data[$i]->isolator_pull_t_broken,
$data[$i]->arrester_r_broken,
$data[$i]->arrester_s_broken,
$data[$i]->arrester_t_broken,
$data[$i]->conductor_r_buyer,
$data[$i]->conductor_r_loose,
$data[$i]->conductor_s_buyer,
$data[$i]->conductor_s_loose,
$data[$i]->conductor_t_buyer,
$data[$i]->conductor_t_loose,
$data[$i]->connector_pg_r_35mm,
$data[$i]->connector_pg_r_70mm,
$data[$i]->connector_pg_r_150mm,
$data[$i]->connector_pg_s_35mm,
$data[$i]->connector_pg_s_70mm,
$data[$i]->connector_pg_s_150mm,
$data[$i]->connector_pg_t_35mm,
$data[$i]->connector_pg_t_70mm,
$data[$i]->connector_pg_t_150mm,
$data[$i]->bending_wire_r,
$data[$i]->bending_wire_s,
$data[$i]->bending_wire_t,
$data[$i]->ultrasonic_r,
$data[$i]->ultrasonic_s,
$data[$i]->ultrasonic_t,
$data[$i]->gws_exist,
$data[$i]->gws_not_exist,
$data[$i]->tree_exist,
$data[$i]->tree_not_exist,
$data[$i]->longitude,
$data[$i]->latitude,
$data[$i]->suggestion,
$data[$i]->descr
);
If I understand you correctly, this is what your function should look like:
function insertSQL(Array $sqlData)
{
Extract the values from the $sqlData variable here.
}
Try the following solution using call_user_func_array, func_get_args, json_encode and json_decode functions (to deal with an array of arguments):
...
$encoded = json_encode($data[$i]);
$fields_arr = json_decode($encoded, true); // to get an array of object properties with values.
// Also you should, probably, check the order of fields
$fields_arr['id'] = false;
$fields_arr = array_filter($fields_arr); // for removing the 'id' field
$args = ['id' => $data[$i]->id]; // first argument
call_user_func_array(array($db, 'insetSQL'), array_merge($args, $fields_arr)); // it also may require your current Namespace in the first arg
...
// Then, the 'insetSQL' method should process the arguments in the following manner:
function insetSQL($fields = []) {
$fields = func_get_args();
$id = $fields[0];
// adjusting the rest of fields ($fields[1], $fields[2] ...)
...
}
Although, I also would suggest to pass the initial object $data[$i] right into the insetSQL method as parameter and get the needed fields for sql INSERT statement
Create a JSON object as
$named_array = array(
"longitude" => "12.2"
"latitude" => "12.2"
);
$named_array = json_encode($named_array);
This $named_array can be array of fields.
You can pass $named_array object to other function as an argument.
Then use
$named_array = json_decode($named_array)
echo $named_array->longitude
You can access any Key Value pair as $named_array->latitude
I get a strange error using json_decode(). It decode correctly the data (I saw it using print_r), but when I try to access to info inside the array I get:
Fatal error: Cannot use object of type stdClass as array in
C:\Users\Dail\software\abs.php on line 108
I only tried to do: $result['context'] where $result has the data returned by json_decode()
How can I read values inside this array?
Use the second parameter of json_decode to make it return an array:
$result = json_decode($data, true);
The function json_decode() returns an object by default.
You can access the data like this:
var_dump($result->context);
If you have identifiers like from-date (the hyphen would cause a PHP error when using the above method) you have to write:
var_dump($result->{'from-date'});
If you want an array you can do something like this:
$result = json_decode($json, true);
Or cast the object to an array:
$result = (array) json_decode($json);
You must access it using -> since its an object.
Change your code from:
$result['context'];
To:
$result->context;
Use true as the second parameter to json_decode. This will decode the json into an associative array instead of stdObject instances:
$my_array = json_decode($my_json, true);
See the documentation for more details.
Have same problem today, solved like this:
If you call json_decode($somestring) you will get an Object and you need to access like $object->key , but if u call json_decode($somestring, true) you will get an dictionary and can access like $array['key']
It's not an array, it's an object of type stdClass.
You can access it like this:
echo $oResult->context;
More info here: What is stdClass in PHP?
As the Php Manual say,
print_r — Prints human-readable information about a variable
When we use json_decode();, we get an object of type stdClass as return type.
The arguments, which are to be passed inside of print_r() should either be an array or a string. Hence, we cannot pass an object inside of print_r(). I found 2 ways to deal with this.
Cast the object to array.
This can be achieved as follows.
$a = (array)$object;
By accessing the key of the Object
As mentioned earlier, when you use json_decode(); function, it returns an Object of stdClass. you can access the elements of the object with the help of -> Operator.
$value = $object->key;
One, can also use multiple keys to extract the sub elements incase if the object has nested arrays.
$value = $object->key1->key2->key3...;
Their are other options to print_r() as well, like var_dump(); and var_export();
P.S : Also, If you set the second parameter of the json_decode(); to true, it will automatically convert the object to an array();
Here are some references:
http://php.net/manual/en/function.print-r.php
http://php.net/manual/en/function.var-dump.php
http://php.net/manual/en/function.var-export.php
Try something like this one!
Instead of getting the context like:(this works for getting array index's)
$result['context']
try (this work for getting objects)
$result->context
Other Example is: (if $result has multiple data values)
Array
(
[0] => stdClass Object
(
[id] => 15
[name] => 1 Pc Meal
[context] => 5
[restaurant_id] => 2
[items] =>
[details] => 1 Thigh (or 2 Drums) along with Taters
[nutrition_fact] => {"":""}
[servings] => menu
[availability] => 1
[has_discount] => {"menu":0}
[price] => {"menu":"8.03"}
[discounted_price] => {"menu":""}
[thumbnail] => YPenWSkFZm2BrJT4637o.jpg
[slug] => 1-pc-meal
[created_at] => 1612290600
[updated_at] => 1612463400
)
)
Then try this:
foreach($result as $results)
{
$results->context;
}
To get an array as result from a json string you should set second param as boolean true.
$result = json_decode($json_string, true);
$context = $result['context'];
Otherwise $result will be an std object. but you can access values as object.
$result = json_decode($json_string);
$context = $result->context;
Sometimes when working with API you simply want to keep an object an object. To access the object that has nested objects you could do the following:
We will assume when you print_r the object you might see this:
print_r($response);
stdClass object
(
[status] => success
[message] => Some message from the data
[0] => stdClass object
(
[first] => Robert
[last] => Saylor
[title] => Symfony Developer
)
[1] => stdClass object
(
[country] => USA
)
)
To access the first part of the object:
print $response->{'status'};
And that would output "success"
Now let's key the other parts:
$first = $response->{0}->{'first'};
print "First name: {$first}<br>";
The expected output would be "Robert" with a line break.
You can also re-assign part of the object to another object.
$contact = $response->{0};
print "First Name: " . $contact->{'first'} . "<br>";
The expected output would be "Robert" with a line break.
To access the next key "1" the process is the same.
print "Country: " . $response->{1}->{'country'} . "<br>";
The expected output would be "USA"
Hopefully this will help you understand objects and why we want to keep an object an object. You should not need to convert an object to an array to access its properties.
You can convert stdClass object to array like:
$array = (array)$stdClass;
stdClsss to array
When you try to access it as $result['context'], you treating it as an array, the error it's telling you that you are actually dealing with an object, then you should access it as $result->context
Here is the function signature:
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
When param is false, which is default, it will return an appropriate php type. You fetch the value of that type using object.method paradigm.
When param is true, it will return associative arrays.
It will return NULL on error.
If you want to fetch value through array, set assoc to true.
I got this error out of the blue because my facebook login suddently stopped working (I had also changed hosts) and throwed this error. The fix is really easy
The issue was in this code
$response = (new FacebookRequest(
FacebookSession::newAppSession($this->appId, $this->appSecret),
'GET',
'/oauth/access_token',
$params
))->execute()->getResponse(true);
if (isset($response['access_token'])) { <---- this line gave error
return new FacebookSession($response['access_token']);
}
Basically isset() function expect an array but instead it find an object. The simple solution is to convert PHP object to array using (array) quantifier. The following is the fixed code.
$response = (array) (new FacebookRequest(
FacebookSession::newAppSession($this->appId, $this->appSecret),
'GET',
'/oauth/access_token',
$params
))->execute()->getResponse(true);
Note the use off array() quantifier in first line.
instead of using the brackets use the object operator for example my array based on database object is created like this in a class called DB:
class DB {
private static $_instance = null;
private $_pdo,
$_query,
$_error = false,
$_results,
$_count = 0;
private function __construct() {
try{
$this->_pdo = new PDO('mysql:host=' . Config::get('mysql/host') .';dbname=' . Config::get('mysql/db') , Config::get('mysql/username') ,Config::get('mysql/password') );
} catch(PDOException $e) {
$this->_error = true;
$newsMessage = 'Sorry. Database is off line';
$pagetitle = 'Teknikal Tim - Database Error';
$pagedescription = 'Teknikal Tim Database Error page';
include_once 'dbdown.html.php';
exit;
}
$headerinc = 'header.html.php';
}
public static function getInstance() {
if(!isset(self::$_instance)) {
self::$_instance = new DB();
}
return self::$_instance;
}
public function query($sql, $params = array()) {
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)) {
$x = 1;
if(count($params)) {
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}
}
if($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
}
else{
$this->_error = true;
}
return $this;
}
public function action($action, $table, $where = array()) {
if(count($where) ===3) {
$operators = array('=', '>', '<', '>=', '<=');
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators)) {
$sql = "{$action} FROM {$table} WHERE {$field} = ?";
if(!$this->query($sql, array($value))->error()) {
return $this;
}
}
}
return false;
}
public function get($table, $where) {
return $this->action('SELECT *', $table, $where);
public function results() {
return $this->_results;
}
public function first() {
return $this->_results[0];
}
public function count() {
return $this->_count;
}
}
to access the information I use this code on the controller script:
<?php
$pagetitle = 'Teknikal Tim - Service Call Reservation';
$pagedescription = 'Teknikal Tim Sevice Call Reservation Page';
require_once $_SERVER['DOCUMENT_ROOT'] .'/core/init.php';
$newsMessage = 'temp message';
$servicecallsdb = DB::getInstance()->get('tt_service_calls', array('UserID',
'=','$_SESSION['UserID']));
if(!$servicecallsdb) {
// $servicecalls[] = array('ID'=>'','ServiceCallDescription'=>'No Service Calls');
} else {
$servicecalls = $servicecallsdb->results();
}
include 'servicecalls.html.php';
?>
then to display the information I check to see if servicecalls has been set and has a count greater than 0 remember it's not an array I am referencing so I access the records with the object operator "->" like this:
<?php include $_SERVER['DOCUMENT_ROOT'] .'/includes/header.html.php';?>
<!--Main content-->
<div id="mainholder"> <!-- div so that page footer can have a minum height from the
header -->
<h1><?php if(isset($pagetitle)) htmlout($pagetitle);?></h1>
<br>
<br>
<article>
<h2></h2>
</article>
<?php
if (isset($servicecalls)) {
if (count ($servicecalls) > 0){
foreach ($servicecalls as $servicecall) {
echo '<a href="/servicecalls/?servicecall=' .$servicecall->ID .'">'
.$servicecall->ServiceCallDescription .'</a>';
}
}else echo 'No service Calls';
}
?>
Raise New Service Call
</div> <!-- Main content end-->
<?php include $_SERVER['DOCUMENT_ROOT'] .'/includes/footer.html.php'; ?>
It is most likely when it tries to access the data with the generic bracket array accessor and not an object operator. Always ensure the variable type is before accessing the data.
While decoding the JSON, the response will be generated as stdObject instances
Rather than calling $result['context'];, access it by $result->context;
If it needs to call as an array itself, decode the JSON by passing the second parameter as true like
json_decode($jsonData, true);
Change it for
$results->fetch_array()