I want to print a value that taken from oracle database. but it is showing error.
Below is my code.
<?php
// Connects to the XE service (i.e. database) on the "localhost" machine
$conn = oci_connect('FUNREAD', 'clock24', '10.6.8.51:1525/DRFUNPD1');
if (!$conn)
{
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$atp1 = oci_parse($conn, 'select count(*) as count from ATP1.PENDING_MESSAGE');
oci_execute($atp1);
$atp1 = oci_fetch_array($atp1);
echo $atp11;
?>
But I am not getting right output. Below output I am getting.
Resource id #4
You're trying to echo a resource result, where what you need to do is to either retrieve the first row and output that, or loop over the results and output them:
while ($row = oci_fetch_array($atp1)) {
print_r($row);
}
Note that fundamentally it's probably a good idea not to re-use the $atp1 variable for both the query and the result set, use something more descriptive, e.g.:
$query = oci_parse($conn, 'select count(*) as count from ATP1.PENDING_MESSAGE');
oci_execute($query);
while ($row = oci_fetch_array($query)) {
print_r($row);
}
I'm pretty much copying this straight out of the manual (since I haven't used Oracle functions in PHP before)...
Related
I am a novice when it comes to working with JSON/PHP. I have been trying to get this to work based off this answer.
How to generate .json file with PHP?
I am trying to query a MySQL database to output it in a JSON format without having it write to a new file I.E. file.json since I am pulling dynamic data. I can create a script that creates a json array but, I need the output in a JSON format. The script I have been working with below from the example link above connects to the DB but, it is not populating with data. It just gives me this output. I added the DB connection check to check if the script was connecting to the DB.
Connected successfully{"streamers":[]}
This is the code I am currently working with. Is there anyone who could tell me what I am missing and could improve on. DB info removed for security reasons.
<?php
header('Content-type:application/json;charset=utf-8');
//Make connection to database
$db=new PDO('mysql:dbname=streamdb;host=localhost;','root','');
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
echo "Connected successfully";
//Prepare the query for analyzing
$sql=$db->prepare('select * from maintable');
$response = array();
$streamers = array();
$result=mysql_query($sql);
while($sql=mysql_fetch_array($result))
{
$displayname=$row['DisplayName'];
$streamkey=$row['StreamKey'];
$streamers[] = array('DisplayName'=> $displayname, 'StreamKey'=> $streamkey);
}
$response['streamers'] = $streamers;
echo stripslashes(json_encode($response));
?>
-Thanks!
First, use PDO only. No mysql_* functions.
Then your code should look like this:
$pdo = new PDO('mysql:host=...', 'username', 'password', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);
$result = $pdo->query('SELECT DisplayName, StreamKey FROM ...');
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
header('Content-Type: application/json;charset=utf-8');
echo json_encode(['streamers' => $rows],
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK);
The PDO::ERRMODE_EXCEPTION sets PDO to throw all errors as exceptions, so they can be handled in an easy and consistent way.
The PDO::FETCH_ASSOC sets fetchAll() to return rows as arrays where column names are used as array keys.
The json_encode() will take care of producing a valid JSON output. Since you are not embedding JSON into HTML, there is no need for escaped slashes and we will make it nicely indented for easier debugging.
So as I said in a comment, the problem is probably that "$row" is not initialized. It should probably be:
while($row=mysql_fetch_array($result))
Also, you used mysql_ functions which are not compatible with PDO. You should do your request using $db->query.
As you asked for suggestions, I may give you a trick that I use.
I think that it's a lot of code for just retrieving a table that is basically the content of the result of your query (in $result). And I guess you have similar code for almost every request. So what I do in general is that I build a generic function called extractResult that directly makes an array of lines from the result of a query.
Here is the function:
/**
* Extract a php array from the result of a db query.
* This result can be directly parsed in JSON for instance.
*/
function extractResult($res) {
$arr = array();
while($line = $res->fetch()) {
$count = count($line)/2;
for ($i=0; $i<$count; $i++) {
unset($line[$i]);
}
array_push($arr, $line);
}
return $arr;
}
Note: the for loop with the "unset" is made to remove the entries with digits. What's returned by a fetch is something like this:
Array("DisplayName" => "Loulou", 0 =>"Loulou", "StreamKey" => 12, 1 => 12)
So it removes the numerical duplicates.
So you could use it like this and your code becomes way lighter:
<?php
header('Content-type:application/json;charset=utf-8');
//Make connection to database
$db=new PDO('mysql:dbname=streamdb;host=localhost;','root','');
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
echo "Connected successfully";
$result=$db->query('select display_name AS DisplayName, stream_key AS StreamKey from maintable');
$response = array();
$response['streamers'] = extractResult($result);
echo json_encode($response);
?>
Note that you have to specify the columns name that you want directly in the request! :)
Don't know if it's nteresting, but I always use this trick so building JSON from DB is so much easier and lighter. :) Good luck.
Here you can check the working code
<?php
$con=mysqli_connect($servername,$username,$password,$databasename);
if (mysqli_connect_errno())
{
echo "Connection Error" . mysqli_connect_error();
}
$query = "SELECT * FROM TableName";
$result = mysqli_query($con,$query);
$querydata = array();
while($data = mysqli_fetch_array($result)) {
$querydata[] = $data;
}
echo json_encode($querydata);
mysqli_close($con);
?>
I'm trying to use PHP/ODBC to connect to an access file. The problem is that I can read from the database but I can't write to it using the below:
$conn = odbc_connect('SKW-DB','','');
if (!$conn)
{
exit ("ODBC Connection Failed ". $conn);
}
$stmt = "INSERT INTO PRODUCT (ProductCode, ProductName) VALUES ('TestCode', 'TestEntry')";
$result = odbc_exec ($conn,$stmt);
echo "Result1: ";
echo $result;
$result returns nothing. Again, I am able to read from the database, connectivity isn't an issue. I just can't write to it.
That's because you're simply ASSUMING the query can never fail. It did fail, and returned a boolean false. echo false literally prints out nothing.
Try this instead:
$result = odbc_exec($conn, $stmt);
if ($result === false ) {
die(odbc_errormsg($conn));
}
And what you get back from odbc_exec() cannot be echoed out anyways. On success, it returns a statement handle, which is NOT something you can simply print out.
Sounds like you need a little more debugging code.
First, try var_dumping the $result instead of echoing it.
var_dump($result);
There's certain PHP variable types that echo can't/won't display.
Next -- chances are your query's causing an error of some sort, so try using the odbc error reporting functions after making your query
$result = odbc_exec ($conn,$stmt);
echo "Result1: ";
var_dump( $result );
if($result)
{
var_dump( odbc_error($conn) );
var_dump( odbc_errormsg($conn) );
}
I'm trying to use Auto-complete using Oracle.
I'd done this using MySQL, but with Oracle I got blank spaces.
This my MySQL Code.
global $db;
$term = trim(strip_tags(strtoupper($_GET['term'])));//retrieve the search term that autocomplete sends
$sql = "SELECT partNo as value FROM products WHERE partno LIKE '".$term."%' ORDER BY partNo LIMIT 15";
Basic::EventLog('getPartNosFromDB-> '.$sql);
$res =& $db->query($sql);
while ($row=$res->fetchRow()){
$row['value']=htmlentities(stripslashes($row['value']));
$row_set[] = $row;//build an array
}
echo json_encode($row_set);
And this is Oracle
$term = trim(strip_tags(strtoupper($_GET['term'])));//retrieve the search term that autocomplete sends
$conn = oci_connect('XXXX', 'XXXXX', 'XXXXX');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$sql = "SELECT product_definition as value FROM t_wip_job WHERE product_definition LIKE '".$term."%' AND ROWNUM < 16";
Basic::EventLog('getPartNosFromDB-> '.$sql);
$res = oci_parse($conn, $sql);
oci_execute($res);
while ($rowcc = oci_fetch_array($res, OCI_ASSOC)){
$row_set[] = $rowcc;//build an array
}
echo json_encode($row_set);
If I execute these query the first returns -> [{"value":"A2C00000000"},{"value":"A2C00000001"}] (MySQL)
And the second returns -> [{"VALUE":"A2C87115000"},{"VALUE":"A2C87114900"}] (Oracle)
But inside textbox when it tries to auto-complete the MySql result shows "A2C87115000" and "A2C87114900"
and the Oracle result shows " " and " ".
The problem could be with the case of the hash keys, since the MySql hash keys are lowercase ("value"), while the Oracle ones are uppercase ("VALUE").
When you load the json, since javascript is case sensitive, looking for "value" it finds the content only in the first case.
Try having lowercase keys in both case. This should do the trick!
I am trying to use a function to perform an SQL query and return the result. Doing a manual SQL query with the same query as the below works and returns the correct result but doing it within PHP is not working at all (page is blank).
connection.php
<?php
require_once("settings.php");
$conn = oci_connect($db_user, $db_pass, $db_ip.'/'.$db);
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
?>
functions.php
<?php
require_once("connection.php");
function GetInvoice($n)
// returns invoice number for given order number
{
$stid = oci_parse($conn, 'SELECT InvoiceNo FROM Orders WHERE OrderNo = $n');
oci_define_by_name($stid, 'InvoiceNo', $InvoiceNo);
oci_execute($stid);
echo "$InvoiceNo";
}
GetInvoice(999645);
?>
Doing the manual SQL query shows a resulting InvoiceNo, it is just not working in PHP.
Thanks
Steve
You are trying to use a variable outside of function inside the function. That variable is not in function's scope. Due to this, $conn is undefined. Also, you have used $InvoiceNo withoud fetch result, I did some refoctoring on that place. You can use following;
function GetInvoice($n, $conn)
// returns invoice number for given order number
{
$stid = oci_parse($conn, 'SELECT InvoiceNo FROM Orders WHERE OrderNo = $n');
oci_define_by_name($stid, 'InvoiceNo', $InvoiceNo);
oci_execute($stid);
while (oci_fetch($stid)) {
echo "$InvoiceNo";
}
}
GetInvoice(999645, $conn);
The parameters you are passing in functions, seems undefined
as you have created your function needs only one parameter, then from where this will get this variable $InvoiceNo
oci_define_by_name($stid, 'InvoiceNo', $InvoiceNo);
Sample code:
$infoArray = array();
require_once("connectAndSelect.php");
// Connects to mysql and selects the appropriate database
$sql = "SOME SQL";
if($results = mysql_query($sql))
{
while($result = mysql_fetch_array($results, MYSQL_ASSOC))
{
$infoArray[] = $result;
}
}
else
{
// Handle error
}
echo("<pre>");
print_r($infoArray);
echo("</pre>");
In this sample code, I simply want to get the result of my query in $infoArray. Simple task, simple measures... not.
I would have enjoyed something like this:
$sql = "SOME SQL";
$infoArray = mysql_results($sql);
But no, as you can see, I have two extra variables and a while loop which I don't care for too much. They don't actually DO anything: I'll never use them again. Furthermore, I never know how to call them. Here I use $results and $result, which kind of represents what they are, but can also be quite confusing since they look so much alike. So here are my questions:
Is there any simpler method that I
don't know about for this kind of
task?
And if not, what names do you
give those one-use variables? Is
there any standard?
The while loop is really only necessary if you are expecting multiple rows to be returned. If you are just getting one row you can simply use mysql_fetch_array().
$query = "SOME SQL";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
For single line returns is the standard I use. Sure it is a little clunky to do this in PHP, but at least you have the process broken down into debug-able steps.
Use PDO:
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
$sql = "SELECT * FROM myTable";
$result = $dbh->query($sql)
//Do what you want with an actual dataset
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
Unless you are legacied into it by an existing codebase. DONT use the mysql extension. Use PDO or Mysqli. PDO being preferred out of the two.
Your example can be come a set of very consise statements with PDO:
// create a connection this could be done in your connection include
$db = new PDO('mysql:host=localhost;dbname=your_db_name', $user, $password);
// for the first or only result
$infoArray = $db->query('SOME SQL')->fetch(PDO::FETCH_ASSOC);
// if you have multiple results and want to get them all at once in an array
$infoArray = $db->query('SOME SQL')->fetchAll(PDO::FETCH_ASSOC);
// if you have multiple results and want to use buffering like you would with mysql_result
$stmt = $db->query('SOME SQL');
foreach($stmt as $result){
// use your result here
}
However you should only use the above when there are now variables in the query. If there are variables they need to be escaped... the easiest way to handle this is with a prepared statement:
$stmt = $db->prepare('SELECT * FROM some_table WHERE id = :id');
$stmt->execute(array(':id' => $id));
// get the first result
$infoArray = $stmt->fetch(PDO::FETCH_ASSOC);
// loop through the data as a buffered result set
while(false !== ($row = $stmt->fetch(PDO::FETCH_ASSOC))){
// do stuff with $row data
}