Goodday Stackoverflow,
I've implented the Captcha-helper in my project successfully. The image is being displayed, saved and what not, although the image itself is created again and again and again after every refresh. After 10 refreshes, my captcha folder contains 10 images.
Is this normal?
This is my code;
...
/**
* Method that returns the currently
* active Captcha code of the user.
*
* #access public
* #return string - user's captcha code
* #since v0.1.0.0
*/
public function get_captcha()
{
// Check for already existing captcha's.
if ($this->is_captcha())
{
// Get the captcha.
$data = $this->get_captcha_data();
}
else
{
// Create a new captcha.
if ($this->insert_captcha())
$data = $this->get_captcha_data();
}
// Set the values.
$captcha_vals = array(
'word' => $data['word'],
'img_path' => './media/sm_general/captcha/',
'img_url' => base_url().'media/sm_general/captcha/',
'img_width' => '175',
'img_height' => '60'
);
// Return the captcha.
return create_captcha($captcha_vals);
}
/**
* Method that returns the captcha data
* of a specific user.
*
* #access private
* #param string $field - (optional) specific to be returned data
* #return array/string - data of the captcha
* #since v0.1.0.0
*/
private function get_captcha_data($field='')
{
// Prepare the query.
$this->db->select('*');
$this->db->from('sm_sessions_captcha');
$this->db->where('ip_address',$this->input->ip_address());
$this->db->limit(1);
// Execute the query.
$query = $this->db->get();
// Get the result.
$result = $query->row_array();
// Return the data.
if ( ! empty($field))
return $result[$field];
else
return $result;
}
/**
* Method that returns a random word from
* the database.
*
* #access private
* #return string - randomly selected word
* #since v0.1.0.0
*/
private function get_word_random()
{
// Prepare the query.
$this->db->select('word');
$this->db->from('sm_sessions_captcha_words');
$this->db->order_by('word','RANDOM');
$this->db->limit(1);
// Execute the query.
$query = $this->db->get();
// Get the result.
$result = $query->row_array();
// Return the word.
return $result['word'];
}
/**
* Method that creates a new captcha image.
*
* #access private
* #return array
* #since v0.1.0.0
*/
private function insert_captcha()
{
// Prepare the query.
$data = array(
'captcha_time' => (time() + 7200),
'ip_address' => $this->input->ip_address(),
'word' => $this->get_word_random()
);
// Execute the query.
if ($this->db->insert('sm_sessions_captcha',$data))
return true;
else
return false;
}
/**
* Check if a captcha already exists.
*
* #access private
* #return boolean - exists or not
* #since v0.1.0.0
*/
private function is_captcha()
{
// Set the expiration time.
$expiration = time() - 7200;
// Remove all expired captchas.
$this->db->where('captcha_time <',$expiration);
$this->db->delete('sm_sessions_captcha');
// Prepare the query.
$this->db->select('*');
$this->db->from('sm_sessions_captcha');
$this->db->where('captcha_time >=',$expiration);
$this->db->where('ip_address',$this->input->ip_address());
$this->db->limit(1);
// Execute the query.
$query = $this->db->get();
// Return the existence.
if ($query->num_rows() == 1)
return true;
else
return false;
}
...
I have no idea if this is working as intended. Please enlighten me if I am mistaking.
Cheers.
This is normal, every refresh a new captcha image is generated, then CI runs a garbage collection, so you can set how much time the old captcha image should remain inside the folder by "expiration" value
http://ellislab.com/codeigniter/user-guide/helpers/captcha_helper.html
$cap = create_captcha($vals);
$this->session->set_userdata('time', $cap['time']);
Write in when data store in database.
Above that:
unlink(realpath('captcha').'/'.$this->session->userdata('time').'.jpg');
Related
Routes - I have 2 routes related to this
Route::resource('items', 'ItemsController');
Route::get('process/{process}/items', 'ItemsController#index');
When I use the 2nd, the index function (in the controller mentioned above) picks up the process id and runs without a hitch.
This is the link on a separate view which uses the 2nd route listed above:
{{ HTML::link('process/'.$process->id.'/items', 'Manage Items', array('class' =>'btn btn-primary')) }}
When I use a redirect from the update function in the same controller I get
"Missing argument 1 for ItemsController::index()"
which is the function that accepts the parameter so it can display all the items with that id.
It doesn't seem to matter what I use. Here are some of the statements I've tried in order to redirect to the index function:
return Redirect::route('items.index', array($data['process_id']));
return Redirect::action('ItemsController#index', array($data['process_id']));
I've also tried using "with(...)"
The following (using either route or action) gives me a "route not defined" error:
return Redirect::action('process/'.$data['process_id'].'/items');
I don't think its good practice to recreate the view as in the index function. I should just be able to redirect and have done with it.
What am I doing wrong?
The model relatioships are as follows:
1 project hasmany items
1 item hasmany attributes
1 attribute hasmany extensions
controller source code
<?php
class ItemAttributesController extends \BaseController {
/**
* Display a listing of itemattributes
*
* #return Response
*/
public function index($item_id)
{
return $this->makeIndex($item_id);
}
/**
* Show the form for creating a new itemattribute
*
* #return Response
*/
public function create()
{
return View::make('item_attributes.create');
}
/**
* Store a newly created itemattribute in storage.
*
* #return Response
*/
public function store()
{
$validator = Validator::make($data = Input::all(), Itemattribute::$rules);
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
$attribute = Itemattribute::create($data);
// add created attribute id to sequence in the item for this attribute
$item = Item::findOrFail($attribute->item_id);
// get the sequence data
// append the attribute id
if (isset($item->attribute)){
$item->attribute = $item->attribute.', '.$attribute->id;
} else {
$item->attribute = $attribute->id;
}
$item->save();
return $this->makeIndex($data['item_id']);
}
/**
* Display the specified itemattribute.
*
* #param int $id
* #return Response
*/
public function show($id)
{
$itemattribute = Itemattribute::findOrFail($id);
return View::make('item_attributes.show', compact('itemattribute'));
}
/**
* Show the form for editing the specified itemattribute.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
$itemattribute = Itemattribute::find($id);
return View::make('item_attributes.edit', compact('itemattribute'));
}
/**
* Update the specified itemattribute in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
$itemattribute = Itemattribute::findOrFail($id);
$validator = Validator::make($data = Input::all(), Itemattribute::$rules);
if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
$itemattribute->update($data);
return $this->makeIndex($data['item_id']);
}
/**
* Remove the specified itemattribute from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
$attribute = Itemattribute::findOrFail($id);
//find the item
$item = Item::findOrFail($attribute->item_id);
// get the sequence string
if (isset($item->attribute)){
// convert to array
$arr=explode(",",$item->attribute);
// remove item
if(($key = array_search($id, $arr)) !== false) {
unset($arr[$key]);
}
// convert back to string and replace initial string
$item->attribute = implode(",", $arr);
// save
$item->save();
}
ItemAttribute::destroy($id);
// return Redirect::route('item_attributes.index');
return $this->makeIndex($attribute->item_id);
}
private function makeIndex($item_id){
$item = Item::findOrFail($item_id);
$project = Project::findOrFail($item->project_id);
$item_attributes = DB::table('item_attributes')->where('item_id', $item->id)->get();
return View::make('item_attributes.index', compact('item_attributes', 'item', 'project'));
// return Redirect::to('item_attributes', );
}
}
routes source code
Route::get('/', function()
{
return View::make('home');
});
Route::resource('projects', 'ProjectsController');
Route::resource('items', 'ItemsController');
Route::resource('item_attributes', 'ItemAttributesController');
Route::resource('attribute_extentions', 'AttributeExtensionsController');
Route::get('project/{projects}/items', 'ItemsController#index');
Route::get('project/{projects}/item/create', 'ItemsController#create');
Route::get('item/{items}/item_attributes', array('as' => 'item_attributes', 'uses' => 'ItemAttributesController#index'));
Route::get('item/{items}/attribute_extentions', 'AttributeExtensionsController#index');
You are not using the route action correctly, it should point to the controller#function.
return Redirect::action('ItemsController#index', array('item_id' => 1));
Fixed it!
The solution was to use
return Redirect::to('item/'.$item->id.'/item_attributes');
This correctly passed the parameter in way that it could be picked up as a parameter by the function.
Thanks for all your help!
I am currently working with the starter site here:
https://github.com/andrewelkins/Laravel-4-Bootstrap-Starter-Site
Any html I put as blog post gets converted to text. For example, tag hi tag(should have brackets around tag) get converted into hi within a div. I want it to just output hi in a tag like a div
Here is the Controller
<?php
class AdminBlogsController extends AdminController {
/**
* Post Model
* #var Post
*/
protected $post;
/**
* Inject the models.
* #param Post $post
*/
public function __construct(Post $post)
{
parent::__construct();
$this->post = $post;
}
/**
* Show a list of all the blog posts.
*
* #return View
*/
public function getIndex()
{
// Title
$title = Lang::get('admin/blogs/title.blog_management');
// Grab all the blog posts
$posts = $this->post;
// Show the page
return View::make('admin/blogs/index', compact('posts', 'title'));
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function getCreate()
{
// Title
$title = Lang::get('admin/blogs/title.create_a_new_blog');
// Show the page
return View::make('admin/blogs/create_edit', compact('title'));
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function postCreate()
{
// Declare the rules for the form validation
$rules = array(
'title' => 'required|min:3',
'content' => 'required|min:3'
);
// Validate the inputs
$validator = Validator::make(Input::all(), $rules);
// Check if the form validates with success
if ($validator->passes())
{
// Create a new blog post
$user = Auth::user();
// Update the blog post data
$this->post->title = Input::get('title');
$this->post->slug = Str::slug(Input::get('title'));
$this->post->content = Input::get('content');
$this->post->meta_title = Input::get('meta-title');
$this->post->meta_description = Input::get('meta-description');
$this->post->meta_keywords = Input::get('meta-keywords');
$this->post->user_id = $user->id;
// Was the blog post created?
if($this->post->save())
{
// Redirect to the new blog post page
return Redirect::to('admin/blogs/' . $this->post->id . '/edit')->with('success', Lang::get('admin/blogs/messages.create.success'));
}
// Redirect to the blog post create page
return Redirect::to('admin/blogs/create')->with('error', Lang::get('admin/blogs/messages.create.error'));
}
// Form validation failed
return Redirect::to('admin/blogs/create')->withInput()->withErrors($validator);
}
/**
* Display the specified resource.
*
* #param $post
* #return Response
*/
public function getShow($post)
{
// redirect to the frontend
}
/**
* Show the form for editing the specified resource.
*
* #param $post
* #return Response
*/
public function getEdit($post)
{
// Title
$title = Lang::get('admin/blogs/title.blog_update');
// Show the page
return View::make('admin/blogs/create_edit', compact('post', 'title'));
}
/**
* Update the specified resource in storage.
*
* #param $post
* #return Response
*/
public function postEdit($post)
{
// Declare the rules for the form validation
$rules = array(
'title' => 'required|min:3',
'content' => 'required|min:3'
);
// Validate the inputs
$validator = Validator::make(Input::all(), $rules);
// Check if the form validates with success
if ($validator->passes())
{
// Update the blog post data
$post->title = Input::get('title');
$post->slug = Str::slug(Input::get('title'));
$post->content = Input::get('content');
$post->meta_title = Input::get('meta-title');
$post->meta_description = Input::get('meta-description');
$post->meta_keywords = Input::get('meta-keywords');
// Was the blog post updated?
if($post->save())
{
// Redirect to the new blog post page
return Redirect::to('admin/blogs/' . $post->id . '/edit')->with('success', Lang::get('admin/blogs/messages.update.success'));
}
// Redirect to the blogs post management page
return Redirect::to('admin/blogs/' . $post->id . '/edit')->with('error', Lang::get('admin/blogs/messages.update.error'));
}
// Form validation failed
return Redirect::to('admin/blogs/' . $post->id . '/edit')->withInput()->withErrors($validator);
}
/**
* Remove the specified resource from storage.
*
* #param $post
* #return Response
*/
public function getDelete($post)
{
// Title
$title = Lang::get('admin/blogs/title.blog_delete');
// Show the page
return View::make('admin/blogs/delete', compact('post', 'title'));
}
/**
* Remove the specified resource from storage.
*
* #param $post
* #return Response
*/
public function postDelete($post)
{
// Declare the rules for the form validation
$rules = array(
'id' => 'required|integer'
);
// Validate the inputs
$validator = Validator::make(Input::all(), $rules);
// Check if the form validates with success
if ($validator->passes())
{
$id = $post->id;
$post->delete();
// Was the blog post deleted?
$post = Post::find($id);
if(empty($post))
{
// Redirect to the blog posts management page
return Redirect::to('admin/blogs')->with('success', Lang::get('admin/blogs/messages.delete.success'));
}
}
// There was a problem deleting the blog post
return Redirect::to('admin/blogs')->with('error', Lang::get('admin/blogs/messages.delete.error'));
}
/**
* Show a list of all the blog posts formatted for Datatables.
*
* #return Datatables JSON
*/
public function getData()
{
$posts = Post::select(array('posts.id', 'posts.title', 'posts.id as comments', 'posts.created_at'));
return Datatables::of($posts)
->edit_column('comments', '{{ DB::table(\'comments\')->where(\'post_id\', \'=\', $id)->count() }}')
->add_column('actions', '<a href="{{{ URL::to(\'admin/blogs/\' . $id . \'/edit\' ) }}}" class="btn btn-default btn-xs iframe" >{{{ Lang::get(\'button.edit\') }}}</a>
{{{ Lang::get(\'button.delete\') }}}
')
->remove_column('id')
->make();
}
}
Here is the Model
<?php
use Illuminate\Support\Facades\URL;
class Post extends Eloquent {
/**
* Deletes a blog post and all
* the associated comments.
*
* #return bool
*/
public function delete()
{
// Delete the comments
$this->comments()->delete();
// Delete the blog post
return parent::delete();
}
/**
* Returns a formatted post content entry,
* this ensures that line breaks are returned.
*
* #return string
*/
public function content()
{
return nl2br($this->content);
}
/**
* Get the post's author.
*
* #return User
*/
public function author()
{
return $this->belongsTo('User', 'user_id');
}
/**
* Get the post's meta_description.
*
* #return string
*/
public function meta_description()
{
return $this->meta_description;
}
/**
* Get the post's meta_keywords.
*
* #return string
*/
public function meta_keywords()
{
return $this->meta_keywords;
}
/**
* Get the post's comments.
*
* #return array
*/
public function comments()
{
return $this->hasMany('Comment');
}
/**
* Get the date the post was created.
*
* #param \Carbon|null $date
* #return string
*/
public function date($date=null)
{
if(is_null($date)) {
$date = $this->created_at;
}
return String::date($date);
}
/**
* Get the URL to the post.
*
* #return string
*/
public function url()
{
return Url::to($this->slug);
}
/**
* Returns the date of the blog post creation,
* on a good and more readable format :)
*
* #return string
*/
public function created_at()
{
return $this->date($this->created_at);
}
/**
* Returns the date of the blog post last update,
* on a good and more readable format :)
*
* #return string
*/
public function updated_at()
{
return $this->date($this->updated_at);
}
}
Thank you in advanced for your help!
This is because the output within the views you are using, is being ran through htmlentities via the blade curly braces {{{ }}}, meaning;
<div>hi </div>
is converted into
<<div>hi </div>
To prevent this and to allow html within posts, change the {{{ }}} to {{ }}.
You have two solutions here:
you can either find in which file the content is being encoded and remove the code that's doing the encoding
or whenever you need to output a value that's encoded, just decode it using HTML::decode(). So for an encoded post content you can write in yout view HTML::decode($post->content).
This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 1 year ago.
I have this error in a Component in Joomla
That's my code (the error is in line 263):
<?php
/**
* #package Joomla.Platform
* #subpackage Database
*
* #copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* #license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
JLoader::register('JDatabaseMySQL', dirname(__FILE__) . '/mysql.php');
JLoader::register('JDatabaseQueryMySQLi', dirname(__FILE__) . '/mysqliquery.php');
JLoader::register('JDatabaseExporterMySQLi', dirname(__FILE__) . '/mysqliexporter.php');
JLoader::register('JDatabaseImporterMySQLi', dirname(__FILE__) . '/mysqliimporter.php');
/**
* MySQLi database driver
*
* #package Joomla.Platform
* #subpackage Database
* #see http://php.net/manual/en/book.mysqli.php
* #since 11.1
*/
class JDatabaseMySQLi extends JDatabaseMySQL
{
/**
* The name of the database driver.
*
* #var string
* #since 11.1
*/
public $name = 'mysqli';
/**
* Constructor.
*
* #param array $options List of options used to configure the connection
*
* #since 11.1
*/
protected function __construct($options)
{
// Get some basic values from the options.
$options['host'] = (isset($options['host'])) ? $options['host'] : 'localhost';
$options['user'] = (isset($options['user'])) ? $options['user'] : 'root';
$options['password'] = (isset($options['password'])) ? $options['password'] : '';
$options['database'] = (isset($options['database'])) ? $options['database'] : '';
$options['select'] = (isset($options['select'])) ? (bool) $options['select'] : true;
$options['port'] = null;
$options['socket'] = null;
/*
* Unlike mysql_connect(), mysqli_connect() takes the port and socket as separate arguments. Therefore, we
* have to extract them from the host string.
*/
$tmp = substr(strstr($options['host'], ':'), 1);
if (!empty($tmp))
{
// Get the port number or socket name
if (is_numeric($tmp))
{
$options['port'] = $tmp;
}
else
{
$options['socket'] = $tmp;
}
// Extract the host name only
$options['host'] = substr($options['host'], 0, strlen($options['host']) - (strlen($tmp) + 1));
// This will take care of the following notation: ":3306"
if ($options['host'] == '')
{
$options['host'] = 'localhost';
}
}
// Make sure the MySQLi extension for PHP is installed and enabled.
if (!function_exists('mysqli_connect'))
{
// Legacy error handling switch based on the JError::$legacy switch.
// #deprecated 12.1
if (JError::$legacy)
{
$this->errorNum = 1;
$this->errorMsg = JText::_('JLIB_DATABASE_ERROR_ADAPTER_MYSQLI');
return;
}
else
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_ADAPTER_MYSQLI'));
}
}
$this->connection = #mysqli_connect(
$options['host'], $options['user'], $options['password'], null, $options['port'], $options['socket']
);
// Attempt to connect to the server.
if (!$this->connection)
{
// Legacy error handling switch based on the JError::$legacy switch.
// #deprecated 12.1
if (JError::$legacy)
{
$this->errorNum = 2;
$this->errorMsg = JText::_('JLIB_DATABASE_ERROR_CONNECT_MYSQL');
return;
}
else
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_CONNECT_MYSQL'));
}
}
// Finalize initialisation
JDatabase::__construct($options);
// Set sql_mode to non_strict mode
mysqli_query($this->connection, "SET ##SESSION.sql_mode = '';");
// If auto-select is enabled select the given database.
if ($options['select'] && !empty($options['database']))
{
$this->select($options['database']);
}
}
/**
* Destructor.
*
* #since 11.1
*/
public function __destruct()
{
if (is_callable(array($this->connection, 'close')))
{
mysqli_close($this->connection);
}
}
/**
* Method to escape a string for usage in an SQL statement.
*
* #param string $text The string to be escaped.
* #param boolean $extra Optional parameter to provide extra escaping.
*
* #return string The escaped string.
*
* #since 11.1
*/
public function escape($text, $extra = false)
{
$result = mysqli_real_escape_string($this->getConnection(), $text);
if ($extra)
{
$result = addcslashes($result, '%_');
}
return $result;
}
/**
* Test to see if the MySQL connector is available.
*
* #return boolean True on success, false otherwise.
*
* #since 11.1
*/
public static function test()
{
return (function_exists('mysqli_connect'));
}
/**
* Determines if the connection to the server is active.
*
* #return boolean True if connected to the database engine.
*
* #since 11.1
*/
public function connected()
{
if (is_object($this->connection))
{
return mysqli_ping($this->connection);
}
return false;
}
/**
* Get the number of affected rows for the previous executed SQL statement.
*
* #return integer The number of affected rows.
*
* #since 11.1
*/
public function getAffectedRows()
{
return mysqli_affected_rows($this->connection);
}
/**
* Gets an exporter class object.
*
* #return JDatabaseExporterMySQLi An exporter object.
*
* #since 11.1
* #throws JDatabaseException
*/
public function getExporter()
{
// Make sure we have an exporter class for this driver.
if (!class_exists('JDatabaseExporterMySQLi'))
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_MISSING_EXPORTER'));
}
$o = new JDatabaseExporterMySQLi;
$o->setDbo($this);
return $o;
}
/**
* Gets an importer class object.
*
* #return JDatabaseImporterMySQLi An importer object.
*
* #since 11.1
* #throws JDatabaseException
*/
public function getImporter()
{
// Make sure we have an importer class for this driver.
if (!class_exists('JDatabaseImporterMySQLi'))
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_MISSING_IMPORTER'));
}
$o = new JDatabaseImporterMySQLi;
$o->setDbo($this);
return $o;
}
/**
* Get the number of returned rows for the previous executed SQL statement.
*
* #param resource $cursor An optional database cursor resource to extract the row count from.
*
* #return integer The number of returned rows.
*
* #since 11.1
*/
public function getNumRows($cursor = null)
{
return mysqli_num_rows($cursor ? $cursor : $this->cursor);
}
/**
* Get the current or query, or new JDatabaseQuery object.
*
* #param boolean $new False to return the last query set, True to return a new JDatabaseQuery object.
*
* #return mixed The current value of the internal SQL variable or a new JDatabaseQuery object.
*
* #since 11.1
* #throws JDatabaseException
*/
public function getQuery($new = false)
{
if ($new)
{
// Make sure we have a query class for this driver.
if (!class_exists('JDatabaseQueryMySQLi'))
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_MISSING_QUERY'));
}
return new JDatabaseQueryMySQLi($this);
}
else
{
return $this->sql;
}
}
/**
* Get the version of the database connector.
*
* #return string The database connector version.
*
* #since 11.1
*/
public function getVersion()
{
return mysqli_get_server_info($this->connection);
}
/**
* Determines if the database engine supports UTF-8 character encoding.
*
* #return boolean True if supported.
*
* #since 11.1
* #deprecated 12.1
*/
public function hasUTF()
{
JLog::add('JDatabaseMySQLi::hasUTF() is deprecated.', JLog::WARNING, 'deprecated');
return true;
}
/**
* Method to get the auto-incremented value from the last INSERT statement.
*
* #return integer The value of the auto-increment field from the last inserted row.
*
* #since 11.1
*/
public function insertid()
{
return mysqli_insert_id($this->connection);
}
/**
* Execute the SQL statement.
*
* #return mixed A database cursor resource on success, boolean false on failure.
*
* #since 11.1
* #throws JDatabaseException
*/
public function execute()
{
if (!is_object($this->connection))
{
// Legacy error handling switch based on the JError::$legacy switch.
// #deprecated 12.1
if (JError::$legacy)
{
if ($this->debug)
{
JError::raiseError(500, 'JDatabaseMySQLi::query: ' . $this->errorNum . ' - ' . $this->errorMsg);
}
return false;
}
else
{
JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'database');
throw new JDatabaseException($this->errorMsg, $this->errorNum);
}
}
// Take a local copy so that we don't modify the original query and cause issues later
$sql = $this->replacePrefix((string) $this->sql);
if ($this->limit > 0 || $this->offset > 0)
{
$sql .= ' LIMIT ' . $this->offset . ', ' . $this->limit;
}
// If debugging is enabled then let's log the query.
if ($this->debug)
{
// Increment the query counter and add the query to the object queue.
$this->count++;
$this->log[] = $sql;
JLog::add($sql, JLog::DEBUG, 'databasequery');
}
// Reset the error values.
$this->errorNum = 0;
$this->errorMsg = '';
// Execute the query.
$this->cursor = mysqli_query($this->connection, $sql);
// If an error occurred handle it.
if (!$this->cursor)
{
$this->errorNum = (int) mysqli_errno($this->connection);
$this->errorMsg = (string) mysqli_error($this->connection) . ' SQL=' . $sql;
// Legacy error handling switch based on the JError::$legacy switch.
// #deprecated 12.1
if (JError::$legacy)
{
if ($this->debug)
{
JError::raiseError(500, 'JDatabaseMySQLi::query: ' . $this->errorNum . ' - ' . $this->errorMsg);
}
return false;
}
else
{
JLog::add(JText::sprintf('JLIB_DATABASE_QUERY_FAILED', $this->errorNum, $this->errorMsg), JLog::ERROR, 'databasequery');
throw new JDatabaseException($this->errorMsg, $this->errorNum);
}
}
return $this->cursor;
}
/**
* Select a database for use.
*
* #param string $database The name of the database to select for use.
*
* #return boolean True if the database was successfully selected.
*
* #since 11.1
* #throws JDatabaseException
*/
public function select($database)
{
if (!$database)
{
return false;
}
if (!mysqli_select_db($this->connection, $database))
{
// Legacy error handling switch based on the JError::$legacy switch.
// #deprecated 12.1
if (JError::$legacy)
{
$this->errorNum = 3;
$this->errorMsg = JText::_('JLIB_DATABASE_ERROR_DATABASE_CONNECT');
return false;
}
else
{
throw new JDatabaseException(JText::_('JLIB_DATABASE_ERROR_DATABASE_CONNECT'));
}
}
return true;
}
/**
* Set the connection to use UTF-8 character encoding.
*
* #return boolean True on success.
*
* #since 11.1
*/
public function setUTF()
{
mysqli_query($this->connection, "SET NAMES 'utf8'");
}
/**
* Method to fetch a row from the result set cursor as an array.
*
* #param mixed $cursor The optional result set cursor from which to fetch the row.
*
* #return mixed Either the next row from the result set or false if there are no more rows.
*
* #since 11.1
*/
protected function fetchArray($cursor = null)
{
return mysqli_fetch_row($cursor ? $cursor : $this->cursor);
}
/**
* Method to fetch a row from the result set cursor as an associative array.
*
* #param mixed $cursor The optional result set cursor from which to fetch the row.
*
* #return mixed Either the next row from the result set or false if there are no more rows.
*
* #since 11.1
*/
protected function fetchAssoc($cursor = null)
{
return mysqli_fetch_assoc($cursor ? $cursor : $this->cursor);
}
/**
* Method to fetch a row from the result set cursor as an object.
*
* #param mixed $cursor The optional result set cursor from which to fetch the row.
* #param string $class The class name to use for the returned row object.
*
* #return mixed Either the next row from the result set or false if there are no more rows.
*
* #since 11.1
*/
protected function fetchObject($cursor = null, $class = 'stdClass')
{
return mysqli_fetch_object($cursor ? $cursor : $this->cursor, $class);
}
/**
* Method to free up the memory used for the result set.
*
* #param mixed $cursor The optional result set cursor from which to fetch the row.
*
* #return void
*
* #since 11.1
*/
protected function freeResult($cursor = null)
{
mysqli_free_result($cursor ? $cursor : $this->cursor);
}
/**
* Execute a query batch.
*
* #param boolean $abortOnError Abort on error.
* #param boolean $transactionSafe Transaction safe queries.
*
* #return mixed A database resource if successful, false if not.
*
* #deprecated 12.1
* #since 11.1
*/
public function queryBatch($abortOnError = true, $transactionSafe = false)
{
// Deprecation warning.
JLog::add('JDatabaseMySQLi::queryBatch() is deprecated.', JLog::WARNING, 'deprecated');
$sql = $this->replacePrefix((string) $this->sql);
$this->errorNum = 0;
$this->errorMsg = '';
// If the batch is meant to be transaction safe then we need to wrap it in a transaction.
if ($transactionSafe)
{
$sql = 'START TRANSACTION;' . rtrim($sql, "; \t\r\n\0") . '; COMMIT;';
}
$queries = $this->splitSql($sql);
$error = 0;
foreach ($queries as $query)
{
$query = trim($query);
if ($query != '')
{
$this->cursor = mysqli_query($this->connection, $query);
if ($this->debug)
{
$this->count++;
$this->log[] = $query;
}
if (!$this->cursor)
{
$error = 1;
$this->errorNum .= mysqli_errno($this->connection) . ' ';
$this->errorMsg .= mysqli_error($this->connection) . " SQL=$query <br />";
if ($abortOnError)
{
return $this->cursor;
}
}
}
}
return $error ? false : true;
}
}
As the link Jon Conde provided says, you are getting this because you have an error in your query. You have not provided the query so it's impossible to know what the problem is. Unfortunately some of the advice you are getting on the whole is going to make it worse because the problem is not in JDatabaseQueryMysqli it is in the code where you are calling it. You are getting a boolean false instead of the expected results because your query has failed.
To see your generated query you can use
echo $query->dump();
put it before you are calling getNumRows(). You may need a die; depending on the context or just log it or if in the cms you can turn on the debugger and see the generated queries (global configuration, debug on).
If you provide your code (not a copy of the api) then people can help debug your query.
I will say it's a bug that it's not testing for that and throwing an exception if your query has failed.
If you're using joomla 2.5, please check again of your php version ; It must be php 5.3 at least.
in node.js i will create mongodb session like this.
app.configure(function()
{
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.session({
secret: 'MY SECRET',
store: new MongoStore({
db: 'MY SESSION DB',
host: 'localhost',
port:88888
})
}));
app.use(everyauth.middleware());
app.use(express.methodOverride());
app.use(app.router);
});
how to create session with mongodb in php.i am new one for php..i want to create session with mongodb in php(webserver: apache),so let me know how to create
You must use a session handler to accomplish this. Normally we don't answer these sort of questions which lack research of any kind but, this one time, here is a small, extremely simple, self contained edition I have:
class Session{
public $db;
/**
* This decides the lifetime (in seconds) of the session
*
* #access private
* #var int
*/
public $life_time='+2 weeks';
/**
* This stores the found session collection so that we don't
* waste resources by constantly going back for it
*
* #access private
* #var sessions
*/
private $_session = array();
/**
* Constructor
*/
function open() {
// Ensure index on Session ID
$this->db->sessions->ensureIndex(array('session_id' => 1), array("unique" => true));
// Register this object as the session handler
session_set_save_handler(
array( $this, "openSession" ),
array( $this, "closeSession" ),
array( $this, "readSession" ),
array( $this, "writeSession"),
array( $this, "destroySession"),
array( $this, "gcSession" )
);
session_start(); // Start the damn session
}
/**
* Open session
*
* This function opens a session from a save path.
* The save path can be changed the method of opening also can
* but we do not change that we just do the basics and return
*
* #param string $save_path
* #param string $session_name
*/
function openSession( $save_path, $session_name ) {
global $sess_save_path;
$sess_save_path = $save_path;
// Don't need to do anything. Just return TRUE.
return true;
}
/**
* This function closes the session (end of session)
*/
function closeSession() {
// Return true to indicate session closed
return true;
}
/**
* This is the read function that is called when we open a session.
* This function attempts to find a session from the Db. If it cannot then
* the session class variable will remain null.
*
* #param string $id
*/
function readSession( $id ) {
// Set empty result
$data = '';
// Fetch session data from the selected database
$time = time();
$this->_sessions = $this->db->sessions->findOne(array("session_id"=>$id));
if (!empty($this->_sessions)) {
$data = $this->_sessions['session_data'];
}
return $data;
}
/**
* This is the write function. It is called when the session closes and
* writes all new data to the Db. It will do two actions depending on whether or not
* a session already exists. If the session does exist it will just update the session
* otherwise it will insert a new session.
*
* #param string $id
* #param mixed $data
*
* #todo Need to make this function aware of other users since php sessions are not always unique maybe delete all old sessions.
*/
function writeSession( $id, $data ) {
//Write details to session table
$time = strtotime('+2 weeks');
// If the user is logged in record their uid
$uid = $_SESSION['logged'] ? $_SESSION['uid'] : 0;
$fields = array(
"session_id"=>$id,
"user_id"=>$uid,
"session_data"=>$data,
"expires"=>$time,
"active"=>1
);
$fg = $this->db->sessions->update(array("session_id"=>$id), array('$set'=>$fields), array("upsert"=>true));
// DONE
return true;
}
/**
* This function is called when a user calls session_destroy(). It
* kills the session and removes it.
*
* #param string $id
*/
function destroySession( $id ) {
// Remove from Db
$this->db->sessions->remove(array("session_id" => $id), true);
return true;
}
/**
* This function GCs (Garbage Collection) all old and out of date sessions
* which still exist in the Db. It will remove by comparing the current to the time of
* expiring on the session record.
*
* #todo Make a cronjob to delete all sessions after about a day old and are still inactive
*/
function gcSession() {
$this->db->sessions->remove(array('expires' => array('$lt' => strtotime($this->life_time))));
return true;
}
}
Which can be called like so:
$session = new Session;
$session->db=$mongo->my_db;
$session->open();
It is a very basic example of how to do this.
Afterwards you can just use it like a normal session like so:
$_SESSION['user_id'] = $id;
I have following model and controller. And database table pages has id, title, content and slug.
Q1. Why does the line in controller,
$this->load->model("pagemodel", 'pages'); // Load the page model,
have 'pages'?
Is it naming "pagemodel" as pages?
And I see a line,
$page_data = $this->pages->fetch($page_slug); // Pull the page data from the database
using pages.
Model code
<?php
class Pagemodel extends Model
{
/**
* Constructor
*/
function Pagemodel()
{
parent::Model();
}
/**
* Return an array of pages — used in the manage view
*
* #access public
* #return array
*/
function pages()
{
$query = $this->db->query("SELECT * FROM `pages` ORDER BY `id` ASC");
return $query->result_array();
}
/**
* Return a list of a single page — used when editing a page
*
* #access public
* #param integer
* #return array
*/
function page($id)
{
$query = $this->db->query("SELECT * FROM `pages` WHERE `id` = '$id' LIMIT 1");
return $query->result_array();
}
/**
* Return an array of a page — used in the front end
*
* #access public
* #param string
* #return array
*/
function fetch($slug)
{
$query = $this->db->query("SELECT * FROM `pages` WHERE `slug` = '$slug'");
return $query->result_array();
}
/**
* Add a record to the database
*
* #access public
* #param array
*/
function add($data)
{
$this->db->query("INSERT INTO `pages` (`title`, `content`, `slug`) VALUES (".$this->db->$data['title'].", ".$this->db->$data['content'].", ".$this->db->escape($data['slug']).")");
}
/**
* Update a record in the database
*
* #access public
* #param integer
* #param array
*/
function edit($id, $data)
{
$this->db->query("UPDATE `pages` SET `title` = ".$this->db->escape($data['title']).", `content` = ".$this->db->escape($data['content']).", `slug` = ".$this->db->escape($data['slug'])." WHERE `id` = '$id'");
}
/**
* Remove a record from the database
*
* #access public
* #param integer
*/
function delete($id)
{
$this->db->query("DELETE FROM `pages` WHERE `id` = '$id'");
}
}
?>
Controller code
<?php
class Page extends Application
{
function Page()
{
parent::Application();
$this->load->model("pagemodel", 'pages'); // Load the page model
}
function _view($page, $page_data)
{
$meta = array (
'meta_title' => 'title here',
'meta_keywords' => 'keywords here',
'meta_description' => 'description here',
'meta_robots' => 'all',
'extra_headers' => '
<script language="javascript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
'
);
$data = array();
// add any data
// merge meta and data
$data = array_merge($data,$meta);
// load view with data
$this->load->view('header', $data);
$this->load->view($page, $page_data);
$this->load->view('footer');
}
function index()
{
$page_slug = $this->uri->segment('2'); // Grab the URI segment
if($page_slug === FALSE)
{
$page_slug = 'home'; //Change home if you change the name in the back-end
}
$page_data = $this->pages->fetch($page_slug); // Pull the page data from the database
if($page_data === FALSE)
{
show_404(); // Show a 404 if no page exists
}
else
{
$this->_view('index', $page_data[0]);
}
}
}
?>
From system/libraries/Loader.php
/**
* Model Loader
*
* This function lets users load and instantiate models.
*
* #access public
* #param string the name of the class
* #param string name for the model
* #param bool database connection
* #return void
*/
function model($model, $name = '', $db_conn = FALSE)
{
...
So yes, the second parameter is just setting a 'friendly' name for the model, and is not needed. It adds a layer of confusion in my opinion.
You are probably right, try renaming 'pages' and I bet it's not available anymore by calling
$this->pages in your controller code.