Hi I'm trying to implement the method fetchAll like the Album example but It doesn't work.
When I try to print the result with a var_dump I get this
object(Zend\Db\ResultSet\ResultSet)#258 (8) {
["allowedReturnTypes":protected]=>
array(2) {
[0]=>
string(11) "arrayobject"
[1]=>
string(5) "array"
}
["arrayObjectPrototype":protected]=>
object(Application\Model\Ubigeo)#242 (5) {
["codDpto"]=>
NULL
["codProv"]=>
NULL
["codDist"]=>
NULL
["name"]=>
NULL
["idUbigeo"]=>
NULL
}
["returnType":protected]=>
string(11) "arrayobject"
["buffer":protected]=>
NULL
["count":protected]=>
int(2057)
["dataSource":protected]=>
object(Zend\Db\Adapter\Driver\Pdo\Result)#257 (8) {
["statementMode":protected]=>
string(7) "forward"
["resource":protected]=>
object(PDOStatement)#248 (1) {
["queryString"]=>
string(52) "SELECT `ubigeo`.* FROM `ubigeo` ORDER BY `name` DESC"
}
["options":protected]=>
NULL
["currentComplete":protected]=>
bool(false)
["currentData":protected]=>
NULL
["position":protected]=>
int(-1)
["generatedValue":protected]=>
string(1) "0"
["rowCount":protected]=>
int(2057)
}
["fieldCount":protected]=>
int(5)
["position":protected]=>
int(0)
}
This is my serviceConfig:
public function getServiceConfig() {
return array(
'factories' => array(
'Application\Model\UbigeoTable' => function ($sm) {
$tableGateway = $sm->get('UbigeoTableGateway');
$table = new UbigeoTable($tableGateway);
return $table;
},
'UbigeoTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Ubigeo());
return new TableGateway('ubigeo', $dbAdapter, null, $resultSetPrototype);
}
),
);
}
Any help would be appreciate
According to var_dump your table contains these rows : codDpto, codProv, codDist, name and idUbigeo.
You can access the results this way :
foreach($resultSet as $row)
{
$result = '<p>codDpto: '.$row['codDpto'];
$result .= ', codProv: '.$row['codProv'];
$result .= ', codDist: '.$row['codDist'];
$result .= ', name: '.$row['name'];
$result .= ', idUbigeo: '.$row['idUbigeo'].'</p>';
echo $result;
}
Related
I've upgraded an app from PHP74 to 81 and doctrine/mongodb-odm 1.x to 2.x.
A call to this method
private function getLoginsForPipeline(array $pipeline)
{
$collection = $dm->getDocumentCollection(LoginTrackerModel::class)->getMongoCollection();
return $collection->aggregateCursor($pipeline, ["allowDiskUse" => true]);
}
where $pipeline is defined as:-
$pipeline = [
[0] =>
array(1) {
'$sort' =>
array(1) {
'date' =>
int(-1)
}
}
[1] =>
array(1) {
'$group' =>
array(2) {
'_id' =>
string(5) "$user"
'lastLoginDate' =>
array(1) {
...
}
}
}
[2] =>
array(1) {
'$match' =>
array(1) {
'lastLoginDate' =>
array(1) {
...
}
}
}
];
returns:-
Error: Call to undefined method MongoDB\Collection::getMongoCollection()
So, looks like getMongoCollection() has been deprecated in doctrine/mongodb-odm 2.x
I have a hunch we can replace
$collection = $dm->getDocumentCollection(LoginTrackerModel::class)->getMongoCollection();
with:-
$builder = $dm->createAggregationBuilder(LoginTrackerModel::class); in 2.x
does anyone know how/what we'd replace
$collection->aggregateCursor($pipeline, ["allowDiskUse" => true]);
with in 2.x?
Am I on the right track with something along the lines of:-
$builder
->match()
->field('lastLoginDate')
->group()
->sort('date');
$result = $builder->getAggregation();
I'm not 100% since getAggregation() != aggregateCursor()
I have this function that handle the Fb Callback.
public function handleFbCallback() {
if( !\Input::get('error', NULL) ) {
try {
$fuser = \Socialize::with('facebook')->user();
$token = $fuser->token;
if($fb = \App\UserFacebook::whereEmail($fuser->getEmail())->first()) {
$fb->fb_id = $fuser->getId();
$fb->nickname = $fuser->getNickname();
$fb->name = $fuser->getName();
$fb->avatar = $fuser->getAvatar();
$fb->token = $token;
$fb->save();
$profile = \App\Profile::whereUserId($fb->user_id)->first();
if($profile) {
$profile->name = $fuser->user['first_name'];
$profile->last_name = $fuser->user['last_name'];
$profile->save();
} else {
\App\Profile::create([
'name' => $fuser->user['first_name'],
'last_name' => $fuser->user['last_name'],
'user_id' => $fb->user_id,
]);
}
//load user and increments number login
$user = \App\User::find($fb->user_id);
if($user) {
$user->last_login = date('Y-m-d H:i:s');
$user->number_logins = $user->number_logins + 1;
$user->save();
}
}
else {
$password = str_random(8);
$nuser = \App\User::whereEmail($fuser->getEmail())->first();
if(!$nuser) {
$nuser = \App\User::create([
'email' => $fuser->getEmail(),
'password' => bcrypt($password),
'active' => 1,
]);
if(\Session::get('source', NULL)) {
$nuser->source = \Session::get('source');
\Session::forget('source');
}
if(\Session::get('campaign', NULL)) {
$nuser->source = \Session::get('campaign');
\Session::forget('campaign');
}
$nuser->save();
//profile
\App\Profile::create([
'name' => $fuser->user['first_name'],
'last_name' => $fuser->user['last_name'],
'user_id' => $nuser->id,
]);
}
$nuser->last_login = date('Y-m-d H:i:s');
$nuser->number_logins = 1;
$nuser->save();
$fb = \App\UserFacebook::create([
'fb_id' => $fuser->getId(),
'nickname' => $fuser->getNickname(),
'name' => $fuser->getName(),
'email' => $fuser->getEmail(),
'avatar' => $fuser->getAvatar(),
'token' => $token,
'user_id' => $nuser->id
]);
}
\Auth::loginUsingId($fb->user_id);
if(\Session::get('custom_url', NULL) == 'thanks') {
return redirect()->route('landing.thanks', array('social', $fb->user_id));
} elseif($url = \Session::get('custom_url', NULL)) {
\Session::forget('custom_url');
return redirect($url);
}
return redirect()->intended();
}
catch(Exception $e) {
dd($e->getMessage());
}
}
return redirect('/');
}
Running this function it make an exception:
Client error: GET https://graph.facebook.com/v2.6/me?access_token=&appsecret_proof=cb32db5fac27b922d1a9c3040772a05b9a6e79f8145ee5a9fc21bbefd1f00909&fields=name,first_name,last_name,email,gender,verified resulted in a 400 Bad Request response: {"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthExce (truncated...)
But it make an exception about the token.
Someone have any idea to solve that?
Thank you!
This my code in codeigniter but it doesn't update in database, I'm beginner ni codeigniter, how could I fix this error, or what is wrong in my code?
THis is my Controller:
function edit() {
$role = $this->session->userdata('role');
$this->form_validation->set_rules('firstname', 'firstname', 'required|xss_clean');
$this->form_validation->set_rules('lastname', 'lastname', 'required|xss_clean');
if ($this->form_validation->run() == FALSE) {
//set page data
$data['title'] = 'Update Profile';
if($role!=''){
$data['admin'] = $this->M_user->get($this->session->userdata('user_id'));
}else{
$data['admin'] = $this->M_administrator->getAdmin($this->session->userdata('id_admin'));
}
$data['sitename'] = $this->M_website->getName();
$data['content'] = 'admin/myaccount/edit';
//parse template
$this->parser->parse('admin/template', $data);
} else {
if($role!=''){
if ($this->M_user->updateStatus($_POST['user_id'])) {
//SAVE ADMIN ACTION LOG
//save_admin_action(array('module' => Constant::AM_ACCOUNT, 'action' => Constant::AL_EDIT, 'title' => $this->form_validation['username'], 'object_id' => $id));
//redirect page
$this->session->set_flashdata('saved', TRUE);
redirect('admin/myaccount');
}
}else{
if ($this->M_administrator->updateStatus($_POST['id_admin'])) {
//SAVE ADMIN ACTION LOG
//save_admin_action(array('module' => Constant::AM_ACCOUNT, 'action' => Constant::AL_EDIT, 'title' => $this->form_validation['username'], 'object_id' => $id));
//redirect page
$this->session->set_flashdata('saved', TRUE);
redirect('admin/myaccount');
}
}
}
}
This is my model administrator:
function updateStatus($post, $id){
$data = array(
'firstname' => $post['firstname'],
'lastname' => $post['lastname']
);
$this->db->where('id_admin', $id);
if($this->db->update('admin', $data)){
return TRUE;
}else{
return FALSE;
}
}
user Model:
function updateStatus($post, $id){
$data = array(
'firstname' => $post['firstname'],
'lastname' => $post['lastname']
);
$this->db->where('user_id', $id);
if($this->db->update('user', $data)){
return TRUE;
}else{
return FALSE;
}
}
pass firstname and last name to your updatestatus model function if you are not getting that value in model so you are not able to change
print your query using $this->db->last_query(); to get query output and post your query here
Change your where clause to
$this->db->where('id_admin', $post);
I using Phalcon Framework and PostgreSQL
I try to insert an array to database column type: varchar[]:
array(4) { [0]=> string(1) "1" [1]=> string(1) "6" [2]=> string(1) "9" [3]=> string(2) "12" }
But getting following error :
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
Please help me to fix this please
Here is my Model:
<?php
namespace App\Models;
use Phalcon\Mvc\Model;
use Phalcon\Validation;
use Phalcon\Validation\Validator\Uniqueness;
class Document extends Model
{
public $id;
public $relatedocument;
public function getSource()
{
return "document";
}
=====Form======
<?php
namespace App\Modules\Backend\Forms;
use Idoc\Models\Document;
use Phalcon\Forms\Form;
use Phalcon\Forms\Element\Select;
class DocumentForm extends Form
{
public function initialize($entity = null, $options = null)
{
$data = Document::find();
$this->add(new Select('relatedocument[]', $data, [
'using' => [
'id',
'name'
],
'useEmpty' => true,
'emptyText' => '....',
'multiple' => 'multiple',
'class' => 'form-control search-select'
]));
}
=====addAction======
public function addAction()
{
if ($this->request->isPost()) {
$doc = new Document();
$doc->relatedocument = $this->request->getPost('relatedocument');
if (!$doc->save()) {
$this->flash->error($doc->getMessages());
} else {
$this->flash->success("Văn bản đã được tạo");
Tag::resetInput();
}
}
$this->view->form = new DocumentForm(null);
}
folks. The uniqueness validator in my form works as expected on adding new records, but on updating an exsisting record, it throws an error that the url already exists. It exists, in fact, but only in the current record.
Here is my controller:
$feed = Feeds::findFirst($id);
$feedForm = new FeedForm($feed, array('edit' => true));
if ($this->request->isPost() == true) {
$feedData = $this->request->getPost();
if ($feedForm->isValid($feedData, $feed)) {
if ($feed->save()) {
$this->flash->success("Feed successfuly updated.");
} else {
$this->flash->error("Update failed.");
}
} else {
foreach ($feedForm->getMessages() as $message) {
$this->flash->error($message);
}
}
}
And my form class:
class FeedForm extends FormBase {
public $options;
public function initialize($entity = null, $options = null) {
parent::initialize();
$this->setEntity($entity);
$this->options = $options;
$status = new Radio('status');
$status->addValidator(
new PresenceOf(
array(
'message' => 'The status is required.'
)
));
$this->add($status);
$name = new Text('name');
$name->addValidator(
new PresenceOf(
array(
'message' => 'The name is required.'
)
));
$name->addValidator(
new StringLength(
array(
'max' => 50,
'messageMaximum' => 'The name you entered is too long.'
)
));
$this->add($name);
$xml = new Text('xml');
$xml->addValidator(
new PresenceOf(
array(
'message' => 'The URL address is required.'
)
));
$xml->addValidator(
new StringLength(
array(
'max' => 2048,
'messageMaximum' => 'The URL address you entered is too long.'
)
));
$xml->addValidator(
new Url(
array(
'message' => 'The URL you entered is invalid.'
)
));
$xml->addValidator(
new Uniqueness(
array(
'model' => 'Sravnisite\Admin\Models\Feeds',
'table' => 'feeds',
'column' => 'xml',
'message' => 'The entered URL address already exists.'
)
));
$periodOptions = array();
for ($i = 4; $i <= 24; $i++) {
array_push($periodOptions, $i);
}
$this->add($xml);
$period = new Select('period', $periodOptions);
$period->addValidator(
new PresenceOf(
array(
'message' => 'The period is required.'
)
));
$this->add($period);
$shopID = new Select('shop_id', Shops::find(), array('using' => array('id', 'name')));
$shopID->addValidator(
new PresenceOf(
array(
'message' => 'The shop is required.'
)
));
$this->add($shopID);
}
}
Any ideas?
The form validation doesn't know to ignore the record you are updating - so for uniqueness it finds the record you're trying to update and gives an error. You could do some complicated find logic to keep the uniqueness validation in the form but it is better moved to the model. Your result would end up something like:
Controller
$feed = Feeds::findFirst($id);
$feedForm = new FeedForm($feed, array('edit' => true));
if ($this->request->isPost() == true) {
$feedData = $this->request->getPost();
if ($feedForm->isValid($feedData, $feed)) {
if ($feed->save()) {
$this->flash->success("Feed successfuly updated.");
} else {
$this->flash->error("Update failed.");
// Get each of the validation messages from the model
foreach ($feed->getMessages() as $message) {
$this->flash->error($message);
}
}
} else {
foreach ($feedForm->getMessages() as $message) {
$this->flash->error($message);
}
}
}
Form
// Exactly the same as you currently have but without the Uniqueness Validator
Model
class Feeds extends Phalcon\Mvc\Model
/**
* Validate that xml URLs are unique
*/
public function validation()
{
$this->validate(new Uniqueness(array(
"field" => "xml",
"message" => "The url must be unique."
)));
return $this->validationHasFailed() != true;
}