Error Handling PHP Oracle Database - php

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

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.

Retrieving row from MySQL Database via PHP

Please bear with me, I'm new here - and I'm just starting out with PHP. To be honest, this is my first project, so please be merciful. :)
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1"));
echo $row['message'];
Would this be enough to fetch the message from the database based upon a pre-defined '$code' variable? I have already successfully connected to the database.
This block of code seems to return nothing - just a blank space. :(
I would be grateful of any suggestions and help. :)
UPDATE:
Code now reads:
<?php
error_reporting(E_ALL);
// Start MySQL Connection
REMOVED FOR SECURITY
// Check if code exists
if(mysql_num_rows(mysql_query("SELECT code FROM data WHERE code = '$code'"))){
echo 'Hooray, that works!';
$row = mysql_fetch_array(mysql_query("SELECT message FROM data WHERE code = '". (int) $code ."' LIMIT 1")) or die(mysql_error());
echo $row['message'];
}
else {
echo 'That code could not be found. Please try again!';
}
mysql_close();
?>
It's best not to chain functions together like this since if the query fails the fetch will also appear to fail and cause an error message that may not actually indicate what the real problem was.
Also, don't wrap quotes around integer values in your SQL queries.
if(! $rs = mysql_query("SELECT message FROM data WHERE code = ". (int) $code ." LIMIT 1") ) {
die('query failed! ' . mysql_error());
}
$row = mysql_fetch_array($rs);
echo $row['message'];
And the standard "don't use mysql_* functions because deprecated blah blah blah"...
If you're still getting a blank response you might want to check that you're not getting 0 rows returned. Further testing would also include echoing out the query to see if it's formed properly, and running it yourself to see if it's returning the correct data.
Some comments:
Don't use mysql_*. It's deprecated. use either mysqli_* functions or the PDO Library
Whenever you enter a value into a query (here, $code), use either mysqli_real_escape_string or PDO's quote function to prevent SQL injection
Always check for errors.
Example using PDO:
//connect to database
$user = 'dbuser'; //mysql user name
$pass = 'dbpass'; //mysql password
$db = 'dbname'; //name of mysql database
$dsn = 'mysql:host=localhost;dbname='.$db;
try {
$con = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
echo 'Could not connect to database: ' . $e->getMessage();
die();
}
//escape code to prevent SQL injection
$code = $con->quote($code);
//prepare the SQL string
$sql = 'SELECT message FROM data WHERE code='.$code.' LIMIT 1';
//do the sql query
$res = $con->query($sql);
if(!$res) {
echo "something wrong with the query!";
echo $sql; //for development only; don't output SQL in live server!
die();
}
//get result
$row = $res->fetch(PDO::FETCH_ASSOC);
//output result
print_r($row);

How to check if a MySQL query using the legacy API was successful?

How do I check if a MySQL query is successful other than using die()
I'm trying to achieve...
mysql_query($query);
if(success){
//move file
}
else if(fail){
//display error
}
This is the first example in the manual page for mysql_query:
$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
die('Invalid query: ' . mysql_error());
}
If you wish to use something other than die, then I'd suggest trigger_error.
You can use mysql_errno() for this too.
$result = mysql_query($query);
if(mysql_errno()){
echo "MySQL error ".mysql_errno().": "
.mysql_error()."\n<br>When executing <br>\n$query\n<br>";
}
If your query failed, you'll receive a FALSE return value. Otherwise you'll receive a resource/TRUE.
$result = mysql_query($query);
if(!$result){
/* check for error, die, etc */
}
Basically as long as it's not false, you're fine. Afterwards, you can continue your code.
if(!$result)
This part of the code actually runs your query.
mysql_query function is used for executing mysql query in php. mysql_query returns false if query execution fails.Alternatively you can try using mysql_error() function
For e.g
$result=mysql_query($sql)
or
die(mysql_error());
In above code snippet if query execution fails then it will terminate the execution and display mysql error while execution of sql query.
put only :
or die(mysqli_error());
after your query
and it will retern the error as echo
example
// "Your Query" means you can put "Select/Update/Delete/Set" queries here
$qfetch = mysqli_fetch_assoc(mysqli_query("your query")) or die(mysqli_error());
if (mysqli_errno()) {
echo 'error' . mysqli_error();
die();
}
if using MySQLi bind_param try to put this line above the query
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

mysql_query not working

Here's PHP code that I'm using:
$query="select * from `myTable` where `email`='$email' limit 0,1";
if(empty($conn))
{
echo "not connected".PHP_EOL;
}
$result = mysql_query($query,$conn);
$row = mysql_fetch_array($result);
if(empty($row))
{
....
When the query is executed in phpmyadmin, I get a single row selected.
However, when I execute the code in php, the row is always empty.
The same goes for several other queries that I've tried to execute. mysql_query always fails.
What could be wrong?
I do not feel there is enough of the code to see what is going on. But based on just what you are showing us, after you get the $result and assign it to $row you have a if statement
if(empty($row)) {...doing something secret...}
which means if something was returned like the row you are expecting NOTHING would happen because (empty($row)) would be false and not execute.
Try this using PDO:
<?php
$email = "example#example.com";
try {
//Instantiate PDO connection
$conn = new PDO("mysql:host=localhost;dbname=db_name", "user", "pass");
//Make PDO errors to throw exceptions, which are easier to handle
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Make PDO to not emulate prepares, which adds to security
$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$query = <<<MySQL
SELECT *
FROM `myTable`
WHERE `email`=:email
LIMIT 0,1;
MySQL;
//Prepare the statement
$stmt = $conn->prepare($query);
$stmt->bindParam(":email", $email, PDO::PARAM_STR);
$stmt->execute();
//Work with results
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
//Do stuff with $row
}
}
catch (PDOException $e) {
//Catch any PDOExceptions errors that were thrown during the operation
die("An error has occurred in the database: " . $e->getMessage());
}
Using mysql_* functions is highly discouraged. It's a guarantee to produce broken code. Please learn PDO or MySQLi from the links in the comment I gave you, and use those instead.
First, confirm $email's value. Echo it right before defining $query to make sure it's what you think it is.
If you've already done that, then you know that's the problem--instead, it's likely that your link identifier $conn is the problem. Instead of using a link identifier, try leaving the second parameter of your query empty, and instead run mysql_connect() at the beginning of your script. That's the best way to do things 99.5% of the time.
See: http://php.net/manual/en/function.mysql-connect.php

How to show SQL errors in SQLite?

Using SQLite in PHP (thus using PDO), I have this code:
try {
$db = new PDO("sqlite:C:\Program Files\Spiceworks\db\spiceworks_prod.db");
echo "Done.<br /><b>";
$query = "SELECT id FROM Devices LIMIT 5";
echo "Results: ";
$result = $db->query($query);
while ($row = $result->fetchArray()) {
print_r($row)."|";
}
}
catch(PDOException $e) {
echo $e->getMessage();
}
But that does not print out any data from the SQL. I know the database has data in it and the connection is valid. If I change the query to say:
$query = "SELECT BLAHid FROM FakeDevices LIMIT 5";
Nothing changes. Nothing from SQL gets printed out again, and I see no errors even though this is clearly an invalid SQL query.
In both situations, the "Done" and "Results" gets printed out okay. How can I print out SQL errors, like if the query is invalid?
You need to tell PDO to throw exceptions. You can do that by adding the following line after you connect to the database:
$db = new PDO("sqlite:C:\Program Files\Spiceworks\db\spiceworks_prod.db");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
That way you can catch all exceptions except for a possible problem with the first line, the database connection itself.

Categories