I am using laravel 5.7 and mongo db(v1.5.3 stable).
I am trying to test connection from laravel to db but everytime I am getting successfull connection even I am providing wrong credentials.
I have tried by the following ways:
Jessengers
$arrMongo = [];
if(true == DB::connection('mongodb')) {
$arrMongo = array(
'status'=>true,
'message' => 'Mongo connection OK'
);
}else{
$arrMongo = array(
'status'=>false,
'message' => 'Mongo connection failed'
);
}
Normal PHP way
$server = "mongodb://google.com:27017/university";
$c = new \MongoDB\Client( $server );
if($c->connected)
echo "Connected successfully";
else
echo "Connection failed";
I am never getting as connection failed while testing with wrong credentials.
Please help me to resolve this problem.
Laravel only connects to the database when it needs something from the database.
You may opt for getting the list of databases inside try/catch block as follow:
try {
DB::connection()->getMongoClient()->listDatabases();
} catch (\Exception $e) {
echo $e->getMessage();
}
Related
I'd like my PHP script (using PDO) to detect whether or not a target database is in the middle of a restore process other than waiting several minutes for a response from a failed connection.
My database connection code eventually returns the message below if a database is being restored, but it happens because the connection fails and it takes several minutes to respond when this happens. Searching on StackOverflow and Google doesn't seem to find anything that fits my need, nor does searching through PHP's documentation.
function getParameterizedPDOConnection($host = false, $overrideOptions = []) {
include(INCLUDE_DIR . "/itrain.config.php");
$host = strtolower($_SERVER["HTTP_HOST"]);
if (count($overrideOptions) > 0) {
$configOptions["host"][$host] = $overrideOptions;
}
$sthUserName = $configOptions["userName"];
$pwd = $configOptions["pwd"];
$addr = $configOptions["host"][$host]["addr"];
$db = $configOptions["host"][$host]["db"];
try {
$pdo = new PDO("sqlsrv:Server=$addr;Database=$db;ConnectionPooling=0", $sthUserName, $pwd, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_SILENT));
return($pdo);
} catch (PDOException $e) {
return "Database connection failure: " . $e->getMessage();
}
}
Returns: "42000",927,"[Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Database 'Workforce' cannot be opened. It is in the middle of a restore.
In my webapp, I am going to accept all the database connection parameters (such as username, server, database etc.) as input from the users and before saving those information, I want to quickly test if a connection can be obtained successfully based on those connection parameters.
Here is my code:
$config = new \Doctrine\DBAL\Configuration();
$url = "mysql://user:pass#server/instance"; // INFORMATION FROM USER
$connectionParams = array('url' => $url);
try {
$conn = \Doctrine\DBAL\DriverManager::getConnection ($connectionParams, $config);
if ($conn->connect()) { // GETTING ERROR HERE
echo "Connection Successful";
}
}
catch (Exception $e)
{
echo "Connection unsuccessful";
}
But I am getting HTTP 500 error at connect() call. My question is, how can I test if connection paremeters are valid?
I have a mac with OSX 10.8.4. I have installed my localhost and it works just fine. I have made a php script, from where I would like to connect MySQL workbench database to. My apache tomcat server runs, and also mysql on the computer, and I use XAMPP. This is my code:
<?php
// Establish connection to DB using PDO
try {
$pdo = new PDO('127.0.0.1:3306', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
echo "Connected!";
} catch (PDOException $e) {
$error = 'ERROR - Connection to DB failed: ' . $e->getMessage();
echo "Connection failed";
exit();
}
I have tried this script to connect to a remote mysql server, where it works fine, but I cannot use it for my localhost. I also tried just to put in localhost in new PDO, but still the same. Does anybody have a clue to what is wrong?
Best Regards
Mads
You'll have an easier time knowing what's not working if you echo the exception being thrown.
Your code
} catch (PDOException $e) {
$error = 'ERROR - Connection to DB failed: ' . $e->getMessage();
echo "Connection failed";
}
doesn't actually print the exception! Try this instead:
} catch (PDOException $e) {
$error = 'ERROR - Connection to DB failed: ' . $e->getMessage();
echo $error;
}
That will at least give you some helpful debugging info.
I have a problem with my database! Here is my code:
<?php
$host = "/homes/49/jc192699/public_html/dbase";
$database = "EduPro.db";
$dbhandle = new PDO("sqlite:".$host.$database);
if (!$dbhandle){
echo "Error connecting to database.\n";
}
else{
echo "<br>";
echo "<br>";
echo "Database connection successful!";
}
mysql_select_db($database);
?>
The problem is that it's saying "Database connection successful!" No matter what I do, if I type the address in wrong, it still says successful, when I renamed the database to a database that doesn't exist, it still says successful. I can't see what the problem is here?
If anybody could help me out it would be GREATLY appreciated!
Thank you!
For starters, the PDO constructor throws an exception if there is an error. It does not return false. Check for errors using
try {
$dbhandle = new PDO("sqlite:".$host.$database);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
Secondly, as you are using SQLite, provided your dbase directory is writeable by the script, your connection attempt will create an empty database.
Try this:
<?php
try {
/*** connect to SQLite database ***/
$dbh = new PDO("sqlite:/path/to/database.sdb");
}
catch(PDOException $e)
{
/*** real error message prints here ***/
echo $e->getMessage();
}
?>
This is directly taken from here:
http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html#4.2
I know that it's not the main idea of this site to answer such kind of questions but in couple of days I'll have the chance to apply for a junior (or maybe more correctly a probationer) position as a PHP programmer and that's why I decided to post here, hoping it will turn out good.
The company is some kind of big compared to others here, so it's well known what is the exam for people wanting to get in this position - it's either - writing a pagination script or some sort of SOAP service.I have no problem with the pagination, but since now I have never payed too much attention to SOAP and now I need to learn tha basics ot SOAP service when used with PHP.Giving the postion I'm applying for, noone expect to show something brilliant but I still I need basic understanding of SOAP client and server sevices, maybe I won't even bother for now about WSDL since I don't think I have enough time for everything.
So I have a sample code that is most likely what I'll need to write and explain If I'm to write SOAP service :
Client side -
<?php
if (isset($_REQUEST["cname"]) && isset($_REQUEST["cpass"]))
{
$cname = $_REQUEST["cname"];
$md5pass = md5( $_REQUEST["cpass"]);
$client = new SoapClient(null, array(
'location' => "http://localhost/test/BuildInSoapWithWSDL/server.php",
'uri' => "urn://localhost/test/BuildInSoapWithWSDL/",
'trace' => 1 ));
try
{
if ( $client->saveUserNameAndPass($cname, $md5pass))
{echo "Data updated!";}
else
{echo "Error updating data!";}
print "<pre>\n";
print "Request :\n".htmlspecialchars($client->__getLastRequest()) ."\n";
print "Response:\n".htmlspecialchars($client->__getLastResponse())."\n";
print "</pre>";
}
catch (Exception $e)
{
echo 'Exception: ', $e->getMessage(), "\n";
}
}
else
{
echo "Error!";
}
?>
server side -
<?php
$server = new SoapServer(null, array('uri' => 'urn://localhost/test/BuildInSoapWithoutWSDL/'));
$server->addFunction("saveUserNameAndPass");
$server->handle();
function database_connect($host, $account, $password, $dbname)
{
$connect = mysql_connect($host, $account, $password);
$connect = mysql_select_db($dbname, $connect);
return $connect;
}
function saveUserNameAndPass($userName,$passWord)
{
try
{
if (database_connect("localhost", "saveuser", "123456", "savetask") == 1)
{
$userName = mysql_real_escape_string($userName);
$sql = "INSERT INTO accounts (name,passmd5) VALUES ('".$userName."','".$passWord."')";
$result = mysql_query($sql);
mysql_close();
if ($result)
{ return true;}
else
{ return false;}
}
else
{
return false;
}
}
catch (Exception $e)
{
return false;
}
}
?>
Even I have the code I still have poor knowledge of what do what.So I need some explanation ot the basics when writing SOAP service and if it's not acceptable this topci to be discussed here I would appreciate any kind of source where these thing are explained from the point of beginner.
Thanks
SOAP is used just the same as you interact with MySQL database. I can give you real life example, for connections to Atlassian JIRA web application.
At first, you just make connection. You will need an WSDL file, that contains all the stuff, that contains every function that this specific SOAP server allows you to do:
try { $soapObject = new SoapClient('http://jira/rpc/soap/jirasoapservice-v2?wsdl'); }
catch(Exception $ex) { die('SOAP connection failed: '$ex->getMessage()); }
After connection has been made, you just use it. If it is needed, login:
$authToken = $soapObject->login(JIRA_LOGIN, JIRA_PASS);
Then send requests to server:
$jqlquery = "status not in (Closed,Resolved) and assignee = user");
try { $issues = $soapObject->getIssuesFromJqlSearch($authToken, $jqlquery, 20); }
catch(Exception $ex) { die('JIRA query failed: '$ex->getMessage()); }
Work on results:
foreach ($issues as $k => $v) { $users[$v->reporter] = array('fullname'=>$soapObject->getUser($authToken,$v->reporter)->fullname,'name'=>$v->reporter); }
$project = $soapObject->getProjectByKey($authToken,"PROJECT");
Note that getIssuesFromJqlSearch, getUser, getProjectByKey and others, are application-specific commands (in this case, all methods/functions are described in JIRA RPC plugin documentation).
That's it. You don't need to "disconnect", afaik when loading finishes, destructor is called, that closes connection by itself.