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?
Related
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);
}
}
}
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.
I want to do the SearchBox on my webapp. I followed tutorial: SeachBox Tutorial excatly, did everything author mentioned, and I'm getting an error:
Index doesn't exists in the specified directory.
My SearchController:
<?php
class SearchController extends Controller
{
private $_indexFiles = 'runtime.search';
public function init(){
Yii::import('application.vendors.*');
require_once('Zend/Search/Lucene.php');
parent::init();
}
/**
* Search index creation
*/
public function actionCreate()
{
$index = Zend_Search_Lucene::create($_indexFiles);
$index = new Zend_Search_Lucene(Yii::getPathOfAlias('application.' . $this->_indexFiles), true);
$posts = News::model()->findAll();
foreach($news as $news){
$doc = new Zend_Search_Lucene_Document();
$doc->addField(Zend_Search_Lucene_Field::Text('title',
CHtml::encode($news->name), 'utf-8')
);
$doc->addField(Zend_Search_Lucene_Field::Text('link',
CHtml::encode($news->url)
, 'utf-8')
);
$doc->addField(Zend_Search_Lucene_Field::Text('content',
CHtml::encode($news->description)
, 'utf-8')
);
$index->addDocument($doc);
}
$index->commit();
echo 'Lucene index created';
}
public function actionSearch()
{
$this->layout='column2';
if (($term = Yii::app()->getRequest()->getParam('q', null)) !== null) {
$index = new Zend_Search_Lucene(Yii::getPathOfAlias('application.' . $this->_indexFiles));
$results = $index->find($term);
$query = Zend_Search_Lucene_Search_QueryParser::parse($term);
$this->render('search', compact('results', 'term', 'query'));
}
}
}
Any ideas to solve this problem? Thanks for any help.
EDIT: OK, the solution was quite obvious. Index wasn't writed because it wasn't really declared...
this private $_indexFiles = 'runtime.search'; before init should just be in actionCreate function - then it works
Thanks for your help!
You have a typo:
$posts = News::model()->findAll();
foreach($news as $news){
Should be:
$posts = News::model()->findAll();
foreach($posts as $news){
I try to explain the problem I have!!!
I use PDO extension to connect to PostgreSQL through pgpool-II. It works fine within Apache, but from PHP CLI (on the same machine) I receive this PDO error:
SQLSTATE[HY000]: General error: 7 no connection to the server
I have already searched on Google and here, but it seems that no one has ever tried to do this. Does anyone have any idea?
EDIT:
This is the code I use to establish a connection:
include 'manage_db.php';
include_once 'properties.php';
global $properties;
$dsn = 'pgsql:dbname=' . $properties['db_pgpool'] . ';host=localhost;port=' . $properties['port_pgpool'];
try{
$mgmtDb = new ManageDb($dsn, $properties['username_pgpool'], $properties['password_pgpool']);
} catch (Exception $e) {
echo 'PDO - Caught exception: ', $e->getMessage(), "\n";
}
ManageDB is my own class that implements some utility functions as well as create the database connection:
class ManageDb {
var $db;
function ManageDb($dsn, $username, $password){
$this->db = new PDO($dsn, $username, $password);
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
....
Try this
config.database.php
<?php
class DatabaseConfig {
const DBNAME = 'dbname';
const HOST = '123.1.233.123';
const USER = 'mysuperuser';
const PASSWORD = 'mysupperparrword';
const PORT = 5432;
}
?>
class.database.php
<?php
include('config.database.php');
class Database {
protected static $instance = null;
final private function __construct() {}
final private function __destruct() {
self::$instance = null;
}
final private function __clone() {}
public static function getInstance() {
if (self::$instance === null) {
try {
self::$instance = new PDO(
'pgsql:host=' . DatabaseConfig::HOST .
';port=' . DatabaseConfig::PORT .
';dbname=' . DatabaseConfig::DBNAME .
';user=' . DatabaseConfig::USER .
';password=' . DatabaseConfig::PASSWORD
);
self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
self::$instance->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
} catch (PDOException $e) {
die('Database connection could not be established.');
}
}
return self::$instance;
}
public static function __callStatic($method, $args) {
return call_user_func_array(array(self::instance(), $method), $args);
}
}
?>
I've been following the Jobeet tutorial in order to integrate the Zend Lucene search into my Symfony project and I can't seem to get it to work. I have added the following code to my config/ProjectConfiguration.class.php
class ProjectConfiguration extends sfProjectConfiguration
{
static protected $zendLoaded = false;
static public function registerZend()
{
if (self::$zendLoaded)
{
return;
}
set_include_path(sfConfig::get('sf_lib_dir').'/vendor'.PATH_SEPARATOR.get_include_path());
require_once sfConfig::get('sf_lib_dir').'/vendor/Zend/Loader/Autoloader.php';
Zend_Loader_Autoloader::getInstance();
self::$zendLoaded = true;
}
I have also added this code to my CarTable.class.php
static public function getLuceneIndex()
{
ProjectConfiguration::registerZend();
if (file_exists($index = self::getLuceneIndexFile()))
{
return Zend_Search_Lucene::open($index);
}
return Zend_Search_Lucene::create($index);
}
static public function getLuceneIndexFile()
{
return sfConfig::get('sf_data_dir').'/car.'.sfConfig::get('sf_environment').'.index';
}
And lastly I have added the following code to my Car.class.php
public function updateLuceneIndex()
{
$index = CarTable::getLuceneIndex();
foreach ($index->find('pk:'.$this->getIditem()) as $hit)
{
$index->delete($hit->id);
}
if (!$this->getActivated())
{
return;
}
$doc = new Zend_Search_Lucene_Document();
$doc->addField(Zend_Search_Lucene_Field::Keyword('pk', $this->getIditem()));
$doc->addField(Zend_Search_Lucene_Field::UnStored('title', $this->getTitle(), 'utf-8'));
$doc->addField(Zend_Search_Lucene_Field::UnStored('features', $this->getFeatures(), 'utf-8'));
$doc->addField(Zend_Search_Lucene_Field::UnStored('location_city', $this->getLocation_city(), 'utf-8'));
$doc->addField(Zend_Search_Lucene_Field::UnStored('location_state', $this->getLocation_state(), 'utf-8'));
$index->addDocument($doc);
$index->commit();
}
public function delete(Doctrine_Connection $conn = null)
{
$index = CarTable::getLuceneIndex();
foreach ($index->find('pk:'.$this->getIditem()) as $hit)
{
$index->delete($hit->id);
}
return parent::delete($conn);
}
And of course I added these few lines to the save function:
$conn = $conn ? $conn : $this->getTable()->getConnection();
$conn->beginTransaction();
try
{
$ret = parent::save($conn);
$this->updateLuceneIndex();
$conn->commit();
return $ret;
}
catch (Exception $e)
{
$conn->rollBack();
throw $e;
}
I have extracted the contents of the "library" folder of the Zend Framework into my lib/vendor/Zend folder.
But every time I run the command
php symfony doctrine:data-load
It runs all the way through and loads all of my fixtures but it doesn't create the folder with the index files in my data folder. I'm not sure what I'm doing wrong.
Here is my reference (Jobeet Tutorial) http://www.symfony-project.org/jobeet/1_4/Doctrine/en/17
By the way I'm using Symfony 1.4 (Doctrine).