Getting Invalid number of parameters in Doctrine2 and Symfony Querybuilder - orm

Here is my code
if(!$criteria){
return null;
}
$em = $this->doctrine->getEntityManagerForClass('Sample\MyBundle\Entity\Call');
$qb = $em->createQueryBuilder();
$qb->add('select', 'c')->add('from', 'Sample\MyBundle\Entity\Call c');
if($criteria->getReason() && $criteria->getReason() != null){
$qb->add('where', 'c.reason = ?1');
$qb->setParameter(1, $criteria->getReason());
}
if($criteria->getCallDate() && $criteria->getCallDate() != null){
$qb->add('where', 'c.callTime = ?2');
$qb->setParameter(2, $criteria->getCallDate());
}
if($criteria->getPage()>1){
$qb->setFirstResult(($criteria->getPage()-1) * 10)->setMaxResults(10);
}
$query = $qb->getQuery();
return $query->getResult();
I'm getting this error - Invalid parameter number: number of bound variables does not match number of tokens I googled but couldn't found a solution. Need help with this.
I even tried to put both setParameter() calls after conditional check if statements but that also give the same error. If I don't set the second parameter and remove second where condition then it works.

Oh, I guess I was making a mistake. I think I can not use multiple 'where' in 'add' function. I replaced it with $qb->andWhere('c.callTime > ?2'); and now it works fine.

Related

What to use as my default to achieve the correct laravel select where?

Please, i'm writing a function and i need guidance
function($file_name='*'){
File::where('filename',$file_name)->get();
}
I want the filename to pull all the filename columns in the database table when file name is not defined, and when it is it should use the value to pull the right data.
My question is, what should i use as default for filename in in the function input to work?
Even if is raw sql i will appreciate
First of all you are missing, your functions name
function getFile($file_name = null){
$q = File::query();
if($file_name == null ){
// Do nothing this will get all files at the end since you haven't applied a where clause.
}else{
$q = File::where('filename',$file_name);
}
$result = $q->get();
return $result;
}

Object of class PDOStatement could not convert to string

I changed my mysqli connection to PDO statment so i have to much error on my page this is the my code pls help us
.
.
.
if ($fn && $ln && $e && $p) { // If everything's OK...
// Make sure the email address is available:
//$q = "SELECT user_id FROM users WHERE email='$e'";
$q = $dbc->query("SELECT user_id FROM users WHERE email='$e'");
$q->execute(array($e));
$r = $q->fetchAll(PDO::FETCH_ASSOC);
//$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
if (mysqli_num_rows($r) == 0) { // Available.
// Create the activation code:
$a = md5(uniqid(rand(), true));
Here is your code converted to PDO.
// Make sure the email address is available:
$q = $dbc->query("SELECT user_id FROM users WHERE email=?");
$q->execute(array($e));
$r = $q->fetchColumn();
if (!$r) { // Available.
// Create the activation code:
$a = md5(uniqid(rand(), true));
Three things has been corrected
You have to always use a placeholder tp represent a variable in the query.
To get a single value from the result, fetchColumn have to be used instead of fetchAll
No need for the manual reporting, as PDO can report its errors automatically, if confugired properly, as described in this tutorial I wrote

Invalid parameter number: number of bound variables does not match number of tokens PDO insert

function mysql_insert($data_array){
$sql = "insert into `". $this->table_name. '`';
$array_keys = array_keys($data_array);
$array_keys_comma = implode(",\n", preg_replace('/^(.*?)$/', "`$1`", $array_keys));
for($a=0,$b=count($data_array); $a<$b; $a++){ $question_marks .="?,"; }
$array_values = array_values($data_array);
$array_values_comma = implode(",", $array_values);
$sql.= " ($array_keys_comma) ";
$sql.= " values(". substr($question_marks, 0,-1) .")";
$prepare = $this->connDB->prepare($sql);
$insert = $prepare->execute(array($array_values_comma));
}
I want to creat like this universal functions, $data_array-comes from $_POST
This function will work for all form. But i dont know what is my wrong :S
I don't know what is my wrong
That's quite easy to know: number of bound variables does not match number of tokens.
I want to creat like this universal functions, $data_array-comes from $_POST
Here you go: Insert/update helper function using PDO
$array_values_comma is a scalar after you implode() the array. So you always pass an array of one element to your execute() function. You should pass $array_values.
Here's how I'd write this function:
function mysql_insert($data_array){
$columns = array_keys($data_array);
$column_list_delimited = implode(",",
array_map(function ($name) { return "`$name`"; }, $columns));
$question_marks = implode(",", array_fill(1, count($data_array), "?"));
$sql = "insert into `{$this->table_name}` ($column_list_delimited)
values ($question_marks)";
// always check for these functions returning FALSE, which indicates an error
// or alternatively set the PDO attribute to use exceptions
$prepare = $this->connDB->prepare($sql);
if ($prepare === false) {
trigger_error(print_r($this->connDB->errorInfo(),true), E_USER_ERROR);
}
$insert = $prepare->execute(array_values($data_array));
if ($insert === false) {
trigger_error(print_r($prepare->errorInfo(),true), E_USER_ERROR);
}
}
A further improvement would be to do some validation of $this->table_name and the keys of $data_array so you know they match an existing table and its columns.
See my answer to escaping column name with PDO for an example of validating column names.

PDO login script won't work

I changed this login script to PDO. Now it passes the username but get's stuck fetchAll line. I need help please. thanks
<?php
session_start();
include_once"includes/config.php";
if (isset($_POST['admin_login'])) {
$admin_user = trim($_POST['admin_user']);
$admin_pw = trim($_POST['admin_pw']);
if ($admin_user == NULL OR $admin_pw == NULL) {
$final_report.="Please complete all the fields below..";
} else {
$check_user_data = $db->prepare("SELECT * FROM `admin`
WHERE `admin_user`='$admin_user'");
$check_user_data->execute();
if ($check_user_data->fetchColumn() == 0) {
$final_report.="This admin username does not exist..";
} else {
$get_user_data = $check_user_data->fetchAll($check_user_data);
if ($get_user_data['admin_pw'] == $admin_pw) {
$start_idsess = $_SESSION['admin_user'] = "".$get_user_data['admin_user']."";
$start_passsess = $_SESSION['admin_pw'] = "".$get_user_data['admin_pw']."";
$final_report.="You are about to be logged in, please wait a few moments...";
header('Location: admin.php');
}
}
}
}
?>
Not checking return value prepare() or execute() for false. You need to check for SQL errors and handle them, stopping the code instead of continuing on blithely.
Not using query parameters in the prepared statement, still interpolating $_POST content into the query unsafely. You're missing the benefit of switching to PDO, and leaving yourself vulnerable to SQL injection attack.
You're storing passwords in plaintext, which is unsafe. See You're Probably Storing Passwords Incorrectly.
Do you really need to SELECT * if you only use the admin_pw column? Hint: no.
PDOStatement::fetchAll() returns an array of arrays, not just one array for a row. Read the examples in the documentation for fetchAll().

Kohana ORM count_all() working but find_all() is not

I'm having an issue where I'm building an ORM query based on several conditions from a $_POST. The final query looks fine and returns records in a direct SQL query (phpmyadmin) but in my application does not return any records. here is the code...
$records = ORM::factory('record')->where(array('date >='=>$_POST['fromdate'],'date <='=>$_POST['todate']));
if ($_POST['agent'] != '0') $records->where(array('ccp_id'=>$_POST['agent']));
if ($_POST['supervisor'] != '0') {
$ccps = ORM::factory('employee')->where(array('supervisor_id'=>$_POST['supervisor'],'active'=>'1'))->find_all();
foreach ($ccps as $ccp) {
$agents[] = $ccp->id;
}
// echo kohana::debug($agents);
$records->in('ccp_id',$agents);
}
if ($_POST['lead'] != '0') $records->where(array('lead_id'=>$_POST['lead']));
if ($_POST['reasons'] != '[]') {
$reasons = explode(',',str_replace(array('[',']','"'),'',$_POST['reasons']));
$records->in('reason_id',$reasons);
}
$records->find_all();
$records->loaded is false. If I change out the find_all() with count_all() I get an accurate count.
With sample data in the $_POST I have this query in $records->last_query()
SELECT `records`.*
FROM (`records`)
WHERE `date` >= '2010-10-10'
AND `date` <= '2010-11-09'
AND `ccp_id` IN ('E128092','E128093','E124874','E124414','E129056','E137678','E078952','E112701','E084457','E098047','E099221','E001131','E120892')
AND `lead_id` = 'E110873'
AND `reason_id` IN (1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24)
ORDER BY `records`.`id` ASC
this returns 4 records in phpmyadmin and (4) for count_all().
I do not understand why this is happening. Any insights would be helpful. Thank you.
In your last line you should have
$records = $records->find_all();
instead of
// this actually returns you the resultset and resets the query builder object
$records->find_all()
$records is a Database_Result and has no loaded property. Use count($records) or iterate it with foreach statement to get ORM objects.
Just a note: It's probably better not to wipe out the ORM object ( $results = $records->find_all() instead of $records = $records->find_all()) if you wish to use $records->count_all() or other calls later in your code. Just an issue I ran into.