Mongodb connectivity error - php

<?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";

Related

how to connect to remote database in php pdo

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.

Access denied for user ''#'localhost' (using password: NO) using AWS and EC2

I am getting the following error when using SHIFTEDIT IDE to try connect to my amazon EC2 instance running LAMP server and mysql server.
The code I am writing in PHP to connect to my sql server is as followed:
<?php
function connect_to_database() {
$link = mysqli_connect("localhost", "root", "test", "Jet");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
echo "Success: A proper connection to MySQL was made! The my_db database is great." . PHP_EOL;
echo "Host information: " . mysqli_get_host_info($link) . PHP_EOL;
mysqli_close($link);
}
?>
OUTPUT: Success: A proper connection to MySQL was made! The my_db database is
great. Host information: Localhost via UNIX socket Access denied for
user ''#'localhost' (using password: NO)
I am definitely using the right password for root as I can successfully login when using Phpmyadmin, I just cannot make a connection with PHP for some reason.
Currently, I have a single Amazon ec2 instance with LAMP server and a MySQL server installed. Any help will be much appreciated.
EDIT: I am using Php 5.6.17
When you create a mysqli instance (either by new mysqli(...) or mysqli_connect(....) within a function/method, you have to take php's variable scope into account. Return the mysqli instance from the function and let the caller use and/or assign that instance.
<?php
/*
builds and throws an exception from the error/errno properties of a mysqli or mysqli_stmt instance
#param useConnectError true: use connect_error/connect_errno instead
#throws mysqli_sql_exception always does
*/
function exception_from_mysqli_instance($mysqli_or_stmt, $useConnectError=false) {
// see http://docs.php.net/instanceof
if ( !($mysqli_or_stmt instanceof mysqli) && !($mysqli_or_stmt instanceof mysqli_stmt) {
// see docs.php.net/class.mysqli-sql-exception
throw new mysqli_sql_exception('invalid argument passed');
}
else if ($useConnectError) {
// ok, we should test $mysqli_or_stmt instanceof mysqli here ....
throw new mysqli_sql_exception($mysqli_or_stmt->connect_error, $mysqli_or_stmt->connect_errno);
}
else {
throw new mysqli_sql_exception($mysqli_or_stmt->error, $mysqli_or_stmt->errno);
}
}
/* creates a new database connection and returns the mysqli instance
#throws mysqli_sql_exception in case of error
#return valid mysqli instance
*/
function connect_to_database() {
$link = new mysqli("localhost", "root", "test", "Jet");
// see http://docs.php.net/mysqli.quickstart.connections
if ( $link->connect_errno) {
// a concept you might or might not be interested in: exceptions
// in any case this is better than to just let the script die
// give the other code components a chance to handle this error
exception_from_mysqli_instance($link, true);
}
return $link;
}
try { // see http://docs.php.net/language.exceptions
// assign the return value (the mysqli instance) to a variable and then use that variable
$mysqli = connect_to_database();
// see http://docs.php.net/mysqli.quickstart.prepared-statements
$stmt = $mysqli->prepare(....)
if ( !$stmt ) {
exception_from_mysqli_instance($stmt);
}
...
}
catch(Exception $ex) {
someErrorHandler();
}
and a hunch (because of the actual error message; trying to use the default root:<nopassword> connection, that's the behaviour of the mysql_* functions, not of mysqli):
Do not mix mysqli and mysql_* functions.

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.

Mysqli php i want a custom error message when unknown server host

I am writing a script to install the database of an application in php. It working fine but when im trying to install a database that doesnt exist i want only my own error message but i keep getting the default Warning : Warning: mysqli::mysqli() [mysqli.mysqli]: (HY000/2005): Unknown MySQL server host 'kasdasd'.
So I know that the host is wrong and I want it to be so, with only my own errormessage. How do I get rid of this message?
My connectclass with parameter DBConfig $config:
$this->mysqli = new mysqli($config->m_host,
$config->m_user,
$config->m_passw,
$config->m_db);
if ($this->mysqli->connect_error) {
return false;
}
$this->mysqli->set_charset("utf8");
return true;
an easy solution would be to see if you can open the hostname using fsockopen and suppressing the errors:
$port = 80;
if($fp = #fsockopen($config->m_host,$port)){
$db = new mysqli($config->m_host,$config->m_user,$config->m_passw,$config->m_db);
}else{
echo 'hostname not recognized';
}
#fclose($fp);
Edited:
You can use
if ($mysqli->connect_error) {
/** handle your error here **/
// Throw a custom exception if you like! (see below)
// or just echo "There was an error";
}
You can further use mysqli_connect_errno() to find out wht happened and handle it accordingly.
Edit: mysqli doesn't throw erros so below is incorrect.
Wrap your code in a try-catch, then you can throw whatever kind of error you like:
try {
/** your code here **/
} catch (Exception $e) {
/** your handling here **/
// i.e.
throw new BadHostNameException($config->m_host);
// or
echo "Could not connect!":
}
Note: you should replace Exception $e with the specific kind of exception a bad host throws so catch(MysqlBadHostnameException $e) (the type of error will be in your error log from your previous attempts or you can do get_class($e) in my example above.
// Isusing a custom exception: Add this outside of your class..
class BadHostNameException extends Exception {}

Categories