I wanted to get the selected fields of the query from an outside array.
foreach($param as $key => $val){
if($val == 'userId'){
$string .= "adminusers.id, ";
}
if($val == 'name'){
$string .= "CONCAT(firstName, ' ', lastName) as name";
}
}
My query is right below;
$where = '1';
$resultSet = UserAdmin::whereRaw($where)
->addSelect(array($string))
->groupBy('adminusers.id');
However, I received this :
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'stmd_adminusers.id, CONCAT(firstName, ' ', lastName)' in 'field list' (SQL: select stmd_adminusers.id, CONCAT(firstName, ' ', lastName) as name from stmd_adminusers
Whenever you use Some Mysql native function you have to use DB::raw()
$resultSet = UserAdmin::whereRaw($where)
->addSelect(array(DB::raw($string)))
->groupBy('adminusers.id');
Hope this helps.
You can use ->selectRaw($string) instead:
$where = '1';
$resultSet = UserAdmin::whereRaw($where)
->selectRaw($string)
->groupBy('adminusers.id');
This has the advantage over using ->addSelect(DB::raw($string)) that you can (optionally) add a second parameter $bindings; which will protect you from SQL injection attacks more than using DB::raw() would.
Related
everyone.
In the codeigniter there is update_batch function by using it we are able to bulk update multiple rows.
$this->db->update_batch('table_name', $update_data_array, 'where_condition_field_name');
I want similar functionality in core PHP in one function or in one file. Is there any workaround?
Is there any way to extract update_batch function from Codeigniter in one file/function?
I tried to extract this function but it is very lengthy process and there will be many files / functions should be extracted.
Please help me in this regard
Thanks in advance
You can also insert multiple rows into a database table with a single insert query in core php.
(1)One Way
<?php
$mysqli = new mysqli("localhost", "root", "", "newdb");
if ($mysqli == = false) {
die("ERROR: Could not connect. ".$mysqli->connect_error);
}
$sql = "INSERT INTO mytable (first_name, last_name, age)
VALUES('raj', 'sharma', '15'),
('kapil', 'verma', '42'),
('monty', 'singh', '29'),
('arjun', 'patel', '32') ";
if ($mysqli->query($sql) == = true)
{
echo "Records inserted successfully.";
}
else
{
echo "ERROR: Could not able to execute $sql. "
.$mysqli->error;
}
$mysqli->close();
? >
(2)Second Way
Let's assume $column1 and $column2 are arrays with same size posted by html form.
You can create your sql query like this:-
<?php
$query = 'INSERT INTO TABLE (`column1`, `column2`) VALUES ';
$query_parts = array();
for($x=0; $x<count($column1); $x++){
$query_parts[] = "('" . $column1[$x] . "', '" . $column2[$x] . "')";
}
echo $query .= implode(',', $query_parts);
?>
You can easily construct similar type of query using PHP.
Lets use array containing key value pair and implode statement to generate query.
Here’s the snippet.
<?php
$coupons = array(
1 => 'val1',
2 => 'va2',
3 => 'val3',
);
$data = array();
foreach ($coupons AS $key => $value) {
$data[] = "($key, '$value')";
}
$query = "INSERT INTO `tbl_update` (id, val) VALUES " . implode(', ', $data) . " ON DUPLICATE KEY UPDATE val = VALUES(val)";
$this->db->query($query);
?>
Alternatively, you can use CASE construct in UPDATE statement. Then the query would be something
like:
UPDATE tbl_coupons
SET code = (CASE id WHEN 1 THEN 'ABCDE'
WHEN 2 THEN 'GHIJK'
WHEN 3 THEN 'EFGHI'
END)
WHERE id IN(1, 2 ,3);
I have the following query (cut for brevity):
$employees = Employee::where('first_name', 'LIKE', "%$query%")
->orWhere('last_name', 'LIKE', "%$query%")
Now this works when the user inputs a single name like 'John' or 'Smith', but when they input 'John Smith' it doesn't find anything. Am I missing an extra orWhere?
Try this :
Employee::where(DB::raw('CONCAT(first_name," ",lastname)'), 'LIKE', "%' . $query . '%"))
You would have to add a 3rd orWhere. For our search function we use something like this:
Employee::whereraw("COALESCE(last_name, '') LIKE '%$query%'")
->Orwhereraw("COALESCE(first_name, '') LIKE '%$query%'")
->Orwhereraw("COALESCE(last_name + ', ' + first_name, '') LIKE '%$query%'")
Adding Coalesce seemed to help with some issues we had when we first implemented it, not sure if it is necessary in your case though.
You can do :
$fullName = trim($query);
$employees = Employee::where(DB::raw("CONCAT(first_name, ' ', last_name)"), 'LIKE', "%".$fullName."%")->get();
You are concatenating the values in database for first_name + ' ' + last_name and then using like to find the matching records.
I just need to order my records according to updated, and then group them according to card_id.
This is my code:
$triages = Triyage::latest('updated_at')->groupBy('card_id')->paginate(8);
return view('Admin.Opd.card_opd', compact('triages'));
Use a subquery JOIN:
$join = Triyage::select('card_id', DB::raw('max(updated_at) updated_at'))
->groupBy('card_id');
$sql = '(' . $join->toSql() . ') as latest';
$triages = Triyage::join(DB::raw($sql), function($join) {
$join->on('triyages.card_id', 'latest.card_id')
->on('triyages.updated_at', 'latest.updated_at');
})->paginate(8);
I am trying a Concat for an autocomplete, Using CI's Active Record.
My Query is :
$this->db->select("CONCAT(user_firstname, '.', user_surname) AS name", FALSE);
$this->db->select('user_id, user_telephone, user_email');
$this->db->from('users');
$this->db->where('name', $term);
I keep getting an MySQL Error from this saying:
Error Number: 1054Unknown column 'name' in 'where clause'
Which is true, However I have just created in my Concat clause. I ideally need $term to match the Concatenated firstname and surname fields.
Any ideas what I can do to improve this? I am considering just writing this as an flat MySQL Query..
Thanks in advance
$this->db->select('user_id, user_telephone, user_email, CONCAT(user_firstname, '.', user_surname) AS name', FALSE);
$this->db->from('users');
$this->db->where('name', $term);
Not sure why you are running multiple selects. So just put it as a single select. It's probably that the 2nd one is overriding the first one and thus overwriting the concatenation to create the name column.
$this->db->select("CONCAT((first_name),(' '),(middle_name),(' '),(last_name)) as candidate_full_name");
Try like above 100% it will work in ci.
If cryptic solution doen't work then try it.
$query = "SELECT *
FROM (
SELECT user_id, user_telephone, user_email, CONCAT(user_firstname, ' ', user_surname) name
FROM users
) a
WHERE name LIKE '%".$term."%'";
$this->db->query($query);
Source: MySQL select with CONCAT condition
You have to SELECT the fields that you want concat like so:
$this->db->select('user_id, user_telephone, user_email, user_firstname, user_surname, CONCAT(user_firstname, '.', user_surname) AS name', FALSE);
$this->db->from('users');
$this->db->where('name', $term);
This will also solve the issue:
$this->db->select('user_id, user_telephone, user_email, user_firstname, user_surname, CONCAT(user_firstname,user_surname) AS name', FALSE);
$this->db->from('users');
I'm trying to group my entity by a field (year) and do a count of it.
Code:
public function countYear()
{
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('b.year, COUNT(b.id)')
->from('\My\Entity\Album', 'b')
->where('b.year IS NOT NULL')
->addOrderBy('sclr1', 'DESC')
->addGroupBy('b.year');
$query = $qb->getQuery();
die($query->getSQL());
$result = $query->execute();
//die(print_r($result));
return $result;
}
I can't seem to say COUNT(b.id) AS count as it gives an error, and
I do not know what to use as the addOrderby(???, 'DESC') value?
There are many bugs and workarounds required to achieve order by expressions as of v2.3.0 or below:
The order by clause does not support expressions, but you can add a field with the expression to the select and order by it. So it's worth repeating that Tjorriemorrie's own solution actually works:
$qb->select('b.year, COUNT(b.id) AS mycount')
->from('\My\Entity\Album', 'b')
->where('b.year IS NOT NULL')
->orderBy('mycount', 'DESC')
->groupBy('b.year');
Doctrine chokes on equality (e.g. =, LIKE, IS NULL) in the select expression. For those cases the only solution I have found is to use a subselect or self-join:
$qb->select('b, (SELECT count(t.id) FROM \My\Entity\Album AS t '.
'WHERE t.id=b.id AND b.title LIKE :search) AS isTitleMatch')
->from('\My\Entity\Album', 'b')
->where('b.title LIKE :search')
->andWhere('b.description LIKE :search')
->orderBy('isTitleMatch', 'DESC');
To suppress the additional field from the result, you can declare it AS HIDDEN. This way you can use it in the order by without having it in the result.
$qb->select('b.year, COUNT(b.id) AS HIDDEN mycount')
->from('\My\Entity\Album', 'b')
->where('b.year IS NOT NULL')
->orderBy('mycount', 'DESC')
->groupBy('b.year');
what is the error you get when using COUNT(b.id) AS count? it might be because count is a reserved word. try COUNT(b.id) AS idCount, or similar.
alternatively, try $qb->addOrderby('COUNT(b.id)', 'DESC');.
what is your database system (mysql, postgresql, ...)?
If you want your Repository method to return an Entity you cannot use ->select(), but you can use ->addSelect() with a hidden select.
$qb = $this->createQueryBuilder('q')
->addSelect('COUNT(q.id) AS HIDDEN counter')
->orderBy('counter');
$result = $qb->getQuery()->getResult();
$result will be an entity class object.
Please try this code for ci 2 + doctrine 2
$where = " ";
$order_by = " ";
$row = $this->doctrine->em->createQuery("select a from company_group\models\Post a "
.$where." ".$order_by."")
->setMaxResults($data['limit'])
->setFirstResult($data['offset'])
->getResult();`