Invalid parameter number, SQL state S1093 php odbc mssql - php

We have a uni student doing work experience at the moment and he's doing a Wordpress prototype for us (as we have neither Wordpress or PHP experience).
It's running on a Windows server and while Wordpress itself is running in mySQL, as all our existing databases are in MS SQL Server 2005/2008 and he's trying to call a stored procedure in a php page using this code:
$connection = odbc_connect('DB', 'UNAME', 'PWORD');
$request = odbc_prepare($connection, "CALL ProcName(?, ?, ?)");
if(!$request) die("Could not prepare statement:" . odbc_errormsg());
$result = odbc_execute($request, array("var1", "var2", "var3"));
if(!$result) die("Could not execute statement:" . odbc_errormsg());
The stored procedure is like this:
ROCEDURE [dbo].[ProcName]
(#option1 varchar(50),
#option2 varchar(50),
#option3 varchar(50))
AS
... lots of logic end with...
select * from tblName
The stored procedure is used both by .net pages and Livelink CMS pages and works correctly but when we try to call it from php, it errors with:
"odbc_execute(): SQL error: [Microsoft][ODBC SQL Server Driver]Invalid parameter number, SQL state S1093 in SQLDescribeParameter in C:\inetpub\wordpress\test.php on line 29"
Strangely, if we rename the procedure call to a non existant stored procedure, it errors with exactly the same thing rather than a stored procedure cannot be found type of error.
We can run sql directly i.e. "select * from etc" and it will return data but we can't call stored procedures (which we use for everything of course!).
Any idea where he could be going wrong?

As I can see from the error message, the error should come from the ODBC driver, because from it's perspective the parameter number differs from prepare to execute statements.
Ask your student to try this approach:
$parms=array("var1", "var2", "var3");
if (!odbc_execute($request, &$parms)) die("odbc_execute failed");

I got the same error when I was doing an native SQL query from Java EE/Hibernate. I was querying "SELECT Count (1) From Table" and I made the mistake of including a mapping class as a parameter. COUNT(1) returns an integer, so it doesn't need to be mapped. Hope that helps.

Related

odbc_fetch_array(): SQL error is saying field refers to more than one table yet should not. Microsoft Access ODBC PHP

I have the following sql statement
$sql=
"SELECT wr.SortOrder, wr.webRequests_ID, wr.PQ_ID, pq.QText,wr.The_Answer, wr.webtmporders_detail_ID
FROM tbl_Preference_Questions as pq
INNER JOIN tblwebtmporders_detail_Requests as wr ON pq.PQ_ID = wr.PQ_ID
WHERE wr.webtmporders_detail_ID = 42569
ORDER BY wr.SortOrder";
I get the records thru a function. the varialbe $mdbFilename is the path to the Access database.
$conn=odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$mdbFilename",'','',SQL_CUR_USE_ODBC);
$result_id = odbc_exec($conn, $sql);
$results = all_odbc_rows($result_id);
function all_odbc_rows($result_id)
{
$tmp_arr = "";
while($row = odbc_fetch_array($result_id)){
// this needs to be in my program code because ODBC / Access DB query will not accept escaping of single quotes. single quotes
// must be replaced by two single quotes for the sql passed to access via ODBC to work.
foreach ($row as $k => $value)
{
$v = strip_tags($value);
$row[$k] = str_replace("\\","",str_replace("'","''",$v));
}
$tmp_arr[] = $row;
}
return $tmp_arr;
}
yet I am getting the following PHP warning
odbc_fetch_array(): SQL error: [Microsoft][ODBC Microsoft Access Driver] The specified field '`PQ_ID`'
could refer to more than one table listed in the FROM clause of your SQL statement., SQL state S1000
in SQLGetData
If I run this sql in Microsoft Access Query builder, it returns 7 records with no problem. Yet I get an error when I run the sql statement thru ODBC in PHP. I get the warning, and ODBC does not return any records. Cannot work out why this join is not working?
I tried getting rid of the wr. and the pq. table identifiers and replaced them with the full table names in the sequel statement, but this did not work.
Any one have any ideas?
Thank you.
btw, if I take the wr.PQ_ID field out of the sql statement, ODBC can run the query succesfully.
This is very strange.
Here is the query builder in Access for this query I am trying to run in ODBC PHP
And SQL statement in in query builder in MS-Access
And the Result
So It works in MS Access, but not in ODBC call from PHP
weird.
Well, I found someone on php.net that brought up the same issue. Yet they were using SQL Server. I am using MS-Access .mdb file. They were able to use aliases with SQL Server database engine. Aliases have not worked for me. So I think the solution is that the joining fields / columns, must have different names, if using MS-Access Database, for ODBC odbc_fetch_array() or odbc_fetch_object() to work in a join sql statement.

How to call a stored procedure in CodeIgniter USING SQL SERVER

I'm bulding my application using Codeigniter and SQL server as my database (I am using the SQLSRV PHP extension to connect to SQL ). The problem happens when I try to call Stored Procedures:
$query = $this->db->query(
"EXECUTE verificacion_fechas '".$codigo."',".$estado.",'".$llave_maestra."','".$fecha_actual."'");
Another way I have tried to create the query with less data is the following , however, it is generating an error:
Error Number: 01000 [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Ejecutando SQL directamente, sin cursor. EXECUTE provando15 34,2,'key05','2015-07-22'
I dont really know what im doing wrong. Can someone please help me?
remove the word Execute and it will work.
$query = $this->db->query(
"verificacion_fechas '".$codigo."',".$estado.",'".$llave_maestra."','".$fecha_actual."'");
Here's a sample on how to call a MYSQL STORED PROCEDURE in codeigniter
$this->db->query('CALL procedure_name());
Here's my solution:
first way(if you do not use a variable);
$query=$this->MSSQL->query("EXEC ProcedureName");
second way(if you use a variable);
$query =$this->MSSQL->query("EXEC ProcedureName '$var1','$var2','$var3' ");
or
$query =$this->MSSQL->query("EXEC ProcedureName #varName1='$var1',#varName2='$var2',#varName3='$var3' ");
Note:if you get result like empty array add SET NOCOUNT ON to after BEGIN in your procedure.

Syntax error or access violation, SQL state 37000. MSSQL though ODBC from PHP

I'm trying to execute a stored procedure in a ms sql database using the following php:
$query = "{CALL dbo.storedProc('functionName', $date, 'id";
$resultSet = odbc_prepare($connection, $query);
odbc_execute($resultSet, array());
odbc_result_all($resultSet);
The same stored procedure works fine for a different function, and the results are selected by date like so ($date is #Searchstr):
(EventStart >= #Searchstr AND EventStart < DATEADD(DD,1,#Searchstr))
However, when I run the code, it errors without giving any specific hints as to what's causing the error. When the query is run in management studio, the results are returned correctly.
SQL error: [Microsoft][ODBC SQL Server Driver]Syntax error or access violation, SQL state 37000 in SQLPrepare in ...
What's causing the query to error? Could it be an ODBC bug?
Thanks in advance,
Will
The query seems to be missing ')} at the end.

Calling odbc_fetch_array after executing a stored procedure in PHP gives error [Microsoft][ODBC SQL Server Driver]Invalid Descriptor Index

So, I'm trying to use ODBC to execute a stored procedure in an SQL database, but it returns the error
odbc_fetch_array() [function.odbc-fetch-array]:
SQL error: [Microsoft][ODBC SQL Server Driver]Invalid Descriptor Index,
SQL state S1002 in SQLGetData
Here's the PHP part, pretty standard
...
$id = 240
$user = "user";
$password = "password";
$server = "server";
$database = "database";
$con = odbc_connect("SERVER=$server;
DRIVER=SQL Server;
DATABASE=$database",
$user,
$password);
$res = odbc_exec($con, "exec usp_GetRelatedToID '$id'");
while($row = odbc_fetch_array($res)){
print_r($row);
}
Here's the Stored Procedure, really small and easy
CREATE PROCEDURE [dbo].[usp_GetRelatedToID]
#id int
AS
BEGIN
SET NOCOUNT ON;
SELECT AMENDMENT_ID, WDATE, ALTERATION, VER, REASON
FROM AMENDMENTS
WHERE AMENDMENT_ID = $id
END
Here's the Table schema for AMENDMENTS
(Column_name) (Type) (Nullable)
AMENDMENT_ID int no
RAD_MAIN_ID int yes
WDATE datetime yes
USR_ID int yes
ALTERATION varchar yes
REASON varchar yes
VER int yes
Identity Seed Increment Not For Replication
AMENDMENT_ID 1 1 0
constraint_type constraint_name constraint_keys
PRIMARY KEY (non-clustered) aaaaaAMENDMENTS1_PK AMENDMENT_ID
What's interesting is that it doesn't return the error if I remove the column VER from the procedure
Like this:
CREATE PROCEDURE [dbo].[usp_GetRelatedToID]
#id int
AS
BEGIN
SET NOCOUNT ON;
SELECT AMENDMENT_ID, WDATE, ALTERATION, REASON
FROM AMENDMENTS
WHERE AMENDMENT_ID = $id
END
Can anyone explain where I'm doing wrong and why this keep happening? I've got other stored procedures that give the same errors (some also share the column VER), and I've got stored procedures that don't.
I've tried different methods of fetching the data in PHP using odbc_prepare and odbc_execute with both query structures, {CALL usp_GetRelatedToID(?)}, but that just gave me more errors.
And for reasons I won't go into, I can't use mssql functions in PHP, ODBC is the only way I'm allowed to connect and query.
Oh, and executing the plain (original) query instead of in a stored procedure gives no errors.
EDIT
$stmt = odbc_prepare($con, "{CALL usp_GetRelatedToID($id)}");
$res = odbc_execute($stmt, array());
//or
$stmt = odbc_prepare($con, "{CALL usp_GetRelatedToID(?)}");
$res = odbc_execute($stmt, array($id));
Both return this error message:
Warning: odbc_execute() [function.odbc-execute]:
SQL error: [Microsoft][ODBC SQL Server Driver]Cursor type changed,
SQL state 01S02 in SQLExecute
I ran into this problem as well. The way I got around it was to use
odbc_exec($connection, $sql)
Instead of
odbc_execute($connection, $sql)
Per a user comment here
Comment was:
BTW. If anyone is banging his head about "cursor type changed" warning
while using execute with ORDER BY clause, then just use exec for
now (remember to addslashes for yourself).
In PHP 5.3 a Bug #43668
will be fixed and it will allow you to change a cursor type to
SQL_CUR_USE_ODBC
Note that you could also try to select a cursor type in odbc_connect, but that didn't work for me (much more problems appeared then it solved).
Apparently this is a bug in PHP, and will be patched per this
So try using odbc_exec() insted of odbc_execute() if you are having this problem.

mssql_fetch_array(): supplied argument is not a valid MS SQL-result resource

I am getting the above error using PHP trying to update an MS SQL server. Any idea what may be happening here? I am using a stored procedure as the basis of the update. I can successfully execute the sproc against the SQL server away from the PHP application.
Any advice/help would be appreciated.
mssql_fetch_array() should be used for SELECT commands, you won't get anything out of UPDATE, INSERT, or DELETE commands.
You can also pass a parameter to the resource by calling mssql_fetch_array($connection) assuming $connection is a valid connection to the DB.
Always test the return value of mssql_query(). If it's ===false mssql_get_last_message() can tell you why the query failed.
$query = 'SELECT x,y,z FROM [foo].[bar].[thingeling]';
$result = #mssql_query($query, $conn);
if(!$result) {
die('MSSQL error: ' . mssql_get_last_message());
}
For debugging purposes you might want to set mssql_min_message_severity and mssql_min_error_severity to more "talkative" values.

Categories