Data not getting fetched from Oracle in PHP using WAMP Server - php

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.

Related

Error Handling PHP Oracle Database

I am trying to throw implement some error handling using Oracle and PHP. If I try to insert the statement into the DB table where the PK already exists, there is no INSERT performed - yet it returns that the data was added - when really it isnt - Need some help with the Error HAndling
require('connection.inc');
require('connection_db.inc');
$conn = db_connect();
$sql = oci_parse($conn,"INSERT INTO Schema.TableA (DOE, Trips) VALUES (:doe, :trp)");
oci_bind_by_name($sql, ':doe', $f1);
oci_bind_by_name($sql, ':trp', $f2);
oci_execute($sql);
<?
if($sql)
{
echo("Input data has been added<br><br>");
echo("<a href='link1.php'>View Links</a>");
}
else
{
echo("Input data has failed");
echo "</div>";
}
?>
You are evaluating the statement identifier $sql and not the result of the oci_execute call ...
oci_execute will return true if successful and false in case the query failed. See http://php.net/manual/en/function.oci-execute.php
$conn = oci_connect('hr', 'welcome', 'localhost/XE');
$stid = oci_parse($conn, 'SELECT * FROM employees');
$result = oci_execute($stid);
if(true === $result){
// Query successfully executed
echo "Hooary";
} else {
// Something went wrong
$e = oci_error($stid);
echo "Error: " . $e['message'];
}
Small tip, judging from the code you posted you seem to be in the process of learning php, i'd say take a look at PDO if you want to have a safer and easier way of interacting with your database. There is an oci driver available for PDO.
http://php.net/manual/en/book.pdo.php
http://php.net/manual/en/ref.pdo-oci.php

Querying Stored Procedure in Oracle via PHP - Not Working

I simply don't get it.
I can connect fine to the Oracle database, but my account can only execute stored procedures. So I try to use one.
echo "before";
$nrows = '';
$stid = oci_parse($conn, 'begin :r := AR_INTEGRATIONS.F_SRVCIMPROVE_ACCNT_INCS(:p); end');
oci_bind_by_name($stid, ':p', '');
oci_bind_by_name($stid, ':r', $nrows);
if(!oci_execute($stid)){
$e = oci_error();
print htmlentities($e['message']);
exit;
}
echo "<br/>After";
When I load this on my browser, it's blank. But when I comment out the oci_bind_by_name() lines, it displays before but not after.
This is the first time I'm using PHP to connect to Oracle and execute queries. It's very different from just using MySQL.
What's going on?

Querying an Oracle Database via Php Script: Insufficient Privileges

I'm trying to query a remote Oracle database through a PHP script. I'm running WAMP server. The Oracle database is read only. I have no problem connecting using the PHP script but I get errors on the oci_execute command.
This is the script I use:
<?php
$c = oci_connect("username", "password", "oracle_SID");
if (!$c) {
$e = oci_error();
trigger_error('Could not connect to database: '. $e['message'],E_USER_ERROR);
}
$s = oci_parse($c, 'Select * from fdma.t_title_stage');
if (!$s) {
$e = oci_error($c);
trigger_error('Could not parse statement: '. $e['message'], E_USER_ERROR);
}
$r = oci_execute($s);
if (!$r) {
$e = oci_error($s);
trigger_error('Could not execute statement: '. $e['message'], E_USER_ERROR);
}
oci_free_statement($stid);
oci_close($conn);
?>
These are the errors I'm getting when I run the script:
If the database is read-only I should be able to run a select * query against it, right?
Oracle has no concept of a database being "read-only". The user you're connecting with may not have any create/insert/update/delete rights, which would make the database read-only to this user, but it's a property of the user, not the database.
The error you're getting, in conjunction with the sql statement (... from fdma.t_title_stage) seems like you're connecting with a user that doesn't even have select rights on fdma's t_title_stage table. Try loggin in as fdma, the grant select on t_title_stage to xxx with xxx being the username you're using in your oci_connect statement.

Trying to execute a SELECT statement in MYSQL but it is not working

I believe I have the syntax correct, at least according to my textbook. This is just a piece of the file as the other info is irrelevant to my problem. The table name is user, as well as the column name is user. I don't believe this to be the problem, as other sql statements work. Though it isn't the smartest thing to do I know :) Anyone see an error?
try {
$db=new PDO("mysql:host=$db_host;dbname=$db_name",
$db_user,$db_pass);
} catch (PDOException $e) {
exit("Error connecting to database: " . $e->getMessage());
}
$user=$_SESSION["user"];
$pickselect = "SELECT game1 FROM user WHERE user='$user' ";
$pickedyet = $db->prepare($pickselect);
$pickedyet->execute();
echo $pickselect;
if ($pickedyet == "0")
{
echo '<form method="post" action="makepicks.php">
<h2>Game 1</h2>......'
Since you're seemingly using prepared statements, I'd recommend using them to their fullest extent so that you can avoid traditional problems like SQL injection (this is when someone passes malicious SQL code to your application, it's partially avoided by cleansing user inputs and/or using bound prepared statements).
Beyond that, you've got to actually fetch the results of your query in order to display them (assuming that's your goal). PHP has very strong documentation with good examples. Here are some links: fetchAll; prepare; bindParam.
Here is an example:
try
{
$db = new PDO("mysql:host=$db_host;dbname=$db_name",
$db_user, $db_pass);
}
catch (PDOException $e)
{
exit('Error connecting to database: ' . $e->getMessage());
}
$user = $_SESSION['user'];
$pickedyet = $db->prepare('SELECT game1 FROM user WHERE user = :user');
/* Bind the parameter :user using bindParam - no need for quotes */
$pickedyet->bindParam(':user', $user);
$pickedyet->execute();
/* fetchAll used for example, you may want to just fetch one row (see fetch) */
$results = $pickedyet->fetchAll(PDO::FETCH_ASSOC);
/* Dump the $results variable, which should be a multi-dimensional array */
var_dump($results);
EDIT - I'm also assuming that there is a table called 'user' with a column called 'user' and another column called 'game1' (i.e. that your SQL statement is correct aside from the usage of bound parameters).
<?php
session_start();
$db_user = 'example';
$db_pass = 'xxxxx';
try
{
// nothing was wrong here - using braces is better since it remove any confusion as to what the variable name is
$db=new PDO( "mysql:host={$db_host}dbname={$db_name}", $db_user, $db_pass);
}
catch ( Exception $e ) // catch all exceptions here just in case
{
exit( "Error connecting to database: " . $e->getMessage() );
}
// this line is unecessary unless you're using it later.
//$user = $_SESSION["user"];
// no need for a new variable here, just send it directly to the prepare method
// $pickselect = '...';
// also, I changed it to a * to get the entire record.
$statement = $db->prepare( "SELECT * FROM user WHERE user=:user" );
// http://www.php.net/manual/en/pdostatement.bindvalue.php
$statement->bindValue( ':user', $_SESSION['user'], PDO::PARAM_STR );
$statement->execute();
// http://www.php.net/manual/en/pdostatement.fetch.php
// fetches an object representing the db row.
// PDO::FETCH_ASSOC is another possibility
$userRow = $statement->fetch( PDO::FETCH_OBJ );
var_dump( $userRow );
echo $userRow->game1;
Change this user=$user with this user='$user'. Please, note the single quotes.
Moreover, you are executing the query $pickedyet->execute(); but then you do echo $pickselect; which is nothing different from the string that contains the query.
Little hints:
You've to retrieve the result of the query execution.
You're using prepared statement which are very good but you're not really using they because you're not doing any binding.

PDO not returning results from SELECT on more than 1 column

The server is running PHP 5.2.8. PDO has mysql 5.1.30 drivers installed.
Alright, so I am trying to figure out some PDO ( and this is just killing me. When I run the code below, I get the expected results, no problem.
However, whenever I try to add more than one column (or *) to the SELECT, there is no reply from the query - no results whatsoever. I have tried everything - I know it must be something simple. Any suggestions as to why more than one column fails to return any rows?
$hostname = "localhost";
$dbname = "dbname";
$username = "username";
$password = "password";
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$sql = "SELECT LastName FROM staff";
foreach ($dbh->query($sql) as $row) {
echo $row['LastName'] . '<br />';
}
/*** close the database connection ***/
$dbh = null;
} catch(PDOException $e) {
echo $e->getMessage();
}
Again, if I try to add columns in the statement stored in $sql to anything other than a single column, I get bupkis. For example:
SELECT FirstName, LastName FROM staff
returns zero results. Both columns exist - if requested separately, they return expected results. When combined, the query takes quite some time, then returns nothing.
No exception is caught by the catch block.
I think you have a number of issues here, mostly in your code that handles reading the values returned by the query. I have taken the liberty of changing a few things and rewriting this to use prepare statements, which is a function that PDO provides that you should take advantage of.
On prepare statements:
Why use them: http://dev.mysql.com/tech-resources/articles/4.1/prepared-statements.html
PHP PDO doc: http://php.net/manual/en/pdo.prepare.php
Here is the core code:
try {
//open database
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
//define sql query
$sql = "SELECT LastName FROM staff";
//prepare the query for execution
$qresult = $dbh->prepare($sql);
//insert code below to handle parameters to the sql query here
//execute the query
$qresult->execute();
//fetch the results
foreach ($qresult->fetch(PDO::FETCH_ASSOC) as $row)
{
echo $row['LastName'] . '<br />';
}
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
$qresult = null; //close the result set
$dbh = null; //close the database
Note, that I have replaced the call to query() with a couple of lines that call prepare() then execute(). You can then easily insert the following lines in between the prepare() and execute() calls to handle passing parameterized queries. This will help reduce chances of sql injection.
I have also changed the way you are accessing the retirned valued by specifying that I want them returned as and associative array, PDO::FETCH_ASSOC. This will get you a result set that you can iterate through like you would have using the old mysql interfaces.
If your query was a parameterized query like:
$sql="SELECT LastName FROM staff WHERE LastName=':lastname'";
where :lastname is the parameter.
Here is the code you would insert at the comment to handle this, (this code will handle multiple parameters. Simply add additional elements to the $param array):
//bind parameters to the prepared statement
$param = array(':lastname'=>'Jones');
foreach ($param as $key => $value) {
$qresult->bindValue($key,$value);
}
Make sure you separate the columns in the SELECT with a comma (space on either side of the comma is okay, but not required). If you want to select all columns, have only a * with no other characters.

Categories