How to display total mysql database tables size in view page (Codeigniter) - codeigniter

How to make this code work on Codeigniter by echo total mysql database tabels Size?
SELECT table_schema "Data Base Name",
sum( data_length + index_length ) / 1024 /
1024 "Data Base Size in MB",
sum( data_free )/ 1024 / 1024 "Free Space in MB"
FROM information_schema.TABLES
GROUP BY table_schema;
This is how to echo total mysql database tabels Rows:
<?php
$sqlx = $this->db->list_tables();
$finalCount = 0;
foreach ($sqlx as $table) {
$counteachrow = $this->db->count_all_results($table);
$finalCount += $counteachrow;
}
?>
<?php echo $finalCount; ?>

Create new model
<?php
class Database_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function get_database_size() {
$query = "SELECT table_schema 'Data Base Name', sum( data_length + index_length ) / 1024 / 1024 'Data Base Size in MB', sum( data_free )/ 1024 / 1024 'Free Space in MB'
FROM information_schema.TABLES
GROUP BY table_schema";
$result = $this->db->query($query);
return $result->result_array();
}
public function get_total_rows() {
$sqlx = $this->db->list_tables();
$finalCount = 0;
foreach ($sqlx as $table) {
$counteachrow = $this->db->count_all_results($table);
$finalCount += $counteachrow;
}
return $finalCount;
}
}
and to your controller
$database_size = $this->database_model->get_database_size();
$total_rows = $this->database_model->get_total_rows();

public function get_database_size() {
$sql = "SELECT table_schema AS db_name, round((sum(data_length + index_length) / 1024 / 1024), 2) AS db_size_mb FROM information_schema.TABLES WHERE table_schema = DATABASE() GROUP BY table_schema ;";
$query = $this->db->query($sql);
if ($query->num_rows() > 0) {
$row = $query->row();
$size = $row->db_size_mb;
return $size;
}
else
{
return false;
}
}

Related

Update Table without loops

There is a table foo and it has a column called fooPos. I ned to update the fooPos column with respect to id.
I have the following data
$id = [21,23,34,56,76];
$fooPos = [1,2,3,4,5];
How can I update this without using loops?
It's like 21(id) => 1(fooPos), 23 => 2, 34 =>3 etc.,
You have a solution with INSERT INTO ... ON DUPLICATE KEY UPDATE..., more details in here Multiple update
That solution can trigger an error if the ID doesn't exist and you have some other required fields. In that cas you ca use this solution:
$updateSets = [];
$ids = [21,23,34,56,76];
$fooPos = [1,2,3,4,5];
foreach ($ids as $key => $id) {
$updateSets[] = 'SELECT '.$id.' as set_id, '.$fooPos[$key].' as pos ';
}
$updateSetsString = implode(' UNION ALL ', $updateSets);
\DB::statement('UPDATE your_table JOIN ('.$updateSetsString.') up_set ON your_table.id = up_set.set_id SET your_table.pos = up_set.pos');
function updateTableWithoutQueryLoops()
{
try {
$id = collect([21,23,34,56,76]);
$fooPos = collect([1,2,3,4,5]);
// To check both parameters should have an equal number of elements.
if(count($id) == count($fooPos) ) {
$combinedValues = $id->combine($fooPos);
} else {
return 'Please check equal number of elements for give arrays.';
}
// Run foreach loop of Combined values
foreach ($combinedValues as $id => $fooPos) {
$id = (int) $id;
$cases[] = "WHEN {$id} then ?";
$params[] = $fooPos;
$ids[] = $id;
}
$ids = implode(',', $ids);
$cases = implode(' ', $cases);
$params[] = \Carbon\Carbon::now();
return \DB::update("UPDATE `foo` SET `fooPos` = CASE `id` {$cases} END, `updated_at` = ? WHERE `id` in ({$ids})", $params);
} catch (\Exception $e) {
return 'Exception message:' . $e->getMessage() . ' with code: ' . $e->getCode();
}
}
function updateTableWithoutQueryLoops()
{
try {
$id = collect([21,23,34,56,76]);
$fooPos = collect([1,2,3,4,5]);
// To check both parameters should have an equal number of elements.
if(count($id) == count($fooPos) ) {
$combinedValues = $id->combine($fooPos);
} else {
return 'Please check equal number of elements for give arrays.';
}
// Run foreach loop of Combined values
foreach ($combinedValues as $id => $fooPos) {
$id = (int) $id;
$cases[] = "WHEN {$id} then ?";
$params[] = $fooPos;
$ids[] = $id;
}
$ids = implode(',', $ids);
$cases = implode(' ', $cases);
$params[] = \Carbon\Carbon::now();
return \DB::update("UPDATE `foo` SET `fooPos` = CASE `id` {$cases} END, `updated_at` = ? WHERE `id` in ({$ids})", $params);
} catch (\Exception $e) {
return 'Exception message:' . $e->getMessage() . ' with code: ' . $e->getCode();
}
}

external classes and PHP files in Laravel - Class not found

I have two php files and I already created a folder called "ExternalClasses" and added the file to that folder. In my php file, I add this line:
namespace App\ExternalClasses;
and in my controller I add this line:
use App\ExternalClasses\CCheckMail;
and this is how I use it:
$pricesClass = new CCheckMail();
$email2 = ['myemail#gmail.com'];
$prices = $pricesClass->execute ($email2);
return view('pages.home', compact('prices'));
but it gave me an error:
Symfony \ Component \ Debug \ Exception \ FatalThrowableError
(E_ERROR) Class 'App\ExternalClasses\CCheckMail' not found
Here is my php file (CCheckMail.php):-
<?php
namespace App\ExternalClasses;
/*
* This script was writed by Setec Astronomy - setec#freemail.it
*
* This script is distributed under the GPL License
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* http://www.gnu.org/licenses/gpl.txt
*
*/
define ('DEBUG_OK', false);
class CCheckMail
{
var $timeout = 10;
var $domain_rules = array ("aol.com", "bigfoot.com", "brain.net.pk", "breathemail.net",
"compuserve.com", "dialnet.co.uk", "glocksoft.com", "home.com",
"msn.com", "rocketmail.com", "uu.net", "yahoo.com", "yahoo.de");
function _is_valid_email ($email = "")
{ return preg_match('/^[.\w-]+#([\w-]+\.)+[a-zA-Z]{2,6}$/', $email); }
function _check_domain_rules ($domain = "")
{ return in_array (strtolower ($domain), $this->domain_rules); }
function execute ($email = "")
{
if (!$this->_is_valid_email ($email))
{ return false; }
$host = substr (strstr ($email, '#'), 1);
if ($this->_check_domain_rules ($host))
{ return false; }
$host .= ".";
if (getmxrr ($host, $mxhosts[0], $mxhosts[1]) == true)
{ array_multisort ($mxhosts[1], $mxhosts[0]); }
else
{
$mxhosts[0] = $host;
$mxhosts[1] = 10;
}
if (DEBUG_OK) { print_r ($mxhosts); }
$port = 25;
$localhost = $_SERVER['HTTP_HOST'];
$sender = 'info#' . $localhost;
$result = false;
$id = 0;
while (!$result && $id < count ($mxhosts[0]))
{
if (function_exists ("fsockopen"))
{
if (DEBUG_OK) { print_r ($id . " " . $mxhosts[0][$id]); }
if ($connection = fsockopen ($mxhosts[0][$id], $port, $errno, $error, $this->timeout))
{
fputs ($connection,"HELO $localhost\r\n"); // 250
$data = fgets ($connection,1024);
$response = substr ($data,0,1);
if (DEBUG_OK) { print_r ($data); }
if ($response == '2') // 200, 250 etc.
{
fputs ($connection,"MAIL FROM:<$sender>\r\n");
$data = fgets($connection,1024);
$response = substr ($data,0,1);
if (DEBUG_OK) { print_r ($data); }
if ($response == '2') // 200, 250 etc.
{
fputs ($connection,"RCPT TO:<$email>\r\n");
$data = fgets($connection,1024);
$response = substr ($data,0,1);
if (DEBUG_OK) { print_r ($data); }
if ($response == '2') // 200, 250 etc.
{
fputs ($connection,"data\r\n");
$data = fgets($connection,1024);
$response = substr ($data,0,1);
if (DEBUG_OK) { print_r ($data); }
if ($response == '2') // 200, 250 etc.
{ $result = true; }
}
}
}
fputs ($connection,"QUIT\r\n");
fclose ($connection);
if ($result) { return true; }
}
}
else
{ break; }
$id++;
}
return false;
}
}
?>
The second php file:
<?php
/*
* This script was writed by Setec Astronomy - setec#freemail.it
*
* On row 41 of CCheckMail.php substitute the following line
*
* if (getmxrr ($host, $mxhosts[0], $mxhosts[1]) == true)
*
* with
*
* if (getmxrr_portable ($host, $mxhosts[0], $mxhosts[1]) == true)
*
* to have a fully working portable (*nix and Windows) CCheckMail class
*
* This script is distributed under the GPL License
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* http://www.gnu.org/licenses/gpl.txt
*
*/
function getmxrr_win ($hostname = "", &$mxhosts, &$weight)
{
$weight = array();
$mxhosts = array();
$result = false;
$command = "nslookup -type=mx " . escapeshellarg ($hostname);
exec ($command, $result);
$i = 0;
while (list ($key, $value) = each ($result))
{
if (strstr ($value, "mail exchanger"))
{ $nslookup[$i] = $value; $i++; }
}
while (list ($key, $value) = each ($nslookup))
{
$temp = explode ( " ", $value );
$mx[$key][0] = substr($temp[3],0,-1);
$mx[$key][1] = $temp[7];
$mx[$key][2] = gethostbyname ( $temp[7] );
}
array_multisort ($mx);
foreach ($mx as $value)
{
$mxhosts[] = $value[1];
$weight[] = $value[0];
}
$result = count ($mxhosts) > 0;
return $result;
}
function getmxrr_portable ($hostname = "", &$mxhosts, &$weight)
{
if (function_exists ("getmxrr"))
{ $result = getmxrr ($hostname, $mxhosts, $weight); }
else
{ $result = getmxrr_win ($hostname, $mxhosts, $weight); }
return $result;
}
?>
Just type composer dumpautoload -o in your terminal.
It was typing error, I created a new project and redo my coding and it's working fine.

CodeIgniter - get row from table where id is id of array

I have one table korisnik with 3 columns (id, username, password).
I want some like:
$upit = "SELECT * FROM korisnik WHERE username = '" . $_POST['username'] . "'
AND password = SHA1('" . $_POST['password'] . "')";
$temp = $upit->fetch(PDO::FETCH_ASSOC);
$_SESSION['id'] = $temp['id'];
if ($pdo_izraz->num_rows() == 1) {
session_start();
$_SESSION['autorizovan'] = 1;
$temp = $pdo_izraz->fetch(PDO::FETCH_ASSOC);
$_SESSION['id'] = $temp['id'];
$upit = ("Select * from korisnici where id=" . $_SESSION['id']);*
$izraz = $dbh->query($upit);
$obj = $izraz->fetch(PDO::FETCH_ASSOC);
$username = $obj['username'];
echo "<p id='bbb'><b >$username</b>:Welcome</p>";
I want to do something like this in CodeIgniter (to get one row where id=array of one row ($_SESSION['id']
I think you are looking for result_array()
see the manual here
$query = $this->db->query("YOUR QUERY");
foreach ($query->result_array() as $row)
{
echo $row['title'];
echo $row['name'];
echo $row['body'];
}
UPDATE
public function login($user, $pass) // Takeing the username/pass from form
{
$this->db->where('username', $user);
$this->db->where('password', md5($pass));
$query = $this->db->get('korisnici');
if ($query->num_rows() == 1)
{
$_SESSION['id'] = $this->query->row()->id;
return TRUE;
}
else
{
return FALSE;
}
}
public function getData()//Get result of array
{
$this->db->where('id', $_SESSION['id']);
$query = $this->db->get('korisnici');
return $query->result(); // here you can change for result_array() if you want
}

how to use this simple acl library into codeigniter

i used cakephp before and now use codeigniter but Unfortunately hasn't any authentication or ACL built-in library ..after more search i have found a good library, but I do not know how to use it..it is no example to use it..any one have create controller and model as sample...thanks for helping
<?php
(defined('BASEPATH')) OR exit('No direct script access allowed');
class acl {
/* Actions::::
* Create 1
* Read 2
* Update 4
* Delete 8
* The allowance is made by a sum of the actions allowed.
* Ex.: user can read and update (2+4)=6 … so ill put 6 instead of 1 or 0.
*
* if(!$this->acl->hasPermission(‘entries_complete_access')) {
echo “No no”;
} else
* echo “yeah”;
}
*
*
*/
var $perms = array(); //Array : Stores the permissions for the user
var $userID; //Integer : Stores the ID of the current user
var $userRoles = array(); //Array : Stores the roles of the current user
var $ci;
function __construct($config = array()) {
$this->ci = &get_instance();
$this->userID = floatval($this->ci->session->userdata('account_id'));
$this->userRoles = $this->getUserRoles();
$this->buildACL();
}
function buildACL() {
//first, get the rules for the user's role
if (count($this->userRoles) > 0) {
$this->perms = array_merge($this->perms, $this->getRolePerms($this->userRoles));
}
//then, get the individual user permissions
$this->perms = array_merge($this->perms, $this->getUserPerms($this->userID));
}
function getPermKeyFromID($permID) {
//$strSQL = “SELECT `permKey` FROM `”.DB_PREFIX.”permissions` WHERE `ID` = ” . floatval($permID) . ” LIMIT 1″;
$this->ci->db->select('permKey');
$this->ci->db->where('id', floatval($permID));
$sql = $this->ci->db->get('perm_data', 1);
$data = $sql->result();
return $data[0]->permKey;
}
function getPermNameFromID($permID) {
//$strSQL = “SELECT `permName` FROM `”.DB_PREFIX.”permissions` WHERE `ID` = ” . floatval($permID) . ” LIMIT 1″;
$this->ci->db->select('permName');
$this->ci->db->where('id', floatval($permID));
$sql = $this->ci->db->get('perm_data', 1);
$data = $sql->result();
return $data[0]->permName;
}
function getRoleNameFromID($roleID) {
//$strSQL = “SELECT `roleName` FROM `”.DB_PREFIX.”roles` WHERE `ID` = ” . floatval($roleID) . ” LIMIT 1″;
$this->ci->db->select('roleName');
$this->ci->db->where('id', floatval($roleID), 1);
$sql = $this->ci->db->get('role_data');
$data = $sql->result();
return $data[0]->roleName;
}
function getUserRoles() {
//$strSQL = “SELECT * FROM `”.DB_PREFIX.”user_roles` WHERE `userID` = ” . floatval($this->userID) . ” ORDER BY `addDate` ASC”;
$this->ci->db->where(array('userID' => floatval($this->userID)));
$this->ci->db->order_by('addDate', 'asc');
$sql = $this->ci->db->get('user_roles');
$data = $sql->result();
$resp = array();
foreach ($data as $row) {
$resp[] = $row->roleID;
}
return $resp;
}
function getAllRoles($format = 'ids') {
$format = strtolower($format);
//$strSQL = “SELECT * FROM `”.DB_PREFIX.”roles` ORDER BY `roleName` ASC”;
$this->ci->db->order_by('roleName', 'asc');
$sql = $this->ci->db->get('role_data');
$data = $sql->result();
$resp = array();
foreach ($data as $row) {
if ($format == 'full') {
$resp[] = array('id' => $row->ID, 'name' => $row->roleName);
} else {
$resp[] = $row->ID;
}
}
return $resp;
}
function getAllPerms($format = 'ids') {
$format = strtolower($format);
//$strSQL = “SELECT * FROM `”.DB_PREFIX.”permissions` ORDER BY `permKey` ASC”;
$this->ci->db->order_by('permKey', 'asc');
$sql = $this->ci->db->get('perm_data');
$data = $sql->result();
$resp = array();
foreach ($data as $row) {
if ($format == 'full') {
$resp[$row->permKey] = array('id' => $row->ID, 'name' => $row->permName, 'key' => $row->permKey);
} else {
$resp[] = $row->ID;
}
}
return $resp;
}
function getRolePerms($role) {
if (is_array($role)) {
//$roleSQL = “SELECT * FROM `”.DB_PREFIX.”role_perms` WHERE `roleID` IN (” . implode(“,”,$role) . “) ORDER BY `ID` ASC”;
$this->ci->db->where_in('roleID', $role);
} else {
//$roleSQL = “SELECT * FROM `”.DB_PREFIX.”role_perms` WHERE `roleID` = ” . floatval($role) . ” ORDER BY `ID` ASC”;
$this->ci->db->where(array('roleID' => floatval($role)));
}
$this->ci->db->order_by('id', 'asc');
$sql = $this->ci->db->get('role_perms'); //$this->db->select($roleSQL);
$data = $sql->result();
$perms = array();
foreach ($data as $row) {
$pK = strtolower($this->getPermKeyFromID($row->permID));
if ($pK == '') {
continue;
}
/* if ($row->value == '1′) {
$hP = true;
} else {
$hP = false;
} */
if ($row->value == '0') {
$hP = false;
} else {
$hP = $row->value;
}
$perms[$pK] = array('perm' => $pK, '1inheritted' => true, 'value' => $hP, 'name' => $this->getPermNameFromID($row->permID), 'id' => $row->permID);
}
return $perms;
}
function getUserPerms($userID) {
//$strSQL = “SELECT * FROM `”.DB_PREFIX.”user_perms` WHERE `userID` = ” . floatval($userID) . ” ORDER BY `addDate` ASC”;
$this->ci->db->where('userID', floatval($userID));
$this->ci->db->order_by('addDate', 'asc');
$sql = $this->ci->db->get('user_perms');
$data = $sql->result();
$perms = array();
foreach ($data as $row) {
$pK = strtolower($this->getPermKeyFromID($row->permID));
if ($pK == '') {
continue;
}
/* if ($row->value == '1′) {
$hP = true;
} else {
$hP = false;
} */
if ($row->value == '0') {
$hP = false;
} else {
$hP = $row->value;
}
$perms[$pK] = array('perm' => $pK, '2inheritted' => false, 'value' => $hP, 'name' => $this->getPermNameFromID($row->permID), 'id' => $row->permID);
}
return $perms;
}
function hasRole($roleID) {
foreach ($this->userRoles as $k => $v) {
if (floatval($v) === floatval($roleID)) {
return true;
}
}
return false;
}
function actionPerm($value, $wanted) {
/* Actions::::
* Create 1
* Read, 2
* Update, 4
* Delete 8
*/
$action['create'] = array('1', '3', '5', '9', '11', '13', '15'); //1
$action['read'] = array('2', '3', '6', '10', '14', '15'); //2
$action['update'] = array('4', '5', '6', '7', '12', '13', '14', '15'); //4
$action['delete'] = array('8', '9', '10', '11', '12', '13', '14', '15'); //8
$action['all'] = array('15');
if (in_array($value, $action[$wanted], true)) {
return true;
} else {
return false;
}
}
function hasPermission($permKey, $action = 'all') {
$permKey = strtolower($permKey);
if (array_key_exists($permKey, $this->perms)) {
if ($this->actionPerm($this->perms[$permKey]['value'], $action)) {
return true;
} else {
return false;
}
} else {
return false;
}
/* OLD METHOD
if ($this->perms[$permKey]['value'] === '1′ || $this->perms[$permKey]['value'] === true)
{
return true;
} else {
return false;
}
} else {
return false;
}
*/
}
}
and this is the url
sample ACL Class for codeigniter
This is simple
Load it first in your controller
$this->load->library('acl');
Now call its method
$this->acl->buildACL();
EDIT
Use these for menuall assigning
$this->acl->perms = array('your values');
$this->acl->userID= 'user id';
$this->acl->userRoles = array('your values');
Note that you should have db table userRoles which will be invoked when the library is initialized getUserRoles method will be called and $userRoles parameter will have values.
I'm Brian from Tastybytes. My best solution would be to step through the tutorial that the code igniter ACL library is based on. It is a 100% straight port from the base php files to CI Library.
http://net.tutsplus.com/tutorials/php/a-better-login-system/
And possibly look at the very bottom of the page where I go through "Installation" and what not.

How to fix this issue with advanced search codeigniter

I want to build advanced search script but I have this error with search_all function in the model
A PHP Error was encountered
Severity: 4096
Message: Object of class CI_DB_mysql_result could not be converted to string
Filename: models/search_model.php
Line Number: 129
i have four fildes
1- input text to write the book name
2- select box for the author
3- select box for the publisher
3-select box for the section
the model is
class search_model extends CI_Model
{
function __construct()
{
parent::__construct();
}
/* This function get all search in database sort by order asc.*/
function get_new_one($id)
{
$this->db->where('ne_id',$id);
$result=$this->db->get('d_search');
return $result->row();
}
//////////////frontend//////////////////////////////////////////////////////////
function show_new($id)
{
$result=$this->db->query("SELECT * , COUNT( d_comments_search.cn_new_id ) as count
FROM d_search
left JOIN d_comments_search ON d_search.ne_id = d_comments_search.cn_new_id and d_search.ne_hide='1'
inner join d_search_category on d_search_category.nc_id = d_search.ne_category_id and d_search_category.nc_hide= '1'
and d_search.ne_id= $id group by d_search.ne_id");
return $result->row() ;
}
function generate_results($keyword,$row=0){
$result1 = $this->db->query("SELECT bo_id,bo_name,bo_state,bo_about FROM d_book where (bo_name like '%$keyword%' or bo_about like '%$keyword%') and bo_state = '1' limit $row,20");
$result2 = $this->db->query("SELECT au_id,au_name,au_state,au_info FROM d_author where (au_name like '%$keyword%' or au_info like '%$keyword%') and au_state = '1' limit $row,20");
$result3 = $this->db->query("SELECT pub_id,pub_name,pub_state,pub_info FROM d_publishing where (pub_name like '%$keyword%' or pub_info like '%$keyword%') and pub_state = '1' limit $row,20");
$results = array_merge($result1->result_array(),$result2->result_array(),$result3->result_array());
return $results;
}
// get total number of users
function getNumUsers($keyword)
{
$result1 = $this->db->query("SELECT bo_id,bo_name,bo_state,bo_about FROM d_book where (bo_name like '%$keyword%' or bo_about like '%$keyword%') and bo_state = '1'");
$result1 = $result1->num_rows();
$result2 = $this->db->query("SELECT au_id,au_name,au_state,au_info FROM d_author where (au_name like '%$keyword%' or au_info like '%$keyword%') and au_state = '1'");
$result2 = $result2->num_rows();
$result3 = $this->db->query("SELECT pub_id,pub_name,pub_state,pub_info FROM d_publishing where (pub_name like '%$keyword%' or pub_info like '%$keyword%') and pub_state = '1'");
$result3 = $result3->num_rows();
return $result1 + $result2 + $result3;
}
//////////////////////////////////end paging///////////////////
function get_publishing()
{
$this->db->where('pub_state','1');
$result=$this->db->get('d_publishing')->result_array();
return $result;
}
function get_author()
{
$this->db->where('au_state','1');
$result=$this->db->get('d_author')->result_array();
return $result;
}
function get_section()
{
$this->db->where('sec_state','1');
$result=$this->db->get('d_section')->result_array();
return $result;
}
function search_name()
{
$bo_name=$_POST['bo_name'];
$this->db->order_by("bo_ord","asc");
$this->db->like('bo_name',$bo_name);
return $this->db->get('d_book')->result_array();
}
function search_all() {
$publish = $this->input->post('publish');
$author = $this->input->post('author');
$sec_name = $this->input->post('section');
$sql = $this->db->query("SELECT * FROM `d_book`");
$searches = array();
if ($publish != 'choose')
$searches[] = "`bo_pub_id` = '$publish'";
if ($author != 'choose')
$searches[] = "`bo_au_id` = '$author'";
if ($sec_name != 'choose')
$searches[] = "`bo_sec_id` = '$sec_name'";
if (count($searches) > 0) {
$sql .= "WHERE " . implode(" AND ", $searches);
}
$sql .= ';';
}
}
this is controller
class Search extends front_end {
var $temp;
function __construct(){
parent::__construct();
$this->load->library('form_validation');
//echo $this->input->post("keyboard");
}
public function index()
{
$this->overview();
}
/**
* This function display all search
* #param integer $row
*/
public function overview($row=0)
{
$this->form_validation->set_rules('keyword', 'كلمة البحث', 'trim|required|xss_clean|htmlspecialchars');
$this->form_validation->run();
$this->store_keyword();
//echo $this->session->flashdata('keyword');
if ($this->session->flashdata('keyword') != ''){
$keyword=$this->session->flashdata('keyword');
$this->generate_results($this->session->flashdata('keyword'),$row);
}else{
$this->generate_results($this->input->post("keyword"),$row);
}
//$this->session->set_flashdata('keyword', $this->input->post("keyword"));
$data = $this->temp;
//$this->session->keep_flashdata('keyword');
$this->view('search/site/results', $data);
}
/**
* This function generate result of search
* #param string $keyword
* #param integer $row
*/
public function generate_results($keyword,$row=0){
$this->load->model('search/search_model','search');
$this->load->library('pagination');
$config['base_url'] = base_url().'search/search/overview/';
$config['total_rows'] = $this->search->getNumUsers($keyword);
$config['per_page'] = '20';
$config['uri_segment'] = '4';
$this->pagination->initialize($config);
$data['page'] = $row;
$data['results'] = $this->search->generate_results($keyword,$row);
$data['total_rows'] = $this->search->getNumUsers($keyword);
$data['links']=$this->pagination->create_links();
$this->temp = $data;
}
/**
* This function display detail of new
* #param integer $id
*/
public function show($id)
{
$data['new']=$this->search->show_new($id);
$count=$data['new']->ne_count_visit;
$this->search->add_count($count,$id);
$data['comments']=$this->search->show_comments($id);
$this->view('site/new', $data);
}
/**
* This function store keyword to use in search
*/
private function store_keyword(){
if($this->input->post("keyword")){
$this->session->set_userdata('keyword', $this->input->post("keyword"));
}
}
public function search_form()
{
$this->load->model('search/search_model','search');
$data['publish']=$this->search->get_publishing();
$data['author']=$this->search->get_author();
$data['section']=$this->search->get_section();
$this->view('search/site/adv_search_form',$data);
}
public function search_adv()
{
$this->load->model('search/search_model','search');
$data['bo_name']=$this->input->post('bo_name');
$data['section']=$this->input->post('section');
$data['publish']=$this->input->post('publish');
$data['author']=$this->input->post('author');
$data['result1'] = '';
$data['result2'] = '';
$data['result3'] = '';
$data['result4'] = '';
if($data['bo_name'] == NULL and $data['section']== NULL and $data['publish']==NULL and $data['author']== NULL){
$this->search_form();
}else{
if(isset($data['bo_name']) and $data['bo_name']!= NULL)
{
$data['result1'] = $this->search->search_name();
}
if(isset($data['section']) and $data['section'] != NULL)
{
$data['result2']=$this->search->search_all();
}
if(isset($data['publish']) and $data['publish'] != NULL)
{
$data['result3']=$this->search->search_all();
}
if(isset($data['author']) and $data['author']!= NULL)
{
$data['result4']=$this->search->search_all();
}
$data['no_results'] = '';
if(! $data['result1'] && !$data['result2'] && !$data['result3'] && !$data['result4']){
$data['no_results'] = TRUE;
}else{
$data['no_results'] = FALSE;
}
$this->view('search/site/search_result',$data);
}
}
}
/* End of file dashboard.php */
$this->db->query() doesn't store a query string for later use. It actually executes the query right away and return an object of CI_DB_mysql_result. You should build the query string before you call $this->db->query() and store it into a variable, then pass it into the method.
$sql = "SELECT * FROM `d_book` ";
$searches = array();
if ($publish != 'choose')
{
$searches[] = "`bo_pub_id` = '__some_id__'";
}
if ($author != 'choose')
{
$searches[] = "`bo_au_id` = '__some_id__'";
}
if ($sec_name != 'choose')
{
$searches[] = "`bo_sec_id` = '__some_id__'";
}
if (count($searches) > 0)
{
$sql .= "WHERE " . implode(" AND ", $searches);
}
$sql .= ';';
$this->db->query($sql);

Resources