How to add new field to codeigniter? - codeigniter

I want to add new field on my model, but I can't do it. Can anyone help me?
This my function on my model:
public function get_item(){
$default_language = setting_value('default_language');
$query = $this->db->order_by('p.id','desc')
->select("p.* , c.name as item_name, a.name as category_name")
->join("content_to_" . $this->url ." c", "c.item_id = p.id" , "left")
->join("content_to_item_category a", "p.item_category_id = a.item_category_id" , "left")
->get_where($this->url ." p",array('c.language_id'=> $default_language,'a.language_id'=> $default_language, 'p.flag !=' => 3))->result_array();
return $query;
}

use database forge for this purpose.
Here is the documentation of DB FORGE
i hope this will work !

Related

codeigniter : Commands out of sync; you can't run this command now

I applied all the possible answers but still same problem.
also tried
$this->db->reconnect();
there is no problem in my query
MyCode:
public function GetdistributorsDetails($username){
$sql = "SELECT u.FirstName, u.Email, u.Telephone, u.MobileNumber, u.AlternateMobileNumber, ud.Address1, ud.Pincode,ud.City,s.Statename FROM users u JOIN userdetails ud ON ud.UserId = u.UserId JOIN states s ON s.StateId = ud.StateId WHERE u.Username = ? ";
$result = $this->db->query($sql,array($username));
return $result->result_array();
}
add following code into /system/database/drivers/mysqli/mysqli_result.php
function next_result()
{
if (is_object($this->conn_id))
{
return mysqli_next_result($this->conn_id);
}
}
then in model when you call Stored Procedure
$query = $this->db->query("CALL test()");
$res = $query->result();
//add this two line
$query->next_result();
$query->free_result();
//end of new code
return $res;
you can use this after call
mysqli_next_result( $this->db->conn_id );
Here is example if you don't want change any thing in mysqli drivers files
$sql = "CALL procedureName(IntParam,'VarcharParm1','VaracharParm2','VarcharParm3');";
$query = $this->db->query($sql);
mysqli_next_result( $this->db->conn_id );
$query->free_result();
these are important line place after to remove the error
mysqli_next_result( $this->db->conn_id );
$query->free_result();
Just use this one if you use multiple query make in same function:
$this->db->close();
If your stored procedure returns more than one result, try to add this code between the queries:
$storedProcedure = 'CALL test(inputParam, #outputParam)';
$this->db->query($storedProcedure);
$conn = $this->db->conn_id;
do {
if ($result = mysqli_store_result($conn)) {
mysqli_free_result($result);
}
} while (mysqli_more_results($conn) && mysqli_next_result($conn));
$sql = 'SELECT #outputParam;';
$this->db->query($sql);
Just add next_result function in
system\database\drivers\mysqli\mysqli_result.php file
public function next_result(){
if(is_object($this->conn_id) && mysqli_more_results($this->conn_id)){
return mysqli_next_result($this->conn_id);
}
}
To call query function
$result = $this->db->query("CALL {$Name}({$Q})",$Param);
$result->next_result();
return $result;

laravel eloquent multiple record hasMany

return Store::whereRaw('status = 1 AND ' . 'pay_status = 1 AND ' . $conditions[0])
->storeBooks()
->whereRaw('status = 1 AND ' . $conditions[1])
->search($request->input('search'), null, true)
->simplePaginate(20)
->makeHidden(['description', 'publisher', 'edition', 'mobile', 'cat_title', 'city_name']);
Hi, I have an store table and this table has some book in store_books table.
i want to search in store books where store has status 1.
I wrote above code but not work.
anyone can help me? Please!
Thanks
You can try this
In your Store model
public function books()
{
return $this->hasMany("App\StoreBooks",'store_id');
}
In your controller's function
$results = [];
$stores = Store::where('status',1)->get();
foreach($stores as $store)
{
$books = $stores->books;
foreach($books as $book)
{
$results[] = $book;
}
}
return $results;

I need help Select Sum in codeigniter

I need help to help me correct my php function in codeigniter.
I have a database; I want addirionner all values ​of " from_user_id ".
Check data
I use this sql to get the desired result.
SELECT SUM(kiff_envoi+kiff_recu+visite_recu+profile_visite+da_recu+da_envoi+topic_poster+repon_topic+conv_envoi+conv_recu) AS total_stats FROM score WHERE from_user_id = ?
In codeingniter I​ use this function.
It allows me to check if " from_user_id " exists, if it exists, we calculate the total different tables and we update the result in " total_stats ". If " from_user_id " does not exist, create it.
But my function does not return me the right result.
I had to make a big mistake but I do not know where!
Does someone could help me please.
public function count_tout_stats($user_id) //total des stats
{
$this->db->select_sum(conv_recu, conv_envoi, repon_topic, etc...);
$query = $this->db->from('score');
$this->db->where('from_user_id', $user_id);
$total_stats = $this->db->count_all_results();
if ($this->ttl_stats_score($user_id) > 0) // Check if exists
{
$data = array(
'total_stats' => $total_stats
);
$this->db->where('from_user_id', $user_id);
$this->db->update('score', $data);
}
else
{
$data = array(
'from_user_id' => $user_id,
'total_stats' => $total_stats
);
$this->db->insert('score', $data);
}
return $total_stats;
}
public function ttl_stats_score($user_id)
{
$this->db->where('from_user_id', $user_id);
$this->db->from('score');
return $this->db->count_all_results();
}
Thank you in advance for your assistance
Violette
You can try this:
$this->db->select('(kiff_envoi+kiff_recu+visite_recu+profile_visite+da_recu+da_envoi+topic_poster+repon_topic+conv_envoi+conv_recu) as total_stats');
$this->db->from('score');
$this->db->where('from_user_id', $user_id);
$result = $this->db->get()->row_array();
print_r($result);
You will get your result

Laravel how to get query with bindings?

I have some query that I need to pass to another query using query builder
$query = DB::table('table')->whereIn('some_field', [1,2,30])->toSql();
Model::join(DB::raw("({$query}) as table"), function($join) {
$join->on('model.id', '=', 'table.id');
})
which should results with
Select * from model join (select * from table where some_field in (1,2,30)) as table on model.id = table.id
but the bindings are not passed, which force me to do
$query = DB::table('table')->whereRaw('some_field in ('. join(',', [1,2,30]) .')')->toSql();
what can be unsafe at times. How can I get the query with bindings?
Check out the getBindings() method on the Builder class
getBindings()
$query = DB::table('table')->whereIn('some_field', [1,2,30]);
$sql = $query->toSql();
$bindings = $query->getBindings();
Laravel now offers debugging directly on your Builder!!!
https://laravel.com/docs/queries#debugging
\App\User::where('age', '18')->dump();
\App\User::where('age', '18')->dd();
Outputs
"select * from `users` where `age` = ?"
[
0 => "18"
]
public static function getQueries(Builder $builder)
{
$addSlashes = str_replace('?', "'?'", $builder->toSql());
return vsprintf(str_replace('?', '%s', $addSlashes), $builder->getBindings());
}
You can define below code block as helper function and use wherever required.
It will bind numeric as well as string value with quotations.
public static function getSqlWithBindings($query)
{
return vsprintf(str_replace('?', '%s', $query->toSql()), collect($query->getBindings())->map(function ($binding) {
return is_numeric($binding) ? $binding : "'{$binding}'";
})->toArray());
}
Example:
$query = Document::where('model', 'contact')->where('model_id', '1');
dd(Document::getSqlWithBindings($query));
Output:
"select * from `document` where `model` = 'contact' and `model_id` = 1"
Building upon Douglas.Sesar's answer.
I found I also needed to put the bindings in single quotations to be able to easily paste it into my database IDE.
$sql = $query->toSql();
$bindings = $query->getBindings();
$sql_with_bindings = preg_replace_callback('/\?/', function ($match) use ($sql, &$bindings) {
return json_encode(array_shift($bindings));
}, $sql);
$sqlQuery = Str::replaceArray(
'?',
collect($query->getBindings())
->map(function ($i) {
if (is_object($i)) {
$i = (string)$i;
}
return (is_string($i)) ? "'$i'" : $i;
})->all(),
$query->toSql());
The following function ensures the resulting SQL doesn't confuse bindings with columns by enclosing the ? to be '?'
public static function getFinalSql($query)
{
$sql_str = $query->toSql();
$bindings = $query->getBindings();
$wrapped_str = str_replace('?', "'?'", $sql_str);
return str_replace_array('?', $bindings, $wrapped_str);
}
If you want to get an executed query including bindings from the query log:
\DB::enableQueryLog();
\DB::table('table')->get();
dd(str_replace_array('?', \DB::getQueryLog()[0]['bindings'],
\DB::getQueryLog()[0]['query']));
I created this function. It is partial, might be parameters which are not covered, for me it was enough.
More than welcomed to add your improvements in a comment!
function getFullSql($query) {
$sqlStr = $query->toSql();
foreach ($query->getBindings() as $iter=>$binding) {
$type = gettype($binding);
switch ($type) {
case "integer":
case "double":
$bindingStr = "$binding";
break;
case "string":
$bindingStr = "'$binding'";
break;
case "object":
$class = get_class($binding);
switch ($class) {
case "DateTime":
$bindingStr = "'" . $binding->format('Y-m-d H:i:s') . "'";
break;
default:
throw new \Exception("Unexpected binding argument class ($class)");
}
break;
default:
throw new \Exception("Unexpected binding argument type ($type)");
}
$currentPos = strpos($sqlStr, '?');
if ($currentPos === false) {
throw new \Exception("Cannot find binding location in Sql String for bundung parameter $binding ($iter)");
}
$sqlStr = substr($sqlStr, 0, $currentPos) . $bindingStr . substr($sqlStr, $currentPos + 1);
}
$search = ["select", "distinct", "from", "where", "and", "order by", "asc", "desc", "inner join", "join"];
$replace = ["SELECT", "DISTINCT", "\n FROM", "\n WHERE", "\n AND", "\n ORDER BY", "ASC", "DESC", "\n INNER JOIN", "\n JOIN"];
$sqlStr = str_replace($search, $replace, $sqlStr);
return $sqlStr;
}
You can do something like this:
$escapedBindings = array();
foreach($query->getBindings() as $item) {$escapedBindings[] = '"'.$item.'"';}
$sql_with_bindings = Str::replaceArray('?', $escapedBindings, $query->toSql());
This is a very old question (2015), but since this is the first Google result I got I think it's worth to give my solution as well, in case it's useful for the next person.
Eloquent (5.7 onwards I think, I haven't tested more recent or earlier versions) has a method to change a Builder's from to wrap a subquery:
# Taken from Illuminate/Database/Query/Builder.php - Line 272
public function fromSub($query, $as) {
[$query, $bindings] = $this->createSub($query);
return $this->fromRaw('('.$query.') as '.$this->grammar->wrapTable($as), $bindings);
}
This however requires an already existing instance of \Illuminate\Database\Query\Builder. In order to make an empty one, you can do:
use Illuminate\Database\Capsule\Manager as DB;
$fancy = DB::table("videogames")->where("uses_sdl2", 1);
$empty = DB::table(null);
# Wrap the fancy query and set it as the "from" clause for the empty one
# NOTE: the alias is required
$empty = $empty->fromSub($fancy, "performant_games");
This will warranty that bindings are treated correctly, since they'll be handled by Eloquent itself.
Since the other answers do not properly quote the expressions, here is my approach. It uses the escaping function that belongs to the current database connection.
It replaces the question marks one by one with the corresponding binding, which is retrieved from $bindings via array_shift(), consuming the array in the process. Note, that $bindings has to be passed by reference for this to work.
function getSql($query)
{
$bindings = $query->getBindings();
return preg_replace_callback('/\?/', function ($match) use (&$bindings, $query) {
return $query->getConnection()->getPdo()->quote(array_shift($bindings));
}, $query->toSql());
}
Simple and elegant solution:
foreach (DB::getQueryLog() as $q) {
$queryStr = \Str::replaceArray('?', $q['bindings'], $q['query']);
echo $queryStr . ";\n";
}
(if you use a non-default connection, use DB::connection('yourConn')->getQueryLog() in the foreach command).
Output to the log all queries with inserted bindings sorted from the slowest query to the fastest:
\DB::enableQueryLog();
// Put here your queries
$query = DB::table('table')->whereIn('some_field', [1,2,30]);
$query2 = DB::table('table2')->where('some_field', '=', 10);
$logQueries = \DB::getQueryLog();
usort($logQueries, function($a, $b) {
return $b['time'] <=> $a['time'];
});
foreach ($logQueries as $item) {
\Log::info(str_replace_array('?', $item['bindings'], $item['query']));
\Log::info($item['time']. ' ms');
}
It is all explained here.....
https://ajcastro29.blogspot.com/2017/11/laravel-join-derived-tables-properly.html
I created a scope query for that thing. I think it can also be in macros..
public function scopeJoinDerived($query, $derivedQuery, $table, $one, $operator = null, $two = null, $type = 'inner', $where = false)
{
$query->join(DB::raw("({$derivedQuery->toSql()}) as `{$table}`"), $one, $operator, $two, $type, $where);
$join = last($query->getQuery()->joins);
$join->bindings = array_merge($derivedQuery->getBindings(), $join->bindings);
return $query;
}

Ignited+datatables -> order by

I'm using codeigniter with datatables and i want to order a select by a column.
How can i do that ?
$this->datatables->select('col_1, col_2, col_3');
$this->datatables->from('table');
....$this->datatables->order ?!?
Thanks
use:
$this->db->order_by("column name", "desc");
You can use the aaSorting parameter to order the table on initialization.
$(document).ready( function() {
$('#example').dataTable( {
"aaSorting": [[2,'asc'], [3,'desc']]
} );
} );
where 2 and 3 are column's index
You can use this way i am controlling here all required value with codeigniter DATA-TABLE and MYSQL select include a small joining
function get_ComponentList($rowperpage, $row, $search='',$order, $dir)
{
$this->db->select('a.component_id, a.component_name as component_name, a.eco_code as eco_code, b.component_name as parent_name');
$this->db->from('component_info as a');
$this->db->join('component_info as b', 'b.component_id = a.parent_id', 'left');
$this->db->order_by($order,$dir);
if($search != ''){
$this->db->like('a.component_name', $search);
$this->db->or_like('a.eco_code', $search);
$this->db->or_like('b.component_name', $search);
}
$this->db->limit($rowperpage,$row);
$query = $query->result();
return $query;}
As you want to use with $this->datatables, you need to make a custom function for that, add the below custom function in Datatables.php library file:
public function corder_by($column, $type = ASC)
{
$this->order_by[] = array($column, $type);
$this->ci->db->order_by($column, $type);
return $this;
}
If the sorting type is not defined "ASC/DESC", then it will by default sort as "Ascending".
And use it as:
$this->datatables->corder_by('column_name','desc');

Resources