I am trying to catch an error if I cannot connect to database (eg xamp down or database connection down etc). I have tried to use PDO::errorCode() but yield no reuslts.
In my php I have a connection.php and a method ' to connect to the datatbase many times and return a new PDO instance to achieve various queries. The response displays the error message then all the php queries that call it, which also includes the name and password of the database in a non encrypted format.
How can I catch this error and replace this error message with a human readable alternative (that doesnt display the name and password)?
CONNECTION.PHP
function connect()
{
// set database server access variables:
$host = "localhost";
$user = "root";
$pass = "password";
$dbase = "dbName";
//Establish a connection
$db = new PDO("mysql:host=".$host."; dbname=".$dbase."", $user, $pass); //line 16
$db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
return $db;
}
RESPONSE
Fatal error: Uncaught exception 'PDOException' with message
'SQLSTATE[HY000] [2002] No connection could be made because the target
machine actively refused it. ' in
D:\Users\Username\Dropbox\Web\htdocs\sitename\php\data\connection.php:16
Stack trace: #0
D:\Users\Username\Dropbox\Web\htdocs\sitename\php\data\connection.php(16):
PDO->__construct('mysql:host=loca...', 'root', 'password') #1
D:\Users\Username\Dropbox\Web\htdocs\sitename\php\function\active-user.php(28):
connect() #2
D:\Users\Username\Dropbox\Web\htdocs\sitename\map-floorplan.php(10):
include('D:\Users\Username...') #3 {main} thrown in
D:\Users\Username\Dropbox\Web\htdocs\sitename\php\data\connection.php
on line 16
do a try/catch to catch exceptions
try{
$db = new PDO("mysql:host=".$host."; dbname=".$dbase."", $user, $pass); //line 16
$db -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
return $db;
} catch( PDOException $e){
$originalError = $e->getMessage();
echo 'something went wrong.. '.$originalError;
exit;
}
Related
here i am trying to connect to MySQL database using PHP-PDO from remote server using IP address. when put ip address in place of host it gives me following error
Warning: PDO::__construct(): php_network_getaddresses: getaddrinfo failed: No such host is known. in D:\xampp\htdocs\oppInsights\database\Database.php on line 32
Fatal error: Uncaught exception 'Exception' with message 'SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: No such host is known. ' in D:\xampp\htdocs\oppInsights\database\Database.php:39 Stack trace: #0 D:\xampp\htdocs\oppInsights\database\Select.php(800): Database->Connection() #1 D:\xampp\htdocs\oppInsights\decision.php(19): Select->expiryContracts() #2 {main} thrown in D:\xampp\htdocs\oppInsights\database\Database.php on line 39
this is the code
<?php
class Database {
public $dbhost = "mysql:dbname=apt;host=http://10.75.225.171:3601";
public $dbuser = "tribhuvan";
public $dbpass = "123456";
public $dbname = "apt";
public $connection;
public $selectdb;
public $isConnected;
public $dbh;
//$user = 'dbuser';
//$password = 'dbpass';
public function Connection()
{
try
{
$this->dbh = new PDO($this->dbhost, $this->dbuser, $this->dbpass);
// echo "true";
return $this->dbh;
}
catch(Exception $e)
{
$this->isConnected = false;
throw new Exception($e->getMessage());
}
}
public function Disconnect()
{
$this->datab = null;
$this->isConnected = false;
}
}
?>
i have checked username and password they seems to be same as i gave.thank you in advance.
You need to remove http from the host and put the port number under port attribute.
Please try with this line :
$dbhost = "mysql:host=10.75.225.171;port=3601;dbname=apt";
I am trying to create a PDO object in a class and then use it in another file. The PDO Object gets created (as far as I understand) but I can not use it in the other file and I view these outputs:
PDO Object ( )
connection successful.
Fatal error: Uncaught Error: Call to undefined method
app\db\Connect::query() in /var/www/html/pdoTest/index.php:25 Stack
trace: #0 {main} thrown in /var/www/html/pdoTest/index.php on line 25
My code is as following:
index.php
<?php
ini_set('display_errors', '1');
require_once './vendor/autoload.php';
$con = new \app\db\Connect();
if (!$con)
{
echo 'no PDO object available.';
}else{
echo 'connection successful.' . '<br>';
}
connect.php
<?php
namespace app\db;
use PDO;
class Connect
{
public function __construct()
{
// set the connection variables
$host = 'localhost';
$dbname = 'pdoposts';
$username = 'root';
$password = 'root';
// create the DSN
$dsn = 'mysql:host=' . $host . ';dbname=' .$dbname;
// create PDO connection
try {
$con = new PDO($dsn, $username, $password);
print_r($con);
echo '<br>';
} catch(Exception $e) {
echo $e->getMessage();
}
return $con;
}
}
I have searched all over stackoverflow and other parts of internet but as it seems I am out of luck understanding what my problem is in using the created PDO object. Would you please help me understand it?
I just start learning about PDO, I need some help, I Installed PHPStorm, and I just start using it too, I already have a datbase on phpMyAdmin, I made this code, but it gives me an error
<?php
try {
$handler = new PDO ('mysql:localost;dbname=Database', 'root', 'password');
$handler -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOExeption $e)
{
die('Sorry, Database problem');
}
$query = $handler->query('select * from users');
while($r= $query->fetch())
{
echo $r['name'];
}
?>
here is the error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected' in C:\Users\user1\PhpstormProjects\PDO\pdo.php:11 Stack trace: #0 C:\Users\user1\PhpstormProjects\PDO\pdo.php(11): PDO->query('select * from u...') #1 {main} thrown in C:\Users\user1\PhpstormProjects\PDO\pdo.php on line 11.
Any help?
thanks in advance :).
Please make sure your database actually exists and that there are no spelling mistakes in your connection code.
Edit 1
I also noticed this issue with your connection I'm not sure if this is what is causing it but you need mysql:host= not just mysql:localhost. Also you have a spelling mistake localost.
Change this,
$handler = new PDO ('mysql:localost;dbname=Database', 'root', 'password');
To,
$handler = new PDO('mysql:host=localhost;dbname=myDb', $username, $password);
replace the handler declaration for this:
$handler = new PDO('mysql:host=localhost;dbname=myDatabase', $username, $password);
where myDatabase is the one you will be using as default..
Is the connect() function depecrated or something? When I try to connect to a mysql database using that function, my page stops working?
i'm doing jeffrey ways 30daysjquery course lesson 25
here's the code in my index.php file
<?php
require 'functions.php'
if ( isset($_POST['q'])) {
connect();
}
include 'views/index.tmpl.php'
?>
This is my code in my functions.php file
<?php
function connect(){
global $pdo; // set it as global so other functions can access it
$pdo = new PDO("mysql:host=localhost;dbname=sakila", "root", "root");
}
function get_actors (){
}
?>
Might it be that I do not have access to the content that's in functions.php? if it is how do I create access?
Your function should maybe return a connection:
function connect(){
$pdo = new PDO("mysql:host=localhost;dbname=sakila", "root", "root");
return $pdo;
}
Then, your function get_actors() could be
$db_connection = connect();
get_actors( $db_connection );
function get_actors( $pdo ) {
//
// You use the database connection $pdo to get actors
//
}
You have to add a parameter to your function get_actors. No need to modify the code into the function.
When I checked MAMP this is the information I have if I want to connect to a MySQL server using a script.
Host localhost
Port 8889
User root
Password root
Socket /Applications/MAMP/tmp/mysql/mysql.sock
thrown in /Applications/MAMP/htdocs/lesson-25/functions.php on line 5
[09-Nov-2014 23:01:47 Europe/Berlin] PHP Fatal error: Uncaught exception 'PDOException' with message 'could not find driver' in /Applications/MAMP/htdocs/lesson-25/functions.php:5
Stack trace:
#0 /Applications/MAMP/htdocs/lesson-25/functions.php(5): PDO->__construct('mysql:host=loca...', 'root', 'root')
#1 /Applications/MAMP/htdocs/lesson-25/functions.php(9): connect()
#2 /Applications/MAMP/htdocs/lesson-25/index.php(3): require('/Applications/M...')
#3 {main}
My friend and I are working on a website, and I am trying to install a build of it on my machine. It is already running live on the server, I just can't seem to connect from my local machine. When I do I get the following error:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] [1045]
Access denied for user 'myusername'#'adsl-client.example.net' (using password: YES)' in /Users/myname/Sites/mysitefolder/req/connect.php:25
Stack trace: #0 /Users/myname/Sites/mysitefolder/req/connect.php(25): PDO->__construct('mysql:host=mysq...', 'myusername', 'mypassword')
#1 /Users/myname/Sites/burn-after-reading/inc/header.php(9): ConnectionFactory->getConnection()
#2 /Users/myname/Sites/burn-after-reading/index.php(79): include('/Users/myna...')
#3 {main} thrown in /Users/myname/Sites/mysitefolder/req/connect.php on line 25
Here is the file I am trying to connect from, connect.php
<?php
class ConnectionFactory
{
var $dbhost = 'mysql.mysitename.io';
var $dbname = 'my_database_name';
var $dbusername = 'myusername';
var $dbpassword = 'mypassword';
private static $factory;
public static function getFactory()
{
if (!self::$factory)
self::$factory = new ConnectionFactory();
return self::$factory;
}
public function getConnection()
{
$conn = new PDO("mysql:host={$this->dbhost};dbname={$this->dbname}",
$this->dbusername,
$this->dbpassword);
return $conn;
}
public function getConnectionNoName()
{
$connNoName = new PDO(
"mysql:host={$this->dbhost}",
$this->dbusername,
$this->dbpassword
);
return $connNoName;
}
}
For security reason you need to add your IP address to the list of allowed remote mysql connections.