i'm in trouble. I'm trying to connect remote mysql server with pdo (php 5.4.12). With this code it's connect normally:
$dbh=new PDO('mysql:host=xxx.xxx.xxx.xxx;dbname=newdb', $user, $pass);
But, if i try set host with variable, like this:
$host='xxx.xxx.xxx.xxx';
$dbh=new PDO('mysql:host='.$host.';dbname=newdb', $user, $pass);
It's just thinks sometime, and tell me:
Fatal error: Uncaught exception 'PDOException' with message ' in
D:\wamp\www\test.php on line 21
21 it's line of creating new PDO object.
Ok, i'm try to catch exception (sorry, it's new for me), and now i have this:
Error!: SQLSTATE[HY000] [2002]
Can you help me, please?
Double quoting not helps
$dbh = new PDO("mysql:host=$host;dbname=newdb", $user, $pass);
Nothing changed.
var_dump('mysql:host='.$host.';dbname=newdb');
string 'mysql:host=xx.xx.xxx.xxx;dbname=newdb' (length=37)
Way with {} not helped for me.
Ok, the situation becomes clear. I'm try to connect another server on another IP, and it's normally connected. Can it be mysql server security options?
Try this way
$host = "xxx.xxx.xxx.xxx";
$dbh = new PDO("mysql:host={$host};dbname=newdb", $user, $pass);
The double quotes and the braces to include the var in the string as you can see here
http://www.php.net/manual/en/language.operators.string.php
Related
I'm trying to get PDO connecting to an SQL server to enter READ UNCOMMITTED, according to various sources (https://msdn.microsoft.com/en-us/library/cc296183(v=sql.105).aspx) this is how you do it.
$pdo = new PDO ("sqlsrv:server=$hostname;database=$dbname",$username,$pw,[PDO::SQLSRV_TXN_READ_UNCOMMITTED]);
This results in a PDOException: "The auto-commit mode cannot be changed for this driver"
When you're using PDO, you have to use this form:
$conn = new PDO("sqlsrv:Server=".$hostname.
";Database=".$database.
";TransactionIsolation=".PDO::SQLSRV_TXN_READ_UNCOMMITTED,
$username, $pw);
https://msdn.microsoft.com/en-us/library/ff628167.aspx
I can't find an answer to this anywhere. Maybe its really simple
I have my mysql PDO connection like this:
try{
$DBH = new PDO("mysql:host=$db_hostname;dbname=$db_database", $db_username, $db_password);
$DBH->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
catch (PDOException $e){
echo $e->getMessage();
exit;
}
i want to just test if the connection worked, ie. if the password, username, databasename & hostname were spelled correctly.
the try, throw just seems to pick up fundamental errors, like if the driver is spelt wrong. it doesnt throw an error if say the password is wrong.
thanks
In a single click from this question, in the PDO tag wiki lies the exact how-to:
$dsn = "mysql:host=localhost;dbname=test;charset=utf8";
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn,'root','', $opt);
As well as a warning
DO NOT use try..catch operator just to handle an error message.
Uncaught exception already excellent for this purpose, as it will treat PDO errors just the same way as other PHP errors - so, you can define the behavior using site-wide settings.
A custom exception handler could be added later, but not required. Especially for new users, it is recommended to use unhandled exceptions, as they are extremely informative, helpful and secure.
More info...
I use the following code to connect:
<?php
class dbConnection extends PDO{
public function __construct() {
switch(DB_TYPE){
case "mysql":
$dbconn = "mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET;
break;
case "sqlite":
$dbconn = "sqlite:".DB_PATH.";charset=".DB_CHARSET;
break;
case "postgresql":
$dbconn = "pgsql:host=".DB_HOST." dbname=".DB_NAME.";charset=".DB_CHARSET;
break;
}
parent::__construct($dbconn,DB_USER,DB_PASS,array(PDO::ATTR_EMULATE_PREPARES => false,PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
}
?>
If I give wrong password, I get
Connection error, because: SQLSTATE[28000] [1045] Access denied for
user 'microaid_logger'#'localhost' (using password: YES)
As Your common sense pointed out, an exception is already thrown in case the connection is not succesful, which will also trigger if the password is wrong. If you want to format the text of the error message or handle it, just set a custom error handler as described here
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I've been advised to use anti-sql injection methods, as I am inserting values inside my database. I've looked around the web, and my first failed attempt is this, of which I need some help, with the PDO method. I found examples online to be waaay too empty of substance for me to understand (btw, I ran a line and it told me PDO is enabled):
Is this good in any way, shape or form?
<?php
include ('config.php');
// Host, User, Pass, DB
$con=mysqli_connect("127.0.0.1","*****","*****","*****");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQLi: " . mysqli_connect_error();
}
$host = 'localhost';
$dbname = '****';
$user = '****';
$pass = '*****';
try {
# MS SQL Server and Sybase with PDO_DBLIB
$DBH = new PDO("mssql:host=$host;dbname=$dbname, $user, $pass");
$DBH = new PDO("sybase:host=$host;dbname=$dbname, $user, $pass");
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
# SQLite Database
$DBH = new PDO("sqlite:my/database/path/database.db");
}
catch(PDOException $e) {
echo $e->getMessage();
}
Also, I get this error upon submitting my form:
Fatal error: Call to a member function prepare() on a non-object in /home/product/*****/*****/*****/processForm-test.php on line 68
One big problem in your code is that it's using both mysqli_connect and PDO to create database connections. Don't do that; that's not supported. Use one or the other.
The lines you have that make PDO connections attempt to connect to four separate databases, SQL Server, Sybase, MySQL and SQLLite, all running on localhost. But you are keeping a handle to only the last one, since you're assigning the database connection to the same variable.
That variable $DBH is your reference to the database session (connection), if the connect succeeds. If it doesn't succeed, that gets assigned a value of false, which you can test, before you proceed.
I think all you need is a single PDO connection to MySQL, like this:
<?php
include ('config.php');
$host = 'localhost';
$dbname = '****';
$user = '****';
$pass = '*****';
try {
# MySQL with PDO_MYSQL
$DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
}
catch(PDOException $e) {
echo "Connect failed: " . $e->getMessage();
}
I'm extrapolating here, but the most likely explanation for the error message you are getting is that you've got a line of code (not shown in your code sample) like this:
$sth = $DBH->prepare($sql);
The issue is that $DBH is not a reference to valid database connection. $DBH has a value of 'false', and that's because the attempt to connect to the database failed. And false is not an object, so there's no way it can have a method named 'prepare' associated with it.
I'm new at mongoDB and am trying to connect using php driver..
this is my code :
$this->connection = new Mongo("mongodb://tatao_user:tatao_pass#ds043047.mongolab.com:43047/tatao");
but it didn't work and resulting in the error below :
Fatal error: Uncaught exception 'MongoConnectionException' with message 'Couldn't authenticate with database tatao: username [tatao_user]'
I've also tried using the shell, but the reuslt is the same.
please help....
Thx B4...
First of all you need to check if mongodb is running and you have no errors.
Then if you are sure your credential (user and password) are right try this:
<?php
$mongo = new Mongo();
$db = $mongo->db_name; //replace db_name with your db name obviously
$username = "myuser";
$password = "mypassword";
$db->authenticate($username, $password);
?>
you should also check the manual:
http://php.net/manual/en/mongo.connecting.php
Then, i use Codeigniter too, and there is a really good library for mongodb, simple and fast, using Active Records and all the staffs as for the standard database library of CI.
I really suggest you to use that, you can check that here:
https://github.com/alexbilbie/codeigniter-mongodb-library
I am writing an installer for one of my apps and I would like to be able to test some default database settings.
Is this possible using PDO to test valid and invalid database connections?
I have the following code:
try{
$dbh = new pdo('mysql:host=127.0.0.1:3308;dbname=axpdb','admin','1234');
die(json_encode(array('outcome' => true)));
}catch(PDOException $ex){
die(json_encode(array(
'outcome' => false,
'message' => 'Unable to connect'
)));
}
The problem I am having is that the script trys to connect until the script execution time of 60 seconds runs out instead of saying it cannot connect to the db.
Thanks
you need to set the error mode when connection to the database:
try{
$dbh = new pdo( 'mysql:host=127.0.0.1:3308;dbname=axpdb',
'admin',
'1234',
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
die(json_encode(array('outcome' => true)));
}
catch(PDOException $ex){
die(json_encode(array('outcome' => false, 'message' => 'Unable to connect')));
}
for more infos see the following links:
Using MySQL with PDO
Errors and error handling
As #Sascha Galley already mentioned you should set error mode to exception mode. However, you should also set up PDO::ATTR_TIMEOUT attribute to prevent a long time waiting for response in some cases.
Although documentation says that behavior of this attribute is driver-dependent in case of MySQL it's a connection timeout. You won't find anything about it documentation but here's a short snippet from driver's source code:
long connect_timeout = pdo_attr_lval(driver_options, PDO_ATTR_TIMEOUT, 30 TSRMLS_CC);
As seen e.g. in the comments at this answer (but hardly anywhere else, so I made it more visible here), the "classic" PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION solution does not always work.
The implementation of PDO::ERRMODE_EXCEPTION is broken, so it seems to be "leaking" in some cases.
For example:
Warning: PDO::__construct() [pdo.--construct]: [2002] No connection could be made because the target machine actively refused
it. (trying to connect via tcp://localhost:3306) in
[...] db.php on line 34
The code there:
try {
$this->pdo = new PDO($cfg['DB'], $cfg['DB_USER'], $cfg['DB_PASS'],
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
} catch {
echo("Can't open the database.");
}
The exception is thrown (and cought: I can see my message).
So, as a necessary workaround, you need to also put a # (let's call it a "diaper operator" in this case) before new pdo(...) to actually keep it clean.
There's a missing closing parenthese at the end of PDO::ERRMODE_EXCEPTION.
Should be:
$this->pdo = new PDO($cfg['DB'], $cfg['DB_USER'], $cfg['DB_PASS'],
array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));