Cannot connect my RDS Oracle instance to a PHP server - php

I have an Oracle database set up on Amazon RDS and am trying to connect to it in PHP.
I am fairly sure my connection string is correct because I connected using sqlplus and am able to retrieve data. The server is an Amazon Linux server, however I have also tried to connect using a different server and get the error:
Is there any more set up that I need to do in either the server or the database server, I have just started using AWS and am not sure if anything else needs to be done.
ORA-12154: TNS:could not resolve the connect identifier specified... Line 19.
Here is my test code:
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php
echo "OCI Test<br>";
$tns = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=xyz.abc.us-west-2.rds.amazonaws.com)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)));";
echo "<pre>$tns</pre>\n";
$username = "xxx";
$password = "yyy";
$db = #oci_connect($username, $password, $tns);
if (!$conn)
{
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
$sql = "select * from city";
$stmt = OCIParse($db, $sql);
if(OCIExecute($stmt))
{
while(OCIFetchInto($stmt, $row, OCI_RETURN_NULLS))
{
echo $row[0]. "-" . $row[1]."<br>";
}
}
OCIFreeStatement($stmt);
?>
</body>
</html>
Edit: Also the Amazon Linux server just shows nothing, while another server that I have access to gives errors, is there a configuration change for this?

The $tns variable looks wrong.
Try
$tns = "(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=xyz.abc.us-west-2.rds.amazonaws.com)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=orcl)));";

Related

How to connect to Oracle Database with php?

I am currently working on a website that connects to an Oracle Database. I have two php files, one for connection with the database and the other is the html structure itself.
Connect.php:
<?php
$servername = "//////";
$username = "/////";
$password = "/////";
$conn = oci_connect($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected!";
?>
I have been having a very hard time connecting to the database. I followed the Oracle tutorial and edited the oci8.connection_class = MYPHPAPP in php.ini, but everytime I run the Connect.php, I get the HTTP Error 500. Did I miss anything? What should I do?
Edit 1: I used display_errors and the error I am getting is Call to undefined function oci_connect()
Edit 2: I tried everything at this point to make the oci_connect work. I downloaded the oracle client and made it an environmental variable but oci_connect is still not working. I would really appreciate if any mac users could help me with this.
Download the appropriate oracle client to your machine, extract it and copy and paste in your system drive.
Add the path of your oracle client to environment variables.
Then you need to enable php_oci8_12c extension using php.ini or GUI if available.
Open php file and write the following code:
function connect(){
$dburl = "(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = your_host)(PORT = 1521))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = your_db_sid)
)
)";
//db charset is optional
$db_charset = 'WE8MSWIN1252'; //your db charset goes here
try {
return oci_connect("username", "password",$dburl,$db_charset);
}
catch (Exception $e) {
die($e);
}
}
This code is work fine on my windows 10 machine, php 7.1.9 and oracle 12c.
Forth link in google after searching for your exact questions brought up the following link: http://me2learn.wordpress.com/2008/10/18/connect-php-with-oracle-database/
<?php
$db = "(DESCRIPTION=(ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.1.34)(PORT = 1521)))(CONNECT_DATA=(SID=orcl)))" ;
if($c = OCILogon("system", "your database password", $db))
{
echo "Successfully connected to Oracle.\n";
OCILogoff($c);
}
else
{
$err = OCIError();
echo "Connection failed." . $err[text];
}
?>

PHP - oci_connect not found

I researched and found out oci_connect() is the way to go. I found out that i could either use the Connect Name from the tnsnames.ora file or use an easy connect syntax. Since my database isn't locally stored and I had no idea where the said, tnsnames.ora file was located in apex.oracle.com, I went with easy connect strings.Here's what I've done so far.
$username = "myemail";
$host = "apex.oracle.com";
$dbname = "name";
$password = "password";
// url = username#host/db_name
$dburl = $username . "#".$host."/".$dbname;
$conn = oci_connect ($username, $password, $dburl);
if(!$conn) echo "Connection failed";
I get a
Call to undefined function oci_connect()
So what would be the way to go?
UPDATE 1:
Here's the list of things I did:
Installed Oracle DB
Unzipped Oracle Instance client
Set the environment variables
Uncommented the extension=php_oci8_12c.dll in php.ini
Copied all the *.dll files from the instance client folder to xampp/php and xampp/apache/bin
also made sure the php/ext folder had the required dlls.
That was last night. I have restarted my PC multiple times, APACHE with it but I'm still getting this error:
Call to undefined function oci_connect()
At this point I'm frustrated and don't know where to go from here. PHP just doesn't seem to link up to oci8. I can view the databases I made from Database Configuration Assistant in cmd from 'sqlplus' command and a few select statements. So everything seems to be setup right, its just the php that's having problems trying to use oci_connect().
My database.php, now is setup as:
public function __construct()
{
error_reporting(E_ALL);
if (function_exists("oci_connect")) {
echo "oci_connect found\n";
} else {
echo "oci_connect not found\n";
exit;
}
$host = 'localhost';
$port = '1521';
// Oracle service name (instance)
$db_name = 'haatbazaar';
$db_username = "SYSTEM";
$db_password = "root";
$tns = "(DESCRIPTION =
(CONNECT_TIMEOUT=3)(RETRY_COUNT=0)
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = $host)(PORT = $port))
)
(CONNECT_DATA =
(SERVICE_NAME = $db_name)
)
)";
$tns = "$host:$port/$db_name";
try {
$conn = oci_connect($db_username, $db_password, $tns);
if (!$conn) {
$e = oci_error();
throw new Exception($e['message']);
}
echo "Connection OK\n";
$stid = oci_parse($conn, 'SELECT * FROM ALL_TABLES');
if (!$stid) {
$e = oci_error($conn);
throw new Exception($e['message']);
}
// Perform the logic of the query
$r = oci_execute($stid);
if (!$r) {
$e = oci_error($stid);
throw new Exception($e['message']);
}
// Fetch the results of the query
while ($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) {
$row = array_change_key_case($row, CASE_LOWER);
print_r($row);
break;
}
// Close statement
oci_free_statement($stid);
// Disconnect
oci_close($conn);
}
catch (Exception $e) {
print_r($e);
}
}
And it outputs:
oci_connect not found
OCI8 is listed in my phpInfo().
Okay I found out the culprit behind this whole ordeal. I had set the PATH Environment Variables but apparently forgot to add a new system environment variable named TNS_ADMIN and set the directory to PATH/TO/INSTANCE/CLIENT.
Here's the list of System Environment variable you need to add:
Edit PATH system variable and add the $ORACLE_HOME/bin dir
Edit PATH system variable and add the Instance Client dir
Add new system variable, name it TNS_ADMIN and add the Instance Client dir
I hope this helps those who come looking.
First, this has been asked before, but Oracle doesn't allow remote database connections to their free apex.oracle.com example service. Sorry. You can only interact with it through the web interface.
Second, if you do find a remote Oracle db to connect to, you'll need to install the Oracle Instant Client for your OS, and configure the PHP OCI8 extension.

Connecting to local Database from remote web server

I am trying to connect to my local Database from the webserver but i get
Fatal error: Call to undefined function odbc_connect()
in -/-/-/7001238/web/s/sage2.php on line 15"
Any help on how to fix issue.
Here is the code i used to connect.
$odbc['dsn'] = "Sage50";
$odbc['user'] = "Peach";
$odbc['pass'] = "XXXX";
$mysql['host'] = "localhost";
$mysql['user'] = "root";
$mysql['pass'] = "";
$mysql['dbname'] = "sagetest";
$mysql['idfield'] = "id";
$debug=true;
// Step 1: Connect to the source ODBC and target mysql database
if ($debug) echo "Connect to " . $odbc['dsn'] . ' as ' . $odbc['user'] . "\n";
$conn = odbc_connect($odbc['dsn'], $odbc['user'], $odbc['pass']);
if (!$conn) {
die("Error connecting to the ODBC database: " . odbc_errormsg());
}
$myconn = mysql_connect($mysql['host'], $mysql['user'], $mysql['pass']);
if (!$myconn)
die("Error connecting to the MySQL database: " . $mysql_error());
if (!mysql_select_db($mysql['dbname'], $myconn)) die("Error selecting the database: " . mysql_error());
// Step 1.5: loop through each table with steps 2-7
$allTables = odbc_tables($conn);
$tablesArray = array();
while (odbc_fetch_row($allTables)) {
if (odbc_result($allTables, "TABLE_TYPE") == "TABLE") {
$tablesArray[] = odbc_result($allTables, "TABLE_NAME");
}
}
Thank you for your time!
First: This error happens because you don't have the ODBC PHP extension installed.
Check http://php.net/manual/en/odbc.installation.php too.
In debian distros you can solve this with a apt-get install php5-odbc, but you can check this also with your hosting provider.
When you see a Call to undefined function you always must check the php.net to be sure about the name of function, or the extension is not loaded.
PS 1: I think you're trying to compare/transfer data between two databases, right?
PS 2: Make sure your server can reach the ODBC address. The webserver is not your dev machine, so localhost is not the real localhost ;)

Why isn't my mysql query from python shell going through to the web hosting database

ok so I have the following code that I am running in the python shell:
import MySQLdb
db = MySQLdb.connect(host = "xxxx",user="xxxx"password="xxxx",db="xxxx")
cur = db.cursor()
cur.execute(CREATE TABLE qqqq (asdf VARCHAR(20),fdsa VARCHAR(20))
Fairly sure the connection part is working, I'll get an error if I enter in the wrong value, or if I deny access to the database for my computer's IP address.
on the webhosting server, I have the following basic index.php file, which I have tested on a server on my computer, and I know works. when I go to the website domain, I get the following error: "Database query failed."
Any ideas why the MySQL query isn't working? My webhosting is Cpanel with godaddy.com, should I look for something else?
<?php
$dbhost = "xxxx";
$dbuser = "xxxx";
$dbpass = "xxxx";
$dbname = "xxxx";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname); /*1*/
if(mysqli_connect_errno()) {
die("Database connection failed: " .
mysqli_connect_error() .
" (" . mysqli_connect_errno() . ")"
);
}
?>
<?php
$query ="SELECT * FROM qqqq"; /*2*/
$result = mysqli_query($connection, $query);
if (!$result) {
die("Database query failed.");
}
?>
<!DOCTYPE html PUBLIC >
<html lang="en">
<head>
<title></title>
</head>
<body>
<ul>
<?php /*3*/
while($subject = mysqli_fetch_assoc($result)){
?><li><?php echo $subject['asdf'];?></li>
<?php
}
?>
</ul>
<?php
mysqli_free_result($result); /*4*/
?>
</body>
</html>
<?php
mysqli_close($connection); /*5*/
?>
You should call db.commit() to have it complete. By default, autocommit is turned off.
You also have an error in your code. The SQL should be a string.
Shouldn't the cursor execute be calling a string? You don't have quotes around your sql statement.
This line without quotas is incorrect:
cur.execute(CREATE TABLE qqqq (asdf VARCHAR(20),fdsa VARCHAR(20))
It should be
cur.execute("CREATE TABLE qqqq (asdf VARCHAR(20),fdsa VARCHAR(20))")
So test in your database whether you really have table qqqq.
You could install SQL Buddy or phpMyAdmin.

PHP mysql connect to any remove server the post variables

if (!empty($_POST)) {
$host = $_POST['host'];
$user = $_POST['user'];
$pass = $_POST['pass'];
$db = $_POST['db'];
echo '<pre>';
print_r($_POST);
$con = #mysqli_connect($host . ":3360", $user, $pass, $db);
// $con=#mysqli_connect('192.168.100.42','root','vertrigo','skates');
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else {
echo 'connected';
}
#mysqli_close($con);
}
I'm using this script to access remote db server in local(basically i want to access local db server through live webiste), howewer, I'm getting an error:
Failed to connect to MySQL: Unknown MySQL server host
'192.168.100.42:3360' (11004)
Please help to get out from this.
192.168.100.42 looks like a local IP. You'd need to try to connect to your static public IP and then forward port 3306 in your router to the 192.168.100.42 machine.
That's not your only problem;
Just because $_POST is not empty, don't assume it has those array keys set and not empty. Syntax like
if(isset($_POST['user'] && !empty($_POST['user'])))
Is much better.
Also, never use $_POST on any database interaction without sanitisation, and never connect to a database with the root user.
I don't know your exact application, but it's impossibly insecure.

Categories