An uncaught Exception was encountered , Type: RuntimeException - codeigniter-3

Unable to locate the model you have specified: User_model
Filename: /opt/lampp/htdocs/ci/system/core/Loader.php
Line Number: 348
Backtrace:
File: /opt/lampp/htdocs/ci/index.php
Line: 315
Function: require_once
i tried to change name but it dose not work....
this code model
db->where(array(
'username' => $username,
'password' => $password
));
$result = $this->db->get('users');
if($result->num_rows()==1 ){
$return->$result->row(0)->id;
}else {
return false ;
}
}
}
?>

Make sure in model folder, the file name starts with Capital and very important point is "Change the model name to some "Reg_model.php" etc and update the controllers file accordingly.. This will surely works !!!
In controllers also use capital letter for the file name
NOTE: dont use the file names like Register_model.php etc , Instead use Reg_model.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {
function __construct()
{
parent::__construct();
}
public function index()
{
$this->register();
}
public function register()
$json = json_decode(file_get_contents('php://input'), TRUE);
$name= $json['name'];
$email = $json['email'];
$password = $json['password'];
echo $name; echo $email; echo $password;
$this->load->model('Reg_model');
$red= $this->Reg_model->registeration($name,$email,$password);
// echo 'controller23'; die();
$insert_id = $this->db->insert_id();
if($insert_id!==""){
$sql = "SELECT * FROM `users` where uid='$insert_id'";
$query = $this->db->query($sql);
$array1 = $query -> row();
echo json_encode($array1);}else{} }
public function login(){
$json = json_decode(file_get_contents('php://input'), TRUE);
$password = $json['password'];
$email = $json['email'];
$resp= $this->db->get_where('users', array('email'=>$email, 'password'=>$password))->row();
if($resp==""){ echo 'incorrect email or password'; }else
{
echo 'login success';
echo json_encode($resp);
}
}
}

Related

Magento 2: change order status programmatically

I need to set in "canceled" all orders stucks in "pending" status.
The code that I used return this exception error:
[2022-12-03 08:00:53] main.CRITICAL: Please provide payment for the order.
Here the code:
use Magento\Sales\Model\Order;
protected $order;
public function __construct(Order $order)
{
$this->order = $order;
}
public function orderStatusChange()
{
$orderId = 9999;
$order = $this->order->load($orderId);
$order->setStatus("canceled");
$order->save();
}
Please create a new file on the magento2 root and add below code:
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$orderId = '12345';
$order = $obj->create('\Magento\Sales\Model\OrderRepository')->get($orderId);
$order->setStatus("canceled");
$order->setState("canceled");
$order->save();
echo "Order updated";

Create Index using Moloquent with Laravel

I am new to MongoDB.
I am using Jensegger/Laravel-MongoDB Moloquent features to work on Mongo DB.
I am trying to create an index of a collection in this method:-
Schema::collection('events', function ($table) {
$table->index(['location' => '2dsphere']);
});
However, I am getting error:-
Class Jenssegers\Mongodb\Schema' not found
I have added these two as well:-
use Jenssegers\Mongodb\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
I have a controller method which is given below:-
public function fetchMongoTest(Request $request){
$error = FALSE;
$respond = array();
$detail = array();
$err_message = array();
$err_validation = array();
$api_code = 2001;
try
{
if ($request->isMethod('post'))
{
$latitude = (float)$request->latitude;
$longitude = (float)$request->longitude;
$status = 1;
$mongoData = array();
$monTestObj = new Mongotest;
Schema::collection('events', function ($table) {
$table->index(['location' => '2dsphere']);
});
$monTestObj->location = ['type' => 'Point', 'coordinates' => [100.0, 0.0]];
$monTestObj->save();
$users = MongoTest::where('loc', 'near', [
'$geometry' => [
'type' => 'Point',
'coordinates' => [
$longitude,
$latitude
]
],
'$maxDistance' => 10,
]);
foreach($users as $u)
{
print_r($u->name);
}
}
else
{
$status = 0;
$message = Config::get('customConfig.api_messages.ENG.post_request_mandatory');
$err_message[] = $message;
}
}
catch(Exception $e)
{
$status = 0;
echo $e->getMessage(); die;
$message=Config::get('customConfig.api_messages.ENG.exception_error');
}
$response['status'] = $status;
$response['message'] = $message;
$response['details'] = $detail;
$response['error'] = $err_message;
$response['error_validation_key'] = $err_validation;
$response['api_version'] = $this->api_version;
$response['api_code'] = $api_code;
$respond['fetch-activity-list-prime'] = $response;
$jsonResult = json_encode($respond);
header('Content-Type: application/json; charset=utf-8');
echo $jsonResult ;
exit();
}
How can I check if a collection exists and if not, create a new collection?
EDIT:
This is my MongoTest model:-
<?php
namespace App\Http\Model;
//use Illuminate\Database\Eloquent\Model;
use Moloquent;
class MongoTest extends Moloquent
{
protected $connection = 'mongodb';
protected $collection = 'test';
//protected $collection = 'rh_country_help_text';
}
You seems to have picked up a partial answer from somewhere. The Schema should be picked up from a "Larvel Migration", which is one recommended way of actually defining indexes in your application.
The process would be to set up like:
Create the Migration
php artisan make:migration create_location_index
Then alter the structure to add the up and down for create and drop of the index:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateLocationIndex extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::connection('mongodb')->table('test', function (Blueprint $collection) {
$collection->index([ "loc" => "2dsphere" ]);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::connection('mongodb')->table('test', function (Blueprint $collection) {
$collection->dropIndex(['loc_2dsphere']);
});
}
}
Then you can run the migration as detailed within the documentation
If you decide to run the code outside of a migrations process then alternate handles for getting the MongoDB\Collection object can be like:
DB::collection('test')->raw(function($collection) {
return $collection->createIndex([ 'loc' => '2dsphere' ])
}
Whatever you do though this code does not belong in the controller. The code to create an index need only be run once. Typically "once only" on your database deployment, but it does not really hurt to issue the command on every application start up, however it certainly hurts with every request. So just don't put it there.

How to get database stuff by using customized connection

I want to auto save the sql query every time, I found this article, if I do everything by the page it will work, but the problem is, I have master and slave database, therefore I have to connect to database like:
model/Users.php
<?php
class Users extends CI_Model
{
protected $table = 'users';
public $master;
public $slave;
public function __construct()
{
$this->master = $this->load->database('master', true);
$this->slave = $this->load->database('slave', true);
}
public function save($datas)
{
$this->master->insert($this->table, $datas);
return $this->master;
}
}
Then I adjust demo code like:
<?php
class Query_log
{
public function log_query()
{
$ci =& get_instance();
$filepath = APPPATH . 'logs/Query-log-' . date('Y-m-d') . '.php';
$handle = fopen($filepath, "a+");
$times = $ci->master->query_times;
foreach ($ci->master->queries as $key => $query) {
$sql = $query . " \n Execution Time:" . $times[$key];
fwrite($handle, $sql . "\n\n");
}
fclose($handle);
}
}
Of course I got error message
A PHP Error was encountered
Severity: Notice
Message: Undefined property: Users::$master
Filename: hooks/query_log.php
How to make it right?

Getting Entity in Doctrine Listener

I have 4 entities in my application Agency, Facilitator, Entry and EntryImage in my application. An Agency has multiple Facilitators who in turn make Entries into the system posting multiple EntryImages for each Entry.
I have a postPersist listener which performs actions depending on the entities, which works well when I save an Agency or Facilitator but not Entry or EntryImage. Here is the code below
<?php
namespace ACME\MyBundle\EventListener;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use ACME\MyBundle\Entity\Agency;
use ACME\MyBundle\Entity\Facilitator;
use ACME\MyBundle\Entity\Entry;
use Application\Sonata\UserBundle\Entity\User;
use Twig_Environment as Environment;
class UserListener
{
protected $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function postPersist(LifecycleEventArgs $args)
{
$entity = $args->getEntity();
$userManager = $this->container->get('fos_user.user_manager');
$em = $args->getEntityManager();
if ($entity instanceof Agency || $entity instanceof Facilitator)
{
$templateFile = "ACMEMyBundle:Default:email.html.twig";
$templateContent = $this->container->get('twig')->loadTemplate($templateFile);
$password = $entity->randomPassword();
$user = $userManager->createUser();
$user->setUsername($entity->getEmail());
$user->setEmail($entity->getEmail());
$user->setPlainPassword($password);
$user->setEnabled(true);
$userManager->updateUser($user, true);
if ($entity instanceof Agency)
{
$group = $em->getRepository('ApplicationSonataUserBundle:Group')->findOneBy(array('id' => 2));
$name = $entity->getName();
$email = array($entity->getContactEmail(),$entity->getAlternativeContactEmail());
}
if ($entity instanceof Facilitator)
{
$group = $em->getRepository('ApplicationSonataUserBundle:Group')->findOneBy(array('id' => 3));
$name = $entity->getFirstName().' '.$entity->getMiddleNames().' '.$entity->getSurname();
$email = $entity->getEmail();
}
$body = $templateContent->render(array('name' => $name, 'password' => $password, 'username' => $entity->getEmail()));
$message = \Swift_Message::newInstance()
->setSubject('Registration to OLX Moving Cheese Portal')
->setFrom(array('movingcheese#localhost.com' => 'Moving Cheese'))
->setTo($entity->getEmail())
->setCC($email)
->setContentType('text/html')
->setReplyTo(array('marvin#localhost.com', 'rita#localhost.com'))
->setBody($body)
;
$this->container->get('mailer')->send($message);
$current_user = $this->container->get('security.context')->getToken()->getUser();
$u = $userManager->findUserByUsername($entity->getEmail());
$u->addGroup($group);
$entity->setUser($u);
if ($entity instanceof Facilitator)
{
$agency = $em->getRepository('ACMEMyBundle:Agency')->findOneBy(array('user' => $current_user));
$entity->setAgency($agency);
$entity->setCreatedBy($current_user->getId());
}
$em->persist($u);
$em->persist($entity);
$em->flush();
}
if ($entity instanceof Entry)
{
$u = $this->container->get('security.context')->getToken()->getUser();
$entity->setUser($u);
$em->persist($entity);
$em->flush();
}
}
}
The issue is the line below evaluates fine when I'm saving a Facilitator or Agency
if ($entity instanceof Agency || $entity instanceof Facilitator)
But this line below doesn't evaluate when I try to save and Entry object even when dumping the $entity shows clearly an object is passed.
if ($entity instanceof Entry)
I don't know whether this is of any significance but maybe i should mention that I have embedded an EntryImageAdmin into EntryAdmin form

how to check full error log in Zend framework?

I am newbie in ZF and this is my first test. i am getting
An error occurred
An error occurred
my error.phtml is
<h1>An error occurred</h1>
<h2><?php echo $this->message ?></h2>
<?php if (isset($this->exception)): ?>
<h3>Exception information:</h3>
<p>
<b>Message:</b> <?php echo $this->exception->getMessage() ?>
</p>
<h3>Stack trace:</h3>
<pre><?php echo $this->exception->getTraceAsString() ?>
</pre>
<h3>Request Parameters:</h3>
<pre><?php echo $this->escape(var_export($this->request->getParams(), true)) ?>
</pre>
<?php endif ?>
and this is what i have in my IndexAction
$this->view->title="My Places";
$this->view->headTitle($this->view->title);
$Places=new Places();
echo "<pre>";var_dump($Places->fetchAll(null,'date_created DESC', 4)); echo "</pre>";
and my module file id
class Places extends Zend_Db_Table
{
protected $_name='places';
public function fetchLatest($count=10)
{
return $this->fetchAll(null,'date_created DESC', $count);
}
}
** EDIT **
ErrorController is
<?php
class ErrorController extends Zend_Controller_Action
{
public function errorAction()
{
$errors = $this->_getParam('error_handler');
if (!$errors || !$errors instanceof ArrayObject) {
$this->view->message = 'You have reached the error page';
return;
}
switch ($errors->type) {
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
// 404 error -- controller or action not found
$this->getResponse()->setHttpResponseCode(404);
$priority = Zend_Log::NOTICE;
$this->view->message = 'Page not found';
break;
default:
// application error
$this->getResponse()->setHttpResponseCode(500);
$priority = Zend_Log::CRIT;
$this->view->message = 'Application error';
break;
}
// Log exception, if logger available
if ($log = $this->getLog()) {
$log->log($this->view->message, $priority, $errors->exception);
$log->log('Request Parameters', $priority, $errors->request->getParams());
}
// conditionally display exceptions
if ($this->getInvokeArg('displayExceptions') == true) {
$this->view->exception = $errors->exception;
}
$this->view->request = $errors->request;
}
public function getLog()
{
$bootstrap = $this->getInvokeArg('bootstrap');
if (!$bootstrap->hasResource('Log')) {
return false;
}
$log = $bootstrap->getResource('Log');
return $log;
}
}
How can i know what caused this error? (how can i see full error log?)
Thanks
In your /application/configs/application.ini
set
resources.frontController.params.displayExceptions = 1
For the environment you are in. If you don't know which one you are in, put it temporarily under [production].