I have a strange problem, I am making a conditional query with values stored in different variables and passing them to where clause. That where clause simply not accepting values and keep on saying undefined variable in very first condition. To understand it I just cut it to one condition and make it simple to get easy answers.
Error: ErrorException: Undefined variable: col_name in file E:\xampp\htdocs\coder\app\Http\Controllers\a26_gets\a26_gets_ctrl.php on line 97
Code:
$this->tableName = 'mytable';
$col_name = 'first_name';
$value = 'danny';
$tableData = DB::table($this->tableName)
->when($value, function ($query, $value) {
return $query->where($col_name, $value);
})->paginate(1);
print_r($tableData);
Try adding the $col_name to the scope of the conditional query...
$this->tableName = 'mytable';
$col_name = 'first_name';
$value = 'danny';
$tableData = DB::table($this->tableName)
->when($value, function ($query, $value) use ($col_name) {
return $query->where($col_name, $value);
})->paginate(1);
print_r($tableData);
Related
I'm trying to get data from firebase and it worked with once().then function, but the problem is when I save the data a variable, its value will change only inside the function ( when the execution of the function is finished then the variable will not have the returned value from firebase )
code example :
static var temp = [];
void tempp() {
var db = FirebaseDatabase.instance.reference();
db.once().then((DataSnapshot snapshot) {
temp.add(1);
print(temp[0]);
});
print(temp[0]);
}
So, the first print statement will print the new value in temp list which is at index zero
but for the second print ( outside the once().then function ) will cause value range error
Invalid value: Valid value range is empty: 0
that means the value that was saved in the function it is not there anymore
How can I save the value after function is executed ?
I tried to use global variables it didn't work,
your help is much appreciated.
thank you.
I need create multiply search by years. From request I get string like 2017,2018 and then I want get Questions which createdAt, between from start year and end year. I have query builder with part, and I'am not understand why I have this error
if ($paramFetcher->get('years')) {
$orXSearch = $qb->expr()->orX();
$yearData = trim($paramFetcher->get('years'));
foreach (explode(',', $yearData) as $key => $id) {
if (!$id) {
continue;
}
$orXSearch
->add($qb->expr()->between('q.createdAt', ':'.$key.'dateFrom', ':'.$key.'dateTo'));
$date = $this->additionalFunction->validateDateTime($id, 'Y');
$first = clone $date;
$first->setDate($date->format('Y'), 1, 1);
$first->setTime(0, 0, 0);
$last = clone $date;
$last->setDate($date->format('Y'), 12, 31);
$last->setTime(23, 59 , 59);
$qb
->setParameter($key.'dateFrom', $first->format('Y-m-d H:i:s'))
->setParameter($key.'dateTo', $last->format('Y-m-d H:i:s'));
}
$qb->andWhere($orXSearch);
}
error:
symfony Invalid parameter format, : given, but :<name> or ?<num> expected.
In your foreach loop, you’re looping over the result of an explode operation which yields a numeric array, i.e. $key will always have a numeric value.
Hence, your parameter placeholder is colon + number + string, i.e. :1dateFrom. This is not allowed. Either you reference a string value with a colon + string placeholder (:foo), or you reference a numeric value with a question mark + number value (?1).
Your problem is easy to solve: Simply add any letter between the colon and the number, and you’re good:
->add($qb->expr()->between(
'q.createdAt',
':x'.$key.'dateFrom',
':x'.$key.'dateTo'
));
I'm new to Symfony, and I got an error while running a query :
public function getFilteredArticles($page, $nbPerPage, $data) {
$query = $this->createQueryBuilder('a')
->leftJoin('a.images', 'i')
->addSelect('i')
->leftJoin('a.type_stockage', 't')
->addSelect('t')
->leftJoin('a.famille', 'f')
->addSelect('f');
if ($data['famille'] != '') {
$query->where('f.id = :famille')
->setParameter('famille', $data['famille']);
}
if ($data['rds'] == false) {
$query->where('a.stock_actuel > 0');
}
if ($data['recherche'] != '' && $data['recherche'] != null) {
$query->where('a.ref_article LIKE :recherche')
->setParameter('recherche', '%' . $data['recherche'] . '%');
}
$query->leftJoin('a.sousfamille', 's')
->orderBy('a.ref_article', 'ASC')
->getQuery();
$query->setFirstResult(($page - 1) * $nbPerPage)
->setMaxResults($nbPerPage);
return new Paginator($query, true);
}
This query have conditionnals parameters as you can see, that returns the list of articles I need for a table. But when I run this query to fill my table, I got the error :
An exception has been thrown during the rendering of a template ("Too
many parameters: the query defines 0 parameters and you bound 1").
I don't know why he is expecting 0 parameters. I tried using setParameters instead, but the result is the same.
Does anyone has an idea?
You should use andWhere() methods instead of where().
where() method removes all previous where, but setParameter() does not. That's why he found more parameters than where clauses.
I personally never use where if the condition has no sense to be the first condition, to avoid this kinds of errors.
if ($data['famille'] != '') {
$query->andWhere('f.id = :famille')
->setParameter('famille', $data['famille']);
}
if ($data['rds'] == false) {
$query->andWhere('a.stock_actuel > 0');
}
if ($data['recherche'] != '' && $data['recherche'] != null) {
$query->andWhere('a.ref_article LIKE :recherche')
->setParameter('recherche', '%' . $data['recherche'] . '%');
}
where() php doc
Specifies one or more restrictions to the query result.
Replaces any previously specified restrictions, if any.
andWhere() php doc
Adds one or more restrictions to the query results, forming a logical
conjunction with any previously specified restrictions.
My error, in Symfony 4, using Doctrine 2.6 was
Too many parameters: the query defines 0 parameters and you bound 2
The problem was that I wasn't defining the parameters in andWhere method as
$this->createQueryBuilder('q')
...
->andWhere('q.propertyDate IS NOT NULL') //this also couldn't find anywhere
->andWhere('q.parameterName = :parameterName')
->setParameters(['q.parameterName' => $parameterName, ...2nd parameter])
As I couldn't find any answer to my problem, but was similar to this one, I thought to maybe help someone who is struggling like I was.
also in symfony 5 and 6 you should use andWhere() methods instead of where().
where() method removes all previous where, but setParameter() does not. That's why he found more parameters than where clauses.
I have this function,
public function getWall(){
$q = $this->createQueryBuilder('f');
$q->leftJoin("f.profilo", 'p');
$q->leftJoin("p.utente", 'u');
$q->where('(f.foto_eliminata IS NULL OR f.foto_eliminata != 1)');
$q->andWhere('p.fase_registrazione = :fase');
$q->andWhere('u.locked = :false');
$q->slice(0, 20);
$q->setParameter(':fase', 100);
$q->setParameter('false', false);
$q->orderBy('f.created_at', 'desc');
$dql = $q->getQuery();
$results = $dql->execute();
return $results;
}
but I get this error,
Call to undefined method Doctrine\ORM\QueryBuilder::slice()
Ok, so, u get this error, cause QueryBuilder has no such method. But Collection has. If u want to use slice, a possible variant is:
use Doctrine\Common\Collections;
public function getWall(){
$result = $this->createQueryBuilder('f')
->leftJoin("f.profilo", 'p')
->leftJoin("p.utente", 'u')
->where('(f.foto_eliminata IS NULL OR f.foto_eliminata != 1)')
->andWhere('p.fase_registrazione = :fase')
->andWhere('u.locked = :false')
->setParameter('fase', 100)
->setParameter('false', false)
->orderBy('f.created_at', 'desc')
->getQuery()
->getResult();
// $result typed as array
return new Collections\ArrayCollection($result))->slice(0,20); // convert array to collection, then slice
}
By the way, it is not a good idea to 'limit' result of the query in a such way.
U can use setMaxResults(20), and not to select all objects at all.
About lazy collections (http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/tutorials/extra-lazy-associations.html): after selecting result objects, u can take some object from result collection: $r = $result[0] after that:
$portfilos = $r->getPortfolio(); // returns for example Collection with some objects;
// its Lazy, without SQL query!
$portfolios->slice(0, 20); // queries first 20 potfolios
To use slice is a rather good idea, if u have lots of objects in some relation.
p.s. sry, mb I didn't recognized your problem, but tried :)
EDITED
fixed errors in code.
I have an issue with a count function in drupal 7.
Code is :
$sql = "select count(Status) from TB_Aanmeldingen where (Status= 'Ja' or Status='Ja, met kleine') and ID_Wedstrijd = :match";
$args = array(':match' => $match);
$row = db_query($sql, $args)->fetchObject();
$aantal = $row->count(Status);
Error message:
Call to undefined method stdClass::count()
Any help is very much appreciated!
I'm not sure what you're trying to do with:
$aantal = $row->count(Status);
Do a print_r or var_dump of the $row object, and you'll see what the structure is. db_query returns a DatabaseStatementInterface, and you're getting an object from it. But the object doesn't have a function you're trying to call.
Instead, debug, print out, and debug the value of $row, and get the value you're looking for.
Also, look into db_select. It's better to use that then db_query.
https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_select/7