PHP - call SQL Server procedure via ODBC error - php

Ugh. I've spent hours searching for a solution for this, so it's probably something simple. I have a stored procedure in SQL Server (2008) that I'm trying to call from PHP code. I'm using ODBC, and everything works if I use a hard-coded SQL statement.
But I'm trying to call a stored procedure that returns a set of rows (cursor, dataset, etc.), passing two parameters. When I run the code through my browser I just get a 500 http error. It is bombing on the odbc_execute() line. Here's my code:
// DSN-less connection:
$conn = odbc_connect("Driver={SQL Server};Server=$server;Database=$database;", '', '');
if (!$conn)
{exit("Connection Failed: " . $conn);}
$fromDate = new DateTime('2012-1-1');
$toDate = new DateTime('2013-12-31');
$sql = odbc_prepare($conn, "{call GET_EVENTS_BY_DATE_RANGE(?, ?)}");
$params = array($fromDate, $toDate);
$result = odbc_execute($sql, $params);
if ( $result === false)
{
exit("Query failed");
}
odbc_close($conn);
Again, no problems until it hits the odbc_execute() function. Any help is appreciated.

Related

Data not getting fetched from Oracle in PHP using WAMP Server

I am trying to fetch data from Oracle in PHP on WAMP Server with the following code but, the data is not getting fetched, neither am i getting any error. But when i execute the same query on Oracle directly, i am getting the data. Also, with same connection parameters within the same php file, i am able to fetch data for another query
$server = "localhost";
$sid = "xe";
$user = "hrs";
$passwd = "hrs123";
$conn = oci_connect($user, $passwd, $server."/".$sid);
if (!$conn) {
$e = oci_error();
echo $m['message'], "\n";
exit;
}
else{
}
$staffno = test_input($_POST['field1']);
if($staffno!='')
{
$exempquery="select stno as stno, nvl(ffname,'')||' '||nvl(lname,'') as fname, substr(gradep,0,1) as grd, nvl(decode(sex,'M','MALE','F','FEMALE'),'') as sex, to_char(birth_dt,'dd-mm-yyyy') as birthdt, to_char(sep_dt,'dd-mm-yyyy') as sepdt, to_char(ret_dt,'dd-mm-yyyy') as retdt, sepdes from emp_master where stno='$staffno' and ((sep_dt<='31-03-2013' and ret_dt<='31-03-2013') or (sep_dt is null and ret_dt<='31-03-2013'))";
$exempstid=oci_parse($conn,$exempquery);
$exempchk=oci_execute($exempstid);
$exemprow=oci_fetch_array($exempstid, OCI_BOTH);
$name=$exemprow['FNAME'];
$grd=$exemprow['GRD'];
$sex=$exemprow['SEX'];
$birthdt=$exemprow['BIRTHDT'];
$sepdt=$exemprow['SEPDT'];
$retdt=$exemprow['RETDT'];
$sepdes=$exemprow['SEPDES'];
}
The database connection is working fine.
Any help would be highly appreciated.
Check your webserver log files for errors
During development, you could do worse than add this to the top of the script to make sure errors are shown:
error_reporting(E_ALL);
ini_set('display_errors', 'On');
Remember to remove these where you put your script in productions
Consider using a HEREDOC or NOWDOC for complex SQL statements, see PHP 5.3 "NOWDOCS" make SQL escaping easier.
Use OCI_ASSOC instead of the (default) OCI_BOTH.
Before going too far, you MUST rewrite your SQL statement to use a bind variable because the way you concatenate $staffno into the statement is a security risk (and will affect performance & scalability). I don't have your data, but something like this is the way to go:
$exempquery="select stno as stno, nvl(ffname,'')||' '||nvl(lname,'') as fname, substr(gradep,0,1) as grd, nvl(decode(sex,'M','MALE','F','FEMALE'),'') as sex, to_char(birth_dt,'dd-mm-yyyy') as birthdt, to_char(sep_dt,'dd-mm-yyyy') as sepdt, to_char(ret_dt,'dd-mm-yyyy') as retdt, sepdes from emp_master where stno = :staffnobv and ((sep_dt<='31-03-2013' and ret_dt<='31-03-2013') or (sep_dt is null and ret_dt<='31-03-2013'))";
$s = oci_parse($c, $exempquery);
if (!$s) {
$m = oci_error($c);
trigger_error('Could not parse statement: '. $m['message'], E_USER_ERROR);
}
$r = oci_bind_by_name($s, ":staffnobv", $staffno);
if (!$r) {
$m = oci_error($s);
trigger_error('Could not bind a parameter: '. $m['message'], E_USER_ERROR);
}
$r = oci_execute($s);
if (!$r) {
$m = oci_error($s);
trigger_error('Could not execute statement: '. $m['message'], E_USER_ERROR);
}
You possibly want one or more bind variables for the date too, unless it really will never, ever change.

Simple MySQL call to select an integer at a specific key not working?

I have this PHP:
<?php
$client_ip = $_SERVER['REMOTE_ADDR'];
$connection = new mysqli("localhost", "MyNotSoSecretUsername", "MySuperSecretPassword", "MyNotSoSecretDatabaseName");
if ($connection->connect_error) {
die("Connection failed: " . $Connection->connect_error);
}
$check_emails_sent_query = "SELECT `emails` FROM `email-ips` WHERE `ip`='11.111.111.111'";
$check_emails_sent_result = $connection->query($check_emails_sent_query);
echo $check_emails_sent_result;
?>
This is a small piece of a much larger function on my site. This snippet is simply intended to get the value of the "emails" column (Which is an int column if that makes a difference) of my table where the IP matches the client's IP.
I added a fake entry for 11.111.111.111 in my database, and used the exact same query on PHPmyAdmin's SQL console. I got a result on the PHPmyAdmin console, but nothing is echoed here.
I have also checked that the connection is good, as you can see in my code. Additionally, I pasted another query from another part of my function, which retrieved its data just fine.
AS stupid or obvious as it may be, I can't seem to figure out why this particular query out of almost twenty won't retrieve its data?
Mysqli query() returns and object. Using the object:
<?php
$client_ip = $_SERVER['REMOTE_ADDR'];
$connection = new mysqli("localhost", "MyNotSoSecretUsername", "MySuperSecretPassword", "MyNotSoSecretDatabaseName");
if ($connection->connect_error)
{
die("Connection failed: " . $Connection->connect_error);
}
$check_emails_sent_query = "SELECT `emails` FROM `email-ips` WHERE `ip`='11.111.111.111'";
if ($check_emails_sent_result = $connection->query($check_emails_sent_query))
{
while($obj = $check_emails_sent_result->fetch_object())
{
$echo $obj->emails;
}
}
?>
You could use fetch_row() instead of fetch_object().
Documentation for the object is here:
http://php.net/manual/en/class.mysqli-result.php
mysqli_query()
Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or
EXPLAIN queries mysqli_query() will return a mysqli_result object. For
other successful queries mysqli_query() will return TRUE.
You can get your email by using
if ($result = $connection->query($check_emails_sent_query)) {
while ($row = $result->fetch_row()) {
printf ("%s (%s)\n", $row[0]);
}
}

Error message: Database Query failed

For some reason, the following code inside the query works in my MySQL command console, yet when I try to run it as a Query in PHP, something keeps going wrong and I'm not sure what. Here is the code I've done so far.
//2. Perform database query
$query = "SELECT skills.element_id, content_model_reference.element_id, element_name FROM skills, content_model_reference WHERE (skills.element_id = content_model_reference.element_id)";
$result = mysql_query($query);
//Tests if there was a query error
if(!$result){
die("Database query failed.");
}
Is there something preventing the code that worked in MySQL (The line with SELECT) from working, or is my syntax somehow wrong?
EDIT: So it's saying I didn't select a database. Yet I thought I had. Here is the code above it:
//1. Create a database connection
$dbhost = "host"; //Host: Can be either an IP address, or a domain (like google.com).
$dbuser = "user";//User: The user that is connecting to the database.
$dbpass = "pass";//Password: This is the password that the user is using.
$dbname = "db";//Name: This is the name of the database.
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);//The value, 'handle,' is the connection.
//Test if connection occurred. Die ends the program/php, and in this case, also prints a message
if(mysqli_connect_errno()){
die("Database connection failed: ".
mysqli_connect_error().
" (". mysqli_connect_errno() . ")"
);
}
Like I said, the error message I am getting is pertaining only to the query, the server is fine with my database connection.
You're using mysqli_* for the connection, but you're using mysql_* for the QUERY... don't think you can do that, has to be one or the other (MYSQLI_ preffered). Also the query should be:
$result = mysqli_query($connection,$query);

PHP - How do I tell why mssql_connect() didn't work?

I'm using PHP 5.2, and normally mssql_connect works fine - but I'm trying to connect to a new MS SQL server, and it won't connect. I've probably got something wrong in the connection details or credentials, but I have no way of telling as I can't get an error message.
The mssql_connect() method returns false, and no connection is available.
mssql_get_last_message() returns nothing - so how do I tell why my connection failed?
Anyone got any ideas?
In MySQL I'd use mysql_error - but there doesn't seem to be an equivalent for ms_sql.
[EDIT]
This question is not a duplicate of "MSSQL_CONNECT returns nothing - no error but no response either" - I'm using php 5.2, and the code works fine for other connection details. I need to figure out how to output what the connection error is - not what the problem is with connecting.
[EDIT2]
To clarify:
the extension is enabled on the server
the code works fine for existing connection details
I am using new connection details and don't know if the hostname or password is wrong
I know the code isn't connecting because I check to see if it's connected
I want to find out the connection error - like you can with MySQL.
Sample code below:
$db_connection = mssql_connect($host, $user, $pass);
$db = mssql_select_db($dbname, $db_connection);
if (!$db_connection) {
echo "No connection";
echo "connection failed because: " . ???????;
die;
}
What do I put in place of ??????? to get the connection error message?
//Database Connection by PDO (MS SQL Server, PHP)
$serverName='localhost';
$database='TreeDB';
$uid='sa';
$pwd='sa*5234';
$dbo = new PDO("sqlsrv:server=$serverName ; Database = $database;ConnectionPooling=0", $uid, $pwd);
//var_dump($dbo);
//Database Query
$sql = "SELECT node.id, node.name, COUNT(parent.id) - 1 AS depth, node.lft, node.rgt
FROM dbo.OrgTree AS node CROSS JOIN dbo.OrgTree AS parent
WHERE (node.lft BETWEEN parent.lft AND parent.rgt)
GROUP BY node.id, node.name, node.lft, node.rgt
ORDER BY node.lft";
//Execute Query
$sql = $dbo->prepare($sql);
$sql->execute();
$qry = $sql->fetchAll();
foreach ($qry as $fetch)
{
$tree[] = $fetch;
}
//print_r($tree);
See below
<?php
// Server in the this format: <computer>\<instance name> or
// <server>,<port> when using a non default port number
$server = 'KALLESPC\SQLEXPRESS';
// Connect to MSSQL
$link = mssql_connect($server, 'sa', 'phpfi');
if (!$link) {
die('Something went wrong while connecting to MSSQL');
}
?>
In this way you can display error if connection fails.
Ref: http://www.php.net/manual/en/function.mssql-connect.php

PHP mssql_init('mydb') failing. Stuck trying to call trivial Stored Proc from PHP

Is there any way to turn on driver logging for PHP/MySQL 5? Is there a log that shows internally what's going on... like all database activity? Lower-level errors?
I'm trying to get a trivial PHP page to call a trivial stored proc on Windows 7. mysql_error isn't returning any error message when the mssql_init() fails.
Thinking it might be a permission problem I created a new user and I get the same results:
CREATE USER 'user1'#'localhost' IDENTIFIED BY 'pass1';
GRANT ALL ON *.* TO 'user1'#'localhost';
Here is the code:
create table trace (
trace varchar(50) not null,
datet datetime not null
);
drop procedure if exists mark;
delimiter !!
create procedure mark()
begin
insert into trace (trace,datet) values ('mark',now());
end; !!
delimiter ;
I can call the SP from MySQL Workbench just fine:
call mark();
Here is the PHP page:
<?php
$connection = mysql_connect('localhost', 'user1', 'pass1');
if (!$connection) {
die('Could not connect: ' . mysql_error());
}
$sel = mysql_select_db('tw');
if (!$sel) {
die('Could not select_db: ' . mysql_error());
}
//$stmt = mssql_init('mark', $connection);
//$stmt = mssql_init('mark', $sel);
$stmt = mssql_init('mark');
if (!$stmt) {
die('Could not init: ' . mysql_error());
}
$result = mssql_execute($stmt);
if (!$result) {
die('Could not execute: ' . mysql_error());
}
mysql_free_result($result);
mssql_free_statement($stmt);
mysql_close($connection);
printf("DONE<br />");
?>
Other proof of concept pages which demonstrate insert, *select,* etc, are working just fine. Just can't get a stupid stored procedure to run from a web page!
The page output is only this:
Could not init:
(The PHP mssql_init documentation page isn't very helpful and seems to have a typo as the $link variable isn't defined.)
You're using mssql_init (Note MS SQL) to execute a stored procedure on My SQL.
Obviously the mssql_init() function can't find your Microsoft SQL Server connection 'cause you don't have one. You should only be using mysql_ functions for a MySQL connection.
And MySQL doesn't have a special function for calling stored procedures. mysql_query('CALL mark()') will work just fine.

Categories