how to connect to remote database in php pdo - php

This is view of my phpmyadmin web server
I need to connect to my university webserver on PHPmyadmin which is "phpmyadmin.newnumyspace.co.uk"
what changes are required to achieve this. I mean i know localhost would be changed and port and something needs to be put here but help me out as i don't understand the syntax
<?php
$db_host="localhost";
$db_user="root";
$db_password="";
$db_name="nbl";
try{
$db=new PDO("mysql:host={$db_host};dbname={$db_name}",$db_user,$db_password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOEXCEPTION $e)
{
$e->getMessage();
}
?>

Your sql DB is local to the web host as they are both run on a linux XAMPP server. Obviously include the correct username and password.
function getConnection() {
try {
/* connects to the SQL DB */
$connection = new
PDO("mysql:host=localhost;dbname=unn_w19038752",
"unn_w19038752", "Password");
$connection->setAttribute(PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION);
return $connection;
} catch (Exception $e) {
/* displays an error if unable to connect */
throw new Exception("Connection error ". $e->getMessage(), 0, $e);
}
}
Then you can just call this function everytime you need to make a connection
($dbConn = getConnection();)
Although for a clearer answer you're better speaking to your KF4009 Module tutor for assistance (That's what you're paying Uni fees for :-) )
Regards, former NU Student :-)
P.S. nbl is a table not a db, and you don't have root access(username), check your email from newnumyspace for your correct server login details.

Related

Mongodb connectivity error

<?php
/**
* Connects to MongoDB server.
* Stops code execution on`enter code here` connection error.
*
* You do not need to use this file, just any place to globally assign a MongoDB instance to $db.
*
* Define constants in your config or here
*/
define('MDB_USERNAME', 'root');
define('MDB_PASSWORD', 'asd');
define('MDB_HOST', 'localhost:80');
define('MDB_NAME', 'abc');
if (!class_exists('Mongo')) {
die("Mongo class not existing. Did you install the PHP MongoDB extension?");
}
try {
$conn = new MongoClient("mongodb://".MDB_USERNAME.":".MDB_PASSWORD."#".MDB_HOST."/".MDB_NAME);
$conn->authenticate('root','gynadfehurbo');
$db = $conn->selectDB(MDB_NAME);
} catch (MongoConnectionException $e) {
die($e->getMessage()); // In production you might want to turn this off.
}
Mongodb connectivity problem.
while am trying to connect mongodb with php got authentication problem ..By giving port the above error is replaced as connection refused .then i changed the port that error has been replaced as
Failed to connect to: localhost:80: Read timed out after reading 0 bytes, waited for 60.000000 seconds
$server = "mongodb://localhost:27017/dbname"; // Connecting to server
$c = new MongoClient($server );
if($c->connected)
echo "Connected successfully";
else
echo "Connection failed";

How to connect with SLIM REST api with MS SQL server?

I am trying to get results from an API call using Slim connecting with MSSQLSERVER2012
the example used to work with MYSQL getconnection function (see below) but when I am trying to
connect with MsSQL server 2012 I am getting an error like "api call error "invalid data source name"
http://localhost/msapi/api.php/clients
1'api call error "invalid data source name"
require '/Slim/Slim.php';
$app = new Slim();
$app->get('/clients', 'getClients');
$app->run();
function getClients() {
$sql = "select * FROM clients";
try {
$db = getConnection();
$stmt = $db->query($sql);
$clients = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo '{"client": ' . json_encode($clients) . '}';
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
function getConnection_MYSQL() {
$dbhost="SERVER";
$dbuser="USER";
$dbpass="PASSWORD";
$dbname="DB";
$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
function getConnection() {
$dbhost="SERVER";
$dbuser="USER";
$dbpass="PASSWORD";
$dbname="DB";
$dbh = new PDO ("ADODB.Connection");
$connStr = "PROVIDER=SQLOLEDB;SERVER=".$dbhost.";UID=".$dbuser.";PWD=".$dbpass.";DATABASE=".$dbname;
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->open($connStr); //Open the connection to the database
return $dbh;
}
the function getConnection_MYSQL() is an example that works.
But the getConnection() tryis to connect with MS SQL server ?
Do you see why I am getting an "invalid data source name" with the function getConnection()?
Since you didn't post an alternative DSN-string, I'm assuming you are using the one from your example and just replace host, username and password. This won't work.
When you are running your Slim-application on a windows host you can (and should) use Microsoft's SQL Server Driver for PHP (sqlsrv).
There are 2 versions sqlsrv.dll and pdo_sqlsrv.dll. When you want to reuse most of your code you should use the latter. This way you probably only have to modify your DSN (see php docs):
new PDO("sqlsrv:Server=localhost;Database=testdb", "UserName", "Password");
If you are using the first you have to update the way you connect to the db and create the query. You can read the Beginner's Guide to see a few examples that should make it easy.
If you are running not running your application on a Windows-machine you will probably have to set up ODBC and FreeTDS and then use PDO with an ODBC-DSN. From my experience this will be quite a lot of work, but there are a few good tutorials out there. Just google for "freetds sql server".

Connecting to Oracle database from PHP

I have an Oracle database that I am trying to connect to.
For some reason when I try the following code:
<?php
include "header.php";
// simply attempt to connect to the database
/* If you are connecting to the Oracle database, the credentials are as follows:
* Username: ********
* Password: ********
* Hostname: **********
* Port: 1521
* Service name: ***********
*/
$oracleConnect = true;
if ($oracleConnect)
{
echo 'Attempting connection...<br>';
$connection = null;
try
{
$connection = oci_connect('user',
'pass',
'user#//hostname:1521/dbname');
}
catch (Exception $e)
{
echo $e->getMessage();
}
if (!$connection)
{
echo '<p>Something is wrong.</p>';
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
// if the connection has been established
else
{
// tell the user and close it (this is a test)
echo 'Connection established!!';
oci_close($connection);
}
}
else
{
$connection = new mysqli('host', 'user', 'password', 'database');
echo ($connection) ? 'Database connection successful!' : 'Could not connect.';
}
include "footer.php";
?>
When I try the above code, I get the "Attempting connection..." to print, but nothing else. It is supposed to print something else regardless. What could possibly be going wrong?
I think the problem is the user# part of your connection string. I dont think thats necessary as oci_connect has a user name parameter. I could be wrong, ive never used oracle from php before, but the docs on oci connections would also seem to indicate that:
To use the Easy Connect naming method, PHP must be linked with Oracle 10g or greater Client libraries. The Easy Connect string for Oracle 10g is of the form: [//]host_name[:port][/service_name]. From Oracle 11g, the syntax is: [//]host_name[:port][/service_name][:server_type][/instance_name]. Service names can be found by running the Oracle utility lsnrctl status on the database server machine.
Also oci_connect does not throw an exception as far as i can tell so your try/catch is useless unless you planned on throwing your own when it returns false.

Error connecting to local db server

I have the following code:
try {
$db_conn = new PDO('mysql:host='.$host.';dbname=stats;port='.$port, $un, $pw);
} catch (PDOException $e) {
WriteLog("Could not connect to database!\nError: ".$e->getMessage());
exit;
}
try {
$db_conn2 = new PDO('mysql:host=localhost;dbname=log', $un2, $pw2);
} catch (PDOException $e) {
WriteLog("Could not connect to database[2]!\nError: ".$e->getMessage());
exit;
}
It connects without errors to the first server (not local), but then it fails to connect to the local server. I get this error message:
Error: SQLSTATE[HY000] [2002] No such file or directory (||)
I'm running PHP v5.4.27
Solved it. Changing from localhost to 127.0.0.1 seems to fix it. I'm not sure why

Error with transfering MySQL database (connected via PDO) from localhost to hosted server

Okay, so this is my code:
try {
$pdo = new PDO ('mysql:host=127.0.0.1;dbname=db_name','user','password');
} catch (PDOException $e) {
exit ('Database error.');
}
I tried so many different combinations with host name, username and password, and every time I get 'Database error'.
My question is:
What should I do to succesfully transfer MySQL database from localhost to my hosted server using this part of code (which is my connection.php file)?
Thank you, in advance.
Get rid of this try catch stuff. Leave it as
$pdo = new PDO ('mysql:host=127.0.0.1;dbname=db_name','user','password');
And see what it says (on-screen or logs)
Use this try and catch block for error trace
try {
$this->conn = new PDO('mysql:host=127.0.0.1;dbname=db_name','user','password');
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Error: ' . $e->getMessage();
}

Categories