Here is my code to filter pets base on a JSON ajax Query
I am getting error follwoing image
public function filter($object, $active=true){
$query = $this->createQueryBuilder('p');
$query->innerjoin('TadpetProfessionalBundle:ProPet', 'pp', 'WITH', 'pp.professionalId = p.id');
$query->innerjoin('TadpetManagerBundle:Pet', 'ppp', 'WITH', 'ppp.id = pp.petId');
$query->where('p.isActive = :active')
->setParameter('active', $active);
if(!empty($object->pets)){
$qString = "";
for($i=1; $i<=sizeof($object->pets); $i++){
if($i == 1){
$qString .= "ppp.name = :petname".$i;
}else{
$qString .= " OR ppp.name = :petname".$i;
}
}
$query->andWhere($qString);
$query->setParameter('petname'+1,$object->pets[0]);
$query->setParameter('petname'+2,$object->pets[1]);
$query->setParameter('petname'+3,$object->pets[2]);
}
return $query->getQuery()->getResult();
}
Help me please
In these lines:
$query->setParameter('petname'+1,$object->pets[0]);
$query->setParameter('petname'+2,$object->pets[1]);
$query->setParameter('petname'+3,$object->pets[2]);
You are adding 'petname' to the numbers, but you should concatenate them:
$query->setParameter('petname'.1,$object->pets[0]);
$query->setParameter('petname'.2,$object->pets[1]);
$query->setParameter('petname'.3,$object->pets[2]);
Also, you could use a loop:
for($i=1; $i<=sizeof($object->pets); $i++){
$query->setParameter('petname'.$i,$object->pets[$i-1]);
}
Related
I have a query that receive some array parameters without any ideas how rows there is. It must return contents with all filters (AND clause), and one or more categories (OR clause).
I can't get results I'd like because parentheses are not a the good place. I should got this SQL rendering:
WHERE (
f3_.idfilter = '87'
AND f5_.idfilter = '90'
AND f7_.idfilter = '154'
AND f9_.idfilter = '165'
)
AND (
c0_.content_category_idcontent_category = 1
OR c0_.content_category_idcontent_category = 3
)
and got this instead:
WHERE (
(
f3_.idfilter = '87'
AND f5_.idfilter = '90'
AND f7_.idfilter = '154'
AND f9_.idfilter = '165'
AND c0_.content_category_idcontent_category = 1
)
OR c0_.content_category_idcontent_category = 3
)
My code:
public function getContentByFiltersAjax($categs, $filters, $offset, $limit) {
$filtersTab = explode(',', $filters);
$query = $this->createQueryBuilder('c');
for ($i = 1; $i <= count($filtersTab); $i++) {
$query = $query
->leftJoin('c.filterfilter', 'f' . $i)
->andWhere('f' . $i . '.idfilter = :filter_idfilter' . $i)
->setParameter('filter_idfilter' . $i, $filtersTab[$i - 1]);
}
$categsTab = explode(',', $categs);
if(sizeof($categsTab) > 1) {
$expr = $query->expr();
$categsTab = explode(',', $categs);
foreach ($categsTab as $key => $value) {
if($key === 0){
$query->andWhere($expr->eq('c.contentCategorycontentCategory', $value));
} else {
$query->orWhere($expr->eq('c.contentCategorycontentCategory', $value));
}
}
} else {
$query
->andWhere('c.contentCategorycontentCategory = :category')
->setParameter('category', $categs);
}
$query
->andWhere('c.status = :status')
->setParameter('status', 'publie');
$query->orderBy('editor.plan', 'DESC');
$query->addOrderBy('c.creationDate', 'DESC');
$query
->setFirstResult($offset)
->setMaxResults($limit);
$result = $query->distinct()->getQuery()->getResult();
return $result;
}
You put the orWhere's inside 1 andWhere like this:
$query->andWhere(
$query->expr->orX(
$query->expr->eq('c.contentCategorycontentCategory', $value1),
$query->expr->eq('c.contentCategorycontentCategory', $value2)
)
);
Or in your foreach loop:
$orX = $query->expr->orX();
foreach ($categsTab as $value) {
$orX->add($query->expr->eq('c.contentCategorycontentCategory', $value));
}
$query->andWhere($orX);
I'm using PhpSpreadsheet to easily read from a xls document and insert into a DB after some calculations. I succeeded using examples from the documentation, but I find it sooo complicated I'm sure I missed something and it can be done much more easily.
$worksheet = $this->getWorksheet("file.xls");
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(FALSE);
foreach ($cellIterator as $key => $cell) {
$cellValue = $cell->getValue();
if($key == 'A')
$field1 = $cellValue;
if($key == 'B') {
$dateTime = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($cellValue);
$date = $dateTime->format("Y-m-d");
}
if($key == 'C')
$field2 = $cellValue;
if($key == 'D')
$field3 = $cellValue;
if($key == 'E')
$field4 = $cellValue;
}
}
I would have expected something like $row->getCell("A")->getValue() to be available.
So... Have I missed something ?
See the docs on getting the values by column and row directly rather than testing the keys
From the example:
// Get the value from cell B5
$cellValue = $spreadsheet->getActiveSheet()->getCellByColumnAndRow(2, 5)->getValue();
Hope that helps
Here is what I found
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$spreadsheet = $reader->load("test.xlsx");
$sheet = $spreadsheet->getSheet(0);
$nb = 0;
foreach ($sheet->getRowIterator() as $row) {
echo $sheet->getCell("A$nb")->getValue();
echo "<hr>";
$nb++;
}
You have to access somehow each cell.
Example: for the case when you don't know the dimensions of rows and columns ( ... which can have combined letters past single alphabet letters), get iteration for each row and then for each column, and in the end you can have the data parsed into multidimensional array:
$results = [];
$reader = new Xlsx(); // PhpOffice\PhpSpreadsheet\Reader\Xlsx
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load(storage_path('app/temp/' . $file));
$sheet = $spreadsheet->getActiveSheet();
foreach ($sheet->getRowIterator() as $index => $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(FALSE); // This loops through all cells, even if a cell value is not set.
$row_content = [];
foreach ($cellIterator as $cell) {
array_push($row_content, $cell->getValue());
}
$results[] = $row_content;
}
I had try to use the getData e.g.
data = $("#dg").datagrid("getData");`
var total = data.total; (total is 100)`
var rows = data.rows; (rows.length is 25)`
It can result: the total number is correct like 100 records
but the rows return only get the current page rows like 25 rows.
I need to get all of the records (100 rows).
Is there something i missed ? Or how can we do this ? Please help me.
This is because of pagination. let me describe model with pagination for showing 100 row in php.
function get_invoiceinfoList($search_keyword,$custID){
$page = 1;
$rows = 100;
$sort = '';
$order = 'asc';
$offset = ($page - 1) * $rows;
if($custID > 0 && $search_keyword == 0){
$search = " and a.customer_id =$custID";
}else{
$search = "and (b.name like '%$search_keyword%' || a.inv_no like '%$search_keyword%')" ;
}
$vQuery=$this->db->query("SELECT a.inv_id,a.inv_no,a.inv_org,a.inv_date,
a.customer_id,a.heading,a.quot_id,a.total_cost as total_amount,
a.paid_amount,(a.total_cost-a.paid_amount)as due_amount,b.name
from sales_invoice a,view_customer_info b
where
a.customer_id = b.customer_id $search order by a.inv_date DESC limit $offset, $rows");
$result = $vQuery->result();
$rows = array();
foreach ($result as $rowData){
array_push($rows, $rowData);
}
$data['rows'] = $rows;
return $data;
}
I have the following piece of code that is giving the following exception and I can't figure out why, any help would be appreciated.
Invalid parameter number: number of bound variables does not match
number of tokens
if (!empty($ids)) {
$queryIds = implode(",", $ids);
$query = $em->createQueryBuilder()
->from('MainClientBundle:Posts','p')
->select('p')
->where('p.id >= :rand')
->where('p.id NOT IN (:ids)')
->orderBy('p.id','ASC')
->setParameter('rand', rand(1, $max))
->setParameter('ids', $queryIds)
->setMaxResults(1);
} else {
$query = $em->createQueryBuilder()
->from('MainClientBundle:Posts','p')
->select('p')
->where('p.id >= :rand')
->orderBy('p.id','ASC')
->setParameter('rand', rand(1, $max))
->setMaxResults(1);
}
try {
if($options['videos'] == "off"){
$query->where("p.type <> :type")->setParameter("type",1);
}
if($options['sfw'] == "on"){
$query->where("p.safeForWork <> :sfw")->setParameter("sfw",0);
}
$post = $query->getQuery()->getSingleResult();
} catch (\Doctrine\Orm\NoResultException $e) {
$post = null;
}
Your first query is the problem. Your query should look like this
if (!empty($ids)) {
$queryIds = implode(",", $ids);
$query = $em->createQueryBuilder()
->from('MainClientBundle:Posts','p')
->select('p')
->where('p.id >= :rand')
->andWhere('p.id NOT IN (:ids)')
->orderBy('p.id','ASC')
->setParameter('rand', rand(1, $max))
->setParameter('ids', $queryIds)
->setMaxResults(1);
} else {
$query = $em->createQueryBuilder()
->from('MainClientBundle:Posts','p')
->select('p')
->where('p.id >= :rand')
->orderBy('p.id','ASC')
->setParameter('rand', rand(1, $max))
->setMaxResults(1);
}
try {
if($options['videos'] == "off"){
$query->where("p.type <> :type")->setParameter("type",1);
}
if($options['sfw'] == "on"){
$query->where("p.safeForWork <> :sfw")->setParameter("sfw",0);
}
$post = $query->getQuery()->getSingleResult();
} catch (\Doctrine\Orm\NoResultException $e) {
$post = null;
}
Note that I changed your second where to andWhere. When you use two where() in the same query builder, the first gets overwritten by the second.
As stated above in the comments the problems lies with the double usage of ->where in your querybuilder. If you want to combine multiple where clauses you need to use ->andWhere or/and ->orWhere.
Also I changed your result to ->getOneOrNullResult(), with that you don't need to use this whole try/catch block you used to catch the doctrine exception.
if (!empty($ids)) {
$queryIds = implode(",", $ids);
$query = $em->createQueryBuilder()
->from('MainClientBundle:Posts','p')
->select('p')
->where('p.id >= :rand')
->where('p.id NOT IN (:ids)')
->orderBy('p.id','ASC')
->setParameter('rand', rand(1, $max))
->setParameter('ids', $queryIds)
->setMaxResults(1);
} else {
$query = $em->createQueryBuilder()
->from('MainClientBundle:Posts','p')
->select('p')
->where('p.id >= :rand')
->orderBy('p.id','ASC')
->setParameter('rand', rand(1, $max))
->setMaxResults(1);
}
if($options['videos'] == "off"){
$query->where("p.type <> :type")->setParameter("type",1);
}
if($options['sfw'] == "on"){
$query->where("p.safeForWork <> :sfw")->setParameter("sfw",0);
}
$post = $query->getQuery()->getOneOrNullResult();
Trying to do a count on these lines COUNT(engineerName) AS engineerCount,
Count(managerName) as managerCount,
Count(isContractor) as contractorCount
but it keeps returning the same numbers for all three. So I'm trying to add a Where for each one, Example Count(isContractor where isContractor = 'yes') as contractorCount but getting errors please help, thank you.
<?php
clASs EfficiencyController extends DooController
{
function getEfficiency(){
include './protected/config/db.conf.php';
Doo::db()->setDb($dbconfig, 'local_network');
$Vendor = ($_SERVER['REQUEST_METHOD'] == "POST") ? $_POST['Vendor'] : $_GET['Vendor'];
$date = ($_SERVER['REQUEST_METHOD'] == "POST") ? $_POST['date'] : $_GET['date'];
$level = ($_SERVER['REQUEST_METHOD'] == "POST") ? $_POST['level'] : $_GET['level'];
switch($level) {
case "Region":
case "area":
$Market99="";
break;
default:
$Market99=$level;
break;
}
{
//
// LUCENT,NORTEL
//
$query = " SELECT
DayKey,
Market99,
Region,
areaName,
Sum(Total_Sites) as totalCount,
Max(engineerCount) AS engineerCount,
Max(managerCount) AS managerCount,
Max(contractorCount) AS contractorCount,
SC_Type,
Sum(Total_Carriers),
Sum(Total_Sectors),
Vendor
FROM
network.envEquipSummaryConfig a
Left Join
(SELECT
market,
areaName,
COUNT(engineerName) AS engineerCount,
Count(managerName) as managerCount,
Count(isContractor) as contractorCount
FROM
employee.employees
GROUP BY market
ORDER BY COUNT(market) DESC) b ON a.Market99 = b.market
Where
a.DayKey <= \"$date\" and a.Vendor = \"$Vendor\"
Group By Market99 asc";
switch($level) {
case "region":
$query = $query. " order by region ASC";
break;
case "area":
$query = $query. " order by areaName ASC";
break;
default;
$query = $query. " order by Market99 ASC";
break;
}
}
//echo $query; exit;
$this->setContentType('xml');
$result = Doo::db()->fetchAll($query);
printf("<root>\n");
if(count($result) > 0)
foreach($result AS $row) {
printf("\t<data>\n");
printf("\t\t<date>%s</date>\n",$row["DayKey"]);
printf("\t\t<vName>%s</vName>\n",$row["Vendor"]);
printf("\t\t<location>%s</location>\n",$row["Market99"]);
printf("\t\t<toCount>%s</toCount>\n",$row["totalCount"]);
printf("\t\t<enCount>%s</enCount>\n",$row["engineerCount"]);
printf("\t\t<mnCount>%s</mnCount>\n",$row["managerCount"]);
printf("\t\t<cnCount>%s</cnCount>\n",$row["contractorCount"]);
printf("\t</data>\n");
}
printf("</root>\n");
}
}
?>
SELECT
market,
areaName,
COUNT(engineerName) AS engineerCount,
Count(managerName) as managerCount,
Count(isContractor) as contractorCount
FROM
employee.employees
GROUP BY market
should be
Group By market,areaName at a guess.
Which is all it can be seeing as you've provided next to no useful information.