How to get PHP and PDO working in Godaddy shared hosting? - php

I have a fatal error showing when I am trying to get MySQL to use a PDO instance in Godaddy shared hosting.
Code I tried to connect my database:
code 1
try{
$connect = new PDO('mysql:host=localhost;dbname=dbname;charset=utf8', 'user', 'password',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
$connect->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
die('Error connecting to database');
}
When I used this code, it is printing 'Error connecting to database'
code 2
$dsn = 'mysql:host=localhost;dbname=dbname';
$user = 'user';
$password = 'password';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
When I used this code it is printing an error:
'Connection failed: SQLSTATE[HY000] [1044] Access denied for user 'user'#'localhost' to database 'dbname"
Godaddy support is saying it is a string error that I have to review from my end and they are asking paid service to resolve it from their end. I found this both code running in my local server (xaamp).

First, make sure everything is correct in your config array, then add '\' this before PDO instance:
// Define Config Options
$config = [
'username' => 'YourUsername',
'password' => 'YourPassword',
'database' => 'YourDatabase'
];
// Make a function to easily access it
function connect($config)
{
try{
$conn = new \PDO('mysql:host=localhost;dbname=' .$config['database'], $config['username'], $config['password']);
$conn->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
return $conn;
}
catch(Exception $e){
return false;
}
}

In shared hosting you normally find that the mysql server is not localhost, you normally find that your provider will place the mysql server on a separate machine.
Login in to you control panel with godaddy and look at the settings, you'll probably have to create a database first.

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.

Unable to connect PHP application with MySQL

From a friend, I got a website (zip file) with PHP and HTML files in it. I also got a SQL script from him. Now what I'm trying to do is run the application on localhost (Xampp apache server) and the website does load, but it looks like I can't connect to the database.(I did import the SQL script and it worked, But I'm still getting this error) This is an error for example that I'm receiving on the home page:
Connection failed: SQLSTATE[HY000] [1045] Access denied for user 'dewaai'#'localhost' (using password: YES)
Notice: Undefined index: logged in C:\xampp\htdocs\deWaai\includes\header.php on line 14
The name of the database is 'dewaai'
The username is: root
And I think there is no password...
This is the connection.php file:
<?php
session_start();
include "db.php";
$db = new db();
$db->setDB("localhost", "dewaai", "dewaai", "dewaai");
$db->connect();
?>
These are database functions in the db.php file:
<?php
class db {
private $conn;
private $servername;
private $dbuser;
private $dbpass;
private $dbname;
function setDB($servername, $dbuser, $dbpass, $dbname) {
$this->servername = $servername;
$this->dbuser = $dbuser;
$this->dbpass = $dbpass;
$this->dbname = $dbname;
}
function connect() {
try {
$this->conn = new PDO("mysql:host=$this->servername;dbname=$this->dbname", $this->dbuser, $this->dbpass);
// set the PDO error mode to exception
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
Does anyone know how I can fix this so the database runs the application?
I really don't know why I'm getting that error.
Any kind of help is appreciated, thx
There is problem with your username or password.
$db->setDB("localhost", "root", "", "dewaai");
Try this it will help you to connect with your database
Hi the issue clearly from the error message states that your username and password given in connection.php file is incorrect.
The format for DB connection is
$db->setDB( Database host IP address or DNS name , Username , Password, DatabaseName);
From what you said i guess connection.php file should be
<?php
session_start();
include "db.php";
$db = new db();
$db->setDB("localhost", "root", "", "dewaai");
$db->connect();
?>
And i think your PDO connection might have an issue as well. It should be
$this->conn = new PDO('mysql:host='.$this->servername.'; dbname='.$this->dbname, $this->dbuser, $this->dbpass);
Hope this helps.

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".

How I check PDO connected to appropriete database

I use this code for check connection to the database(MYSQL).If the database name not available then also it show connect successfully.
if(isset($_REQUEST['submit']))
{
echo $name = $_REQUEST['name'];
echo $pwd = $_REQUEST['password'];
$servername = "localhost";
$username = "root";
$password = "";
try
{
$conn = new PDO("mysql:host = $servername;dbname = pdo",$username,$password);
//echo "Connected successfully";
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "connect successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
}
TL;DR
Because your code is using try-catch blocks you can be sure that as long as no exceptions are thrown the connection was successfully established. Otherwise check the error code stored inside the exception to resolve the type of error.
More detailed
Your code makes use of exceptions, so if an error occurred while a connection was attempted established an exception would be thrown. As far as I know the PDO object throws exceptions by default while it is constructed and falls back to silent mode when to instance is created. So you are assured you will be warned if anything bad happens during construction.
Update 1
How to check the database name is available or not in to the database using PDO?
As said you can utilize exceptions. But instead of echoing the exception message you can inspect the returned error code using the PDOException method getCode(). Using php version 5.6.8 I will get the code 1049. You can then check using the following:
try {
$pdo = new PDO($dsn, $username, $passowrd, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
]);
}catch(PDOException $exception) {
if($exception->getCode() == 1049) {
echo 'Database does not exist!';
}
// Continue error handling...
}
Update 2: Alternative
Using the same PHP version as above you can avoid selecting a database in the DSN. With this you can fetch a list of accessible databases for the used MYSQL user. Using this list you can check the existence of one or more databases at the same time and avoid the overhead of an exception halting execution of your script.
/*
* I assume you are on localhost.
*/
$pdo = new PDO('mysql:host=127.0.0.1', $username, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
]);
$databases = $pdo->query('SHOW DATABASES'); // Does not require a prepared statement since it takes no input.
/*
* The following can be done more elegant/efficient.
*/
$exists = false; // Equals TRUE if the database exists.
$check = 'test'; // Enter the database to check for.
foreach($databases->fetchAll(PDO::FETCH_ASSOC) as list($database)) {
if($database == $check) {
$exists = true;
break;
}
}
Bonus
You are setting the error mode after the PDO instance has been constructed. This can also be done with the fourth parameter of PDO's constructer. I think this leads to more readable code.
I would also recommend setting the configuration PDO::ATTR_EMULATE_PREPARES to false. This ensure prepared statements are always used. The documentation can be found here.
$pdo = new PDO($dsn, $username, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_EMULATE_PREPARES => false
]);
Happy coding!

PDO no such file or directory - only ftp server access

I'm moving our php administration to a new server (hosted) but while trying out the migrated system, I detected that our code is unable to access the MySql database. The code was working before and the new webhost says it is supporting PDO. We have no ability to access the actual server more than via ftp and phpmyadmin, preventing us from accessing php.ini. We would prefer to be able to keep using PDO.
Any ideas how to fix this, and if not
How could we have this file working in the same/a similar way but without PDO?
Class Database{
protected $_link;
public function __construct(){
$config['db'] = array(
'hostname' => 'localhost', //The provided XXX.loopia.se and 127.0.0.1 has also been attemped here with no result
'dbname' => 'database_name',
'username' => 'user_name',
'password' => 'password'
);
$db = new PDO('mysql:hostname=' . $config['db']['hostname'] .';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$this->_link = $db;
}
}
Log output:
PHP Warning: PDO::__construct() [pdo.--construct]: [2002] No such file or
directory (trying to connect via unix:///tmp/mysql.sock)
Link to loopia's "PHP to SQL"-use-this-code: https://support.loopia.se/files/php_till_mysql.zip
After quick feedback from the webhost, the above does not seem to be the preffered way to accomplish this at loopia. For further reference for other googlers, this is the code received (and edited to match the above purpose):
<?php
Class Database{
protected $_link;
public function __construct(){
$hostname = "xXXX.loopia.se"; //Log on to phpmyadmin and see what it says in the top after "server"
$username = "username";
$password = "password";
try {
$db = new PDO("mysql:host=$hostname;dbname=<DBNAME>",
$username,
$password,
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$this->_link = $db;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
?>

Categories