trouble connecting to dashDB on BlueMix - php

Here is my code of my .php app connecting to dash-DB instance
//parse VCAP_SERVICES Environment variable
$vcap_services = $_ENV["VCAP_SERVICES"];
$services_json = json_decode($vcap_services,true);
$sqldb = $services_json["dashDB"];
if (empty($sqldb)) {
echo "No sqldb service instance is bound. Please bind a sqldb service instance";
return;
}
//Get Credentials object (db,host,port,username,password)
$sqldb_config = $services_json["dashDB"][0]["credentials"];
$conn_string = "DRIVER={IBM DB2 ODBC DRIVER};DATABASE=".
$sqldb_config["db"].
";HOSTNAME=".
$sqldb_config["host"].
";PORT=".
$sqldb_config["port"].
";PROTOCOL=TCPIP;UID=".
$sqldb_config["username"].
";PWD=".
$sqldb_config["password"].
";";
$conn = db2_connect($conn_string, '', ''); //db connection
$sql = "SELECT * FROM BX1_USERS WHERE Username ='$username'";
$foundElements = 0;
if ($conn) {
$stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
//lLINE 44 that the output.txt fiel referres to starts here
while ($row = db2_fetch_assoc($stmt)) {
$dbusername = $row['Username'];
$dbpassword = $row['Password'];
$dbfirstname = $row['FirstName'];
$dblastname = $row['LastName'];
$foundElements = 1;
}
}
print $foundElements;
echo "<br>";
print $sql;
echo "<br>";
if ($foundElements == 1){
/// rest of my code here
I tested the printed $sql in the database console and it works just fine.. .. but still $foundElements = 0 ...
I get this error in the recent logs file:
"
PHP Warning: db2_fetch_assoc() expects parameter 1 to be resource, boolean given in /home/vcap/app/www/login.php on line 44,
"
I even added this to the code:
print $sqldb_config["db"];
echo "<br>";
print $sqldb_config["host"];
echo "<br>";
print $sqldb_config["port"];
echo "<br>";
print $sqldb_config["username"];
echo "<br>";
print $sqldb_config["password"];
and the page show the same exact values as in my VCAP.

after a few hours of banging my head against the wall I found an answer.
the code I was using was from a connection and queries I used on the IBM SQLDB...
and fro whatever reason I had to change it a little bit to work with IBM dashDB.
I had to change:
$stmt = db2_exec($conn, $sql, array('cursor' => DB2_SCROLLABLE));
to
$stmt = db2_exec($conn, $sql);

Related

Pulling Queries from Database Clears Results on Error vs. Stopping

We have a script that pulls queries from a database every couple of minutes. Those results are then shown in a table on a webpage. It works great, until that database responds with an error code (for whatever reason that may be) and instead of stopping it clears all the data. We don't want this data being cleared. It just needs to stop trying to pull if it gets an error message and wait until the next pull. Any idea how we can prevent this clearing all content?
Connection to Database:
<?php
$constr = 'mysql:host=mysql.test.com;dbname=test_custom;charset=utf8';
$dbUser = 'test';
$dbPW = 'test';
try {
$db = new PDO($constr, $dbUser, $dbPW);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
//$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$rez = "Connected";
//echo $rez;
} catch(PDOException $ex) {
$rez = "An Error occured connecting to the DB: ".$ex->getMessage().".";
//echo $rez;
}
?>
Code to display the results on the page:
<?php
include 'db.connect.php';
$sql = "SELECT ts_id, position, name FROM ts_applications WHERE enable = 1 ORDER BY Client";
$stmt = $db->prepare($sql);
$stmt->execute();
$num_rows = $stmt->rowCount();
//echo $num_rows;
if($num_rows > 0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$id = $row['ts_id'];
$name = $row['name'];
echo "<tr>";
echo "<th><a href='position.php?id=" . $id . "'>" . $name . "</a></th>";
echo "</tr>";
}
} else {
echo "<tr>";
echo "<th>Please <a href='contact.php'>Contact</a> Doh! Something went wrong</th>";
echo "</tr>";
}
include 'db.close.php';
?>
Thank you in advance!
You might try changing your query to:
$sql = "IF EXISTS (SELECT TOP 1 fm_id FROM mb_searches WHERE fm_id IS NOT NULL) SELECT fm_id, position, client, city, state FROM mb_searches WHERE enable = 1 ORDER BY Client";
I don't know if that will filter out your error message

I am having an issue with PHP. I can query from MSSMS directly to the DB but my web pages all will not connect to the Server

I am having an issue with PHP. I can query from MSSMS directly to the DB but my web pages all will not connect to the Server..
SQL Server 2016
PHP version 5.2.4
Sample:
$DatabaseServer = 'server';
$DatabaseUser = 'reader';
$DatabasePassword = '';
$DatabaseName = 'FSDBMV';
$SQL_db = #mssql_connect($DatabaseServer,$DatabaseUser,$DatabasePassword) or die("Unable to connect to Database server");
mssql_select_db("$DatabaseName");
$Sql = " SELECT [CustomerID]
,[CustomerName]
,[CSR]
,[CommissionCode]
FROM [FSDBMV].[dbo].[FS_Customer] as C
Explanations:
First, remove error control operator # and check for errors with mssql_get_last_message(). Then, execute your statement with mssql_query().
Example:
<?php
# Settings
$DatabaseServer = 'server';
$DatabaseUser = 'reader';
$DatabasePassword = '';
$DatabaseName = 'FSDBMV';
# Connection
$SQL_db = mssql_connect($DatabaseServer, $DatabaseUser, $DatabasePassword);
if ($SQL_db === false) {
echo "Error (mssql_connect): ".mssql_get_last_message();
exit;
}
if (!mssql_select_db($DatabaseName, $SQL_db)) {
echo "Error (mssql_select_db): ".mssql_get_last_message();
exit;
};
# Query
$Sql = "
SELECT
[CustomerID]
,[CustomerName]
,[CSR]
,[CommissionCode]
FROM [FSDBMV].[dbo].[FS_Customer] as C
";
$stmt = mssql_query($Sql, $SQL_db);
if (!$stmt) {
echo "Error (mssql_query): ".mssql_get_last_message();
exit;
}
# Results
while ($row = mssql_fetch_assoc($stmt)) {
echo print_r($row, true)."</br>";
}
# End
mssql_free_result($stmt);
mssql_close($SQL_db);
?>
Notes:
MSSQL feature was removed in PHP 7.0. Consider another way to connect to MS SQL Server.

Oracle + PHP : Display results in HTML Table

I'm having a little trouble tinkering with PHP and Oracle using OCI8 to connect. I've confirmed that i'm able to connect, but keep getting the below error:
PHP Fatal error: Call to a member function query() on resource ... on line 17.
Here's the code I have currently
<?php
$DB = '//DBGOESHERE:PORT/SIDHERE';
$DB_USER = '****';
$DB_PASS = '****';
$conn = oci_connect($DB_USER, $DB_PASS, $DB);
//check for errors
if (!$conn)
{
$e = oci_error();
print htmlentities($e['message']);
exit;
}
$sql = "select display_name, last_export_file, last_export_date from schema.ms_export where last_export_date > sysdate -1 order by last_export_date desc";
$stid = oci_parse($conn, $sql);
oci_execute($stid);
while (oci_fetch($stid)) {
echo oci_result($stid, 'display_name') . " | ";
echo oci_result($stid, 'last_export_file') . " | ";
echo oci_result($stid, 'last_export_date') . "<br>\n";
}
oci_free_statement($stid);
oci_close($conn);
?>
Any help would be greatly appreciated! Technically I'm trying to get it to output into a pretty HTML table, but starting with cheap and dirty line breaks.
Thank you!
Ends up the above was correct and I hadn't synced the most recent version of the php file. Sorry for the trouble!

Using PHP to query a MDB file, and return JSON

I have a Microsoft Access Database, and I am trying to query the table using PHP, and output valid JSON. I have an equivalent code for a MSSQL database, am I am trying to make my code do the same thing, but just for the Access database.
Here is the MSSQL code
$myServer = "server";
$myDB = "db";
$conn = sqlsrv_connect ($myServer, array('Database'=>$myDB));
$sql = "SELECT *
FROM db.dbo.table";
$data = sqlsrv_query ($conn, $sql);
$result = array();
do {
while ($row = sqlsrv_fetch_array ($data, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($data));
$json = json_encode ($result);
sqlsrv_free_stmt ($data);
sqlsrv_close ($conn);
Here is what I tried for the MDB file
$dbName = "/filename.mdb";
if (!file_exists($dbName)) {
die("Could not find database file.");
}
$db = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", $user, $password);
$sql = "SELECT *
FROM cemetery";
$data = $db->query($sql); // I'm getting an error here
$result = array();
// Not sure what do do for this part...
do {
while ($row = fetch($data, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($data));
$json = json_encode ($result);
I kind of followed this to try to connect to the database: http://phpmaster.com/using-an-access-database-with-php/
Currently this is giving me a 500 Internal Server Error. I'm expecting a string such as this to be saved in the variable $json
[
{
"col1":"col value",
"col2":"col value",
"col3":"col value",
},
{
"col1":"col value",
"col2":"col value",
"col3":"col value",
},
{
etc...
}
]
Can someone help me port the MSSQL code I have above so I can use it with an MDB database? Thanks for the help!
EDIT: I'm commenting out the lines one by one, and it throws me the 500 error at the line $data = $db->query($sql);. I looked in the error log, and I'm getting the error Call to a member function query() on a non-object. I already have the line extension=php_pdo_odbc.dll uncommented in my php.ini file. Anyone know what the problem could be?
You only need 1 loop,
fetchAll is your iterable friend:
while ($row = $data->fetchAll(SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
odbc_connect doesn't return an object, it returns a resource. see (http://php.net/manual/en/function.odbc-connect.php) so you would need to do something like this.
$db = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", $user, $password);
$oexec = obdc_exec($db,$sql);
$result[] = odbc_fetch_array($oexec);
and then you can iterate over results..
see also:
http://www.php.net/manual/en/function.odbc-fetch-array.php
http://www.php.net/manual/en/function.odbc-exec.php
I finally figured it out.
<?php
// Location of database. For some reason I could only get it to work in
// the same location as the site. It's probably an easy fix though
$dbName = "dbName.mdb";
$tName = "table";
// Throws an error if the database cannot be found
if (!file_exists($dbName)) {
die("Could not find database file.");
}
// Connects to the database
// Assumes there is no username or password
$conn = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$dbName", '', '');
// This is the query
// You have to have each column you select in the format tableName.[ColumnName]
$sql = "SELECT $tName.[ColumnOne], $tName.[ColumnTwo], etc...
FROM $dbName.$tName";
// Runs the query above in the table
$rs = odbc_exec($conn, $sql);
// This message is displayed if the query has an error in it
if (!$rs) {
exit("There is an error in the SQL!");
}
$data = array();
$i = 0;
// Grabs all the rows, saves it in $data
while( $row = odbc_fetch_array($rs) ) {
$data[$i] = $row;
$i++;
}
odbc_close($conn); // Closes the connection
$json = json_encode($data); // Generates the JSON, saves it in a variable
?>
I use this code to get results from an ODBC query into a JSON array:
$response = null;
$conn = null;
try {
$odbc_name = 'myODBC'; //<-ODBC connectyion name as is in the Windows "Data Sources (ODBC) administrator"
$sql_query = "SELECT * FROM table;";
$conn = odbc_connect($odbc_name, 'user', 'pass');
$result = odbc_exec($conn, $sql_query);
//this will show all results:
//echo odbc_result_all($result);
//this will fetch row by row and allows to change column name, format, etc:
while( $row = odbc_fetch_array($result) ) {
$json['cod_sistema'] = $row['cod_sistema'];
$json['sistema'] = $row['sistema'];
$json['cod_subsistema'] = $row['cod_subsistema'];
$json['sub_sistema'] = $row['sub_sistema'];
$json['cod_funcion'] = $row['cod_funcion'];
$json['funcion'] = $row['funcion'];
$json['func_desc_abrev'] = $row['desc_abreviada'];
$json['cod_tipo_funcion'] = $row['cod_tipo_funcion'];
$response[] = array('funcionalidad' => $json);
}
odbc_free_result($result); //<- Release used resources
} catch (Exception $e) {
$response = array('resultado' => 'err', 'detalle' => $e->getMessage());
echo 'ERROR: ', $e->getMessage(), "\n";
}
odbc_close($conn);
return $response;
And finnally encoding the response in JSON format:
echo json_encode($response);

oci_parse error message

I get this error message, what does it mean and how to fix it?
Warning: oci_parse() expects parameter 1 to be resource, null given in /user_auth_fns.php on line 3
$conn = db_connect();
$result = oci_parse($conn, "select * from user where username='$username' and passwd = sha1('$password')");
if (!$result){
$err = oci_error();
echo "Could not log you in.";
exit;
}
$r = oci_execute($result);
if (!$r) {
$error = oci_error($conn);
echo "Could not log you in." . $error['message'];
exit;
}
function db_connect()
{
$db = "dbms";
if ($c=oci_connect("username", "password", $db)){
echo "Successfully connected to Oracle.\n";
OCILogoff($c);
} else {
$err = OCIError();
echo "Oracle Connect Error " . $err[text];
}
}
Edit 2 fixed the problem, another error message, what other compression function(other than SHA1) should use for oracle?
Warning: oci_execute() [function.oci-execute]: ORA-00904: "SHA1": invalid identifier in /user_auth_fns.php on line 10
I don't know what db_connect() is returning. Maybe it is just creating a connection by its own. Try this:
$conn = oci_connect("userName","password","hostName");
fill up the useName & password & hostName here. if you are having problem with hostName then try to put the whole connection string there. example:
$conn = oci_connect('userName', 'password', '(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = )(PORT = )) (CONNECT_DATA = (SERVICE_NAME = ) (SID = )))');
then you can create a query like
$query="....";
then you can parse like this:
$result = oci_parse($conn, $query);
if you succeed in querying then $result holds Boolean value 'true'.
Your $conn variable is null. How do you instantiate that?
Edit
You instantiate $conn from db_connect(), which is not part of the standard PHP library so I can not tell you what's wrong with it other than it's returning null.
Edit 2
You're db_connect() doesn't return anything. Additionally, you close the connection immediately after opening it. Try this:
function db_connect()
{
$db = "dbms";
if ($c=oci_connect("username", "password", $db)){
echo "Successfully connected to Oracle.\n";
//OCILogoff($c); // You probably don't want to close the connection here
return $c;
} else {
$err = OCIError();
echo "Oracle Connect Error " . $err[text];
}
}
It means that $conn has no value, it is null. What did you want to have in $conn? Go back and check that.

Categories