I've found so many existing questions asking about this error but none of them relate to my code's situation so despite searching for a while I've had to start a new question.
I'm writing a PDO prepared statement in PHP and i'm getting the error code:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]: Invalid parameter number: parameter was not defined' in...
The query that has been build so far is:
SELECT * FROM esl_comments, esl_articles WHERE esl_comments.commentSet=:esl_comments.commentSet AND esl_comments.commentSetInstanceID=:esl_comments.commentSetInstanceID AND esl_comments.commentVisible=:esl_comments.commentVisible AND esl_comments.commentID=:esl_comments.commentID;
And the data is being passed to the function which attempts to execute the query just fine. I've echo'ed it and it appears as:
esl_comments.commentSet - article
esl_comments.commentSetInstanceID - esl_articles.articleID
esl_comments.commentVisible - Y
esl_comments.commentID - 2
So there are four placeholders in the query, and all four are being satisfied with data but when I try to execute the query after binding it is giving the above error.
Does anyone have any ideas what may be causing it?
Placeholders must be alphanumeric or underscore.
:esl_comments.commentSet is not a valid placeholder. Try just :commentSet instead.
(And of course the other ones will need to be replaced as well)
Related
I am Getting Warning Like Warning: PDO::query() expects parameter 1 to be string, object given in C:\xampp\htdoc And Values are not Going to insert in database.
Can anybody please me I am Stuck With Problem From Many Days
Here is code:-
<?php
if(isset($_POST['btn_Add']))
{
// Step 1: Establish a connection
$conn = new PDO("mysql:host=localhost; dbname=DbName", 'root', '');
$MaxId ="2";
$Feild_1 =$_POST['txt_Feild1']; //datatype int
$Feild_2 =$_POST['txt_Feild2']; //datatype varchar
$Feild_3 =$_POST['txt_Feild3']; //varchar
// Step 2: Construct a query
$insert_query=$conn->prepare("Insert INTO Dbname (Max_Id, Feild_1, Feild_2, Feild_3)
values (:Max_Id,:Feild_1, :Feild_2, :Feild_3,");
// Step 3: Send the query
$result=$conn->query($insert_query);
// STEP 4:Bind The Placeholder name to specific Script variables
$insert_query->bindParam(':Max_Id', $Max_Id);
$insert_query->bindParam(':Feild_1', $Field_1);
$insert_query->bindParam(':Feild_2', $Field_1);
$insert_query->bindParam(':Feild_3', $Field_1);
//Step 5 Execute Query
$insert_query->execute();
}//OUTER IF END
?>
PDO Warning :-Warning: PDO::query() expects parameter 1 to be string, object given in C:\xampp\htdocs\BSNL Project\Add_Pin_Unpin_File(Without Auto Increment).php on line 109
[]
Step 1 - Fix your SQL:
So, with the code you've given, you've actually got an SQL error. If we take the SQL out of the PHP, it looks like...
Insert INTO Dbname (Max_Id, Feild_1, Feild_2, Feild_3)
values (:Max_Id,:Feild_1, :Feild_2, :Feild_3,
So the issue with this is that, first, you have a trailing comma that shouldn't be there, and you're missing a trailing ) that closes the values part of the query.
As a side note, you're using Dbname as a table name. Whether this is correct or not, we don't know, that depends on you.
Step 2 - Use PDO correctly:
The warning message you've provided is;
PDO Warning :-Warning: PDO::query() expects parameter 1 to be string, object given in C:\xampp\htdocs\BSNL Project\Add_Pin_Unpin_File(Without Auto Increment).php on line 109
If you look at the documentation the query method expects at least one parameter which has to be a string. This method returns an instance of PDOStatement and runs an execute straight away. As far as I know, it does not support prepared statements.
So the warning comes because you've called prepare with your SQL statement which returns an object of type PDOStatment, and then pass that returned object as the first parameter which as expected throws a warning saying that you've not passed a string.
By simply removing the line $result=$conn->query($insert_query); you will remove the warning message without causing other issues as it's not necessary anyway as you bind and then execute the query manually afterwards.
If there are further issues, then I'd suggest you have a look at setting the exception mode on your PDO connection variable and seeing what comes up.
Step 3 - Fix your binds
The final issue that I can see is with the following...
$insert_query->bindParam(':Max_Id', $Max_Id);
You bind $Max_Id but earlier in your code, you actually create the variable $MaxId.
The same goes for the fields. You bind $Field_1, but your actual variable is $Feild_1.
Finally, you're binding the same variable for multiple placeholders which doesn't seem quite right when you appear to have defined different variables for each one.
You need to call execute for the prepared queries.
http://php.net/manual/en/pdostatement.execute.php
$insert_query->execute();
I have a series of queries to loop through and execute using PDO.
The queries may make use of zero or more of the following 3 bound values, ":valA", ":valB" and ":valC".
At runtime I don't know which of these three parameter a query might use. But the values of these parameters will be the same for each query I loop through.
If I bind all three to a prepared query and the query does not make use of all the parameters, PDO will error.
I.e.
<?php
$stmt = $pdo->prepare('SELECT * FROM table WHERE col = :valA OR col = valB');
$stmt->execute(array(':valA' => 'a', ':valB' => 'b', ':valC' => 'c'); // Results in an error because the query does makes use of :valC.
Is there a method for binding a parameter without making it required to be used by a prepared query?
I thought I wuold be able to catch the exception and allow the code to resume, but the query won't execute regardless of the error mode set for PDO.
Note that this question is different to the suggested duplicate of, Ignore particular WHERE criteria. In that question, the query needed to be crafted to suit optional values supplied by a user. I this case, the values are hardcoded by the application, and the queries are stored in a database. The application does not know which params a query may make use of, so it needs to make them all available.
Obviously I can regex check for params, but it could be tripped up by a string that happen to contain the parameter name.
The queries could also be stored with additional properties to indicate which params it makes use of, but I would prefer to not have to do this.
There is a way to do this with PDO. The methods bindParam() and bindValue() return false or throw an exception if you try to bind to a parameter that doesn't appear in the query.
But it only works if you set:
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
Example:
$stmt = $pdo->prepare("INSERT INTO foo (test, boolcol) VALUES (:valA, :valB)");
if (!$stmt->bindParam("valA", $foo))
{
echo "error, no param 'valA'\n";
}
if (!$stmt->bindParam("valB", $foo))
{
echo "error, no param 'valB'\n";
}
if (!$stmt->bindParam("valC", $foo))
{
echo "error, no param 'valC'\n";
}
Outputs:
PHP Warning: PDOStatement::bindParam(): SQLSTATE[HY093]:
Invalid parameter number: parameter was not defined in /home/billkarwin/pdo.php on line 18
error, no param 'valC'
If you set $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); then it throws an exception instead of a warning, and you could wrap each bindParam() in a try/catch block:
PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY093]:
Invalid parameter number: parameter was not defined' in /home/billkarwin/pdo.php:18
Stack trace:
#0 /home/billkarwin/pdo.php(18): PDOStatement->bindParam('valC', 'foo')
#1 {main}
thrown in /home/billkarwin/pdo.php on line 18
This question already has answers here:
Warning: PDOStatement::bindValue(): SQLSTATE[HY093]: Invalid parameter number: Columns/Parameters are 1-based
(2 answers)
Closed 6 years ago.
My code is:
.....
.....
$sql = 'SELECT '.$return_fields.' FROM '.$table.' WHERE '.$search_field.'=:'.$search_field;
$stmt = $conn->prepare($sql);
$stmt->bindParam($search_field, $search_val);
$stmt->execute();
....
....
where $search_field = 'reg_user_linked', $search_val = 'aa#gmail.com'.
This error occurs when execute the statement and I couldn't figure out why:
Invalid parameter number: Columns/Parameters are 1-based
Can anyone help?
After hours of trying, I found out that this error only occurs when I was in debugging mode. If I ran the code and print the result, it works.....
Does anyone know why this happens? (My IDE is NetBeans 7.2, debug tool is xdebug)...
When binding the parameter you need to specify the : in the parameter name:
$stmt->bindParam(':' . $search_field, $search_val);
You are getting an error because this is missing and the code falls back to expecting an integer value to indicate the parameter position (as if you were using ?-style parameters).
Note this description of the first parameter for PDOStatement::bindParam() from the documentation.
parameter
Parameter identifier. For a prepared statement using named placeholders, this will be a parameter name of the form :name. For a
prepared statement using question mark placeholders, this will be the
1-indexed position of the parameter.
Using the following code I get an error stating invalid number of parameters.
$stmt = $this->db->PrepareSP("DECLARE SONUC VREPORT_ARRAY; BEGIN ZDS.ADMIN_REPORT(:SORGU_TARIH,:SONUC); END;");
$this->db->InParameter($stmt,$DATA['SORGU_TARIH'],'SORGU_TARIH');
$this->db->OutParameter($stmt,$output,'SONUC');
$rs = $this->db->Execute($stmt);
The second parameter named SONUC is of VARRAY / TABLE type. I cannot be sure whether this kind of return type is unsopperted or I'm missing something else. I'm using adodb library for database operations.
Edit: The following is the error message I got running the procedure call.
oci8 error: [6550: ORA-06550: line 1, column 36: PLS-00306: wrong number or types of arguments in call to 'ADMIN_REPORT' ORA-06550: line 1, column 36: PL/SQL: Statement ignored] in EXECUTE("Array")
Edit 2: After a ton of trials and wasted hours, it is still not working. The application has other statements calling stored procedures successfully (none of them have a return output parameter) . They are all executed through Execute method directly. PrepareSP and InParameter/OutParameter was never used.
Today I encountered a bug (in PDO) I never saw before, but is kinda obvious when you think about it.
I got the following error:
Warning: PDOStatement::execute() [pdostatement.execute]: SQLSTATE[HY093]: Invalid parameter number:
The query I was using was similar to the following:
SELECT
x
FROM
y
WHERE
-- CHECKING IF X = :Z --
x = :y
AND
1 = 2
Obviously I had more parameters and a longer query.
Why does it give me this error?
The solution is obvious: PDO disregards comments as such and tries to bind the non-existent variable ':Z'. You can't use parameters in comments in PDO (unless you do bind them).
There's a similar bug using question marks in comments.