Can't Link To MySQL database - php

I am learning MySQL/PHP and I cannot figure out how to connect to MySQL on my localhost. I have written a short bit of code and I included root as my user name and root as my password because I have not set these elements yet (as far as I know). I feel that perhaps I am missing something in regards to the username/password combination. However, I feel that this should not be an issue because I have not tampered with the default conditions.
I need some help.
My code is below:
<?php
try {
$db = new PDO("mysql:host=localhost;dbname=shirts4max;port=3306", "root", "root");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf-8'");
} catch (Exception $e) {
echo "Could not connect to the database.";var_dump($e);
exit;
}
I am only seeing the error message on my page:
"Could not connect to the database."
Thank for reading. Please help me Obiwan.

Show the real error. Avoid using root except for maintenance.
From the PDO Manual page here, modified for you
<?php
$dsn = 'mysql:dbname=shirts4max;host=localhost';
$user = 'root';
$password = 'root';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>

Have you tried connecting via command line using: mysql -uroot -proot -hlocalhost -p3306? If you can't connect that way, the PDO connection won't go through either. Playing with the connection info via command line gives you a nice easy way to find what works, then include it in your code. Also, if you've not set the user/pw, it's possible there isn't one currently, so you wouldn't need those parameters at all.

Related

PHP PDO connection failing without error

It's been many years since I did any dev in PHP.
The concept of connecting to MySQL using PDO is completely new to me, and I don't seem to be able to get it to work.
Using MySQLi, and the following code, which I know is deprecated, works nicely:
<?php
include 'models/db_details.php';
$db_connection = mysql_pconnect("$dbhost", "$dbusername", "$dbpasswd") or die("Couldn't connect to server: " . mysql_error());
$db = mysql_select_db("$dbname", $db_connection) or die("Couldn't select database.");
?>
<h1>After connecting to the DB</h1>
As expected, this displays:
After connecting to the DB
From all of the pages I have read, using PDO, this should look something like:
<?php
include 'models/db_details.php';
try
{
$conn = new PD0("mysql:host=$dbhost;dbname=$dbname;charset=utf8", $dbusername, $dbpasswd);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
<h1>After connecting to the DB</h1>
The result of this is a completely blank page.
All of this is on a FreeBSD box, running:
Apache/2.4.25
PHP/5.6.30
MySQL 5.6.35
I have uncommented extension=php_pdo_mysql.dll in php.ini.
I can also confirm that the MySQL driver for PDO is installed:
What am I missing?
Check the font. Make sure it is pdo and not pd0 (zero).
Magic happens after that.

My file corrupt when using db connection

I have a download script which get id of file and search in database and find it's name. But when I include my db connection the files get corrupted on download.
when I comment my db connection and give file name manually file downloading work fine.
I test my db connection and there wasn't any excpetion or any html output , what do you think my problem is?
<?php
session_start();
try{
$db= new PDO("mysql:host=localhost;dbname=dbname","user","pass");
$db->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
$db->exec("SET NAMES 'utf8'");
}catch (Exception $e){
//echo "something wrong in db.php";
echo $e->getMessage();
exit;
}
?>
I run my code on windows server IIS, if it does matter
Just try with this code..
error_reporting(E_ALL);
ini_set('display_errors','1');
$dsn = 'mysql:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
try {
$dbh = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
It will return your error.
after few days struggling and headache finaly problem resolved by deleting try catch block

MAMP localhost not Responding

I am trying to run php file using MAMP on my mac system having maverick operating system.
it was working good before but suddenly it stop responding.
when I run html file it work fine even when I run any .php file with out database PDO it work fine but when I try to run php file with PDO database connection, localhost does work.
any concrete suggestions. welcome !
<?php
try
{
$host ="localhost";
$db ="ijdb";
$user="ijdbuser";
$pwd = "ijdbuser";
$pdo = new PDO('mysql:host=$host; dbname = $db', $user, $pwd);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec('SET NAMES "utf8"');
}
catch (PDOException $e)
{
$output = 'Unable to connect to the database server.';
include 'output.html.php';
exit();
}
$output = 'Database connection established.';
include 'output.html.php';
There are a few reasons as to why it's failing.
1) Variables do not get parsed in singles quotes
2) You have spaces; there should not be any.
'mysql:host=$host; dbname = $db'
//^ ^ ^
needs to read as:
"mysql:host=$host;dbname=$db"
^ ^
You may also want to use:
$pdo->exec("SET NAMES utf8");
Nota:
You should also modify your catch{...} to read as:
catch(PDOException $e) {
print $e->getMessage();
}
to get the real reason as to why it's failing.

Can't connect to database through PHP PDO class

I'm trying to connect to my mySQL database using the PDO class in PHP.
Here is my Code :
// Connects to Our Database via PDO.
if($local) {
try {
$db = new PDO("mysql:=localhost;dbname=bbc_archive;port=3306", "root", "");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch(Exception $e) {
echo "Connection to the DataBase was not possible. ";
die();
}
} else {
try {
$db = new PDO("mysql:=bbcarchive.db.11505263.hostedresource.com;dbname=bbcarchive", "bbcarchive", "myPassword");
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$db->exec("SET NAMES 'utf8'");
} catch(Exception $e) {
echo "Connection to the live DataBase was not possible. ";
die();
}
}
The $local variable is defined before and determines whether or not the script is running on a the live server or a test server.
When running in my local environment everthing works fine but on my live server it echo's out "Connection to the live DataBase was not possible." from the catch block.
I've contacted my host provider (godaddy) and they think it's a coding error. I've also, obviously, checked the hostname, dbname, username and password a 100 times and it's all correct. I just can't see the problem!
How can i do this ?
Your DSN seems to be incorrect. The documentation on MySQL DSNs indicates that it should look somewhat like this:
$db = new PDO("mysql:host=localhost;dbname=bbc_archive;port=3306", "root", "");

Check if connected to database (right username/password, host)

I would love to check if i can connect to database using given username, password, and database host.
So far i was trying:
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$conndatabase = mysql_select_db($dbname);
if(!mysql_ping($conn) || !$conndatabase){
//do something when cant connect
} else {
//do something when you connected
}
It works when i give bad $dbname, cuz it cant select this database. But when i give wrong host, username or password, it will give me white page with errors. For example:
Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'rootx'#'localhost' (using password: YES) in C:\xampp\htdocs\strony\planer\config\opendb.php on line 6
Warning: mysql_ping() expects parameter 1 to be resource, boolean given in C:\xampp\htdocs\strony\planer\grupy.php on line 3
Question:
Is there a way to check if i can connect using given data without errors? It just gives errors before getting to mysql_ping()
EDIT
After trying Mike Brant solution, i think i could have explained it wrong. I am trying to connect to database, and if it lets me, it shows user page he wanted to access, but when it's impossible, it redirects him to the other page, to modify database information.
if(!$conndatabase){
header('Location: index.php');
}
I am using that for checking if database exists. But if i try if(!$conn) or something similar, its too late, because i got errors displayed on $conn = mysql_connect($dbhost, $dbuser, $dbpass). So i cant redirect, as it gives me
Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'root'#'localhost'~~
Warning: Cannot modify header information - headers already sent by~~
Yes. Just test the value of $conn. If it is false then the connection failed, and you shouldn't even try to proceed to the db selection step.
Your code might look like this:
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if (false === $conn) {
throw new Exception('Could not connect to database: ' . mysql_error());
}
$db_select = mysql_select_db($dbname. $conn);
if (false === $db_select) {
throw new Exception('Could not select database: ' . mysql_error($conn));
}
The PHP documentation is very clear on this: http://php.net/manual/en/function.mysql-connect.php
By the way, you should look at using mysqli or PDO as mysql_* functions are deprecated.
Try to debug your connection with something like
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link){
die('Could not connect: ' . mysql_error());
}
In this way you can easilly check if connection is estabilished otherwise you will print an error.
Then I would like to remember you that mysql_ functions are deprecated so i would advise you to switch to mysqli or PDO
When you look on my edit in question, you can see those answers didn't solve my problem completely. I still lacked some way to avoid errors. That's where i used error_reporting(0);.
I am not sure if that's best solution, but it works like a charm for me.
So the code for everything i tried to achieve looks like that:
opendb.php file
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password123';
$dbname = 'databasename';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$conndatabase = mysql_select_db($dbname);
?>
And there on the site i am checking connection:
<?php
error_reporting(0);
include 'opendb.php';
if(!mysql_ping($conn) || !$conndatabase){
header('Location: index.php'); //or any other site where you can config your database connection information.
}
So yeah, thats complete solution to my problem. I guess i could use !$conn instead of !mysql_ping($conn) with same result.
As has already been said, it’s the first example on the PHP manual page for the mysql_connect function.
Secondly, you should be either using the mysqli_ functions or PDO, as the mysql_ functions are deprecated and currently being phased out.
To check a connection with PDO:
try {
$db = new PDO('mysql:host=127.0.0.1;dbname=dbname', 'user', 'pass');
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e) {
header('HTTP/1.1 500 Internal Server Error');
die($e->getMessage());
}

Categories