PHP Laravel Framework Database Connection Error - php

I created a database called learning-laravel and I created a table which is users I want to get data from that table I wrote this code block:
Route::get('/',function()
{
$users = DB::table('users')->get();
return $users;
});
but I'm getting this type of error:
PDOException
SQLSTATE[HY000] [2005] Unknown MySQL server host 'localhost:3306' (2)
*/
public function createConnection($dsn, array $config, array $options)
{
$username = array_get($config, 'username');
$password = array_get($config, 'password');
return new PDO($dsn, $username, $password, $options);
}

Try instead of including the port in the host, add a "port" key and the port in a seperate key.
'host' => 'localhost',
'port' => '8889'
Looks like it may be trying to use that entire string as the host name.

As you said in your comment above, you have your MAMP settings pointing MySQL requests to port 3306. Here is the correct setting in that case:
'host' => 'localhost',
'port' => '3306'
Also, the "is it plugged in" suggestion would be to make sure your DB is actually running.

The solution is:
'host' => 'localhost:3306',

Related

how to set dynamic database values through classes and objects in php5

This is my code
<?php
class Connection
{
function __construct()
{
if(isset($_SERVER['SERVER_NAME']))
{
switch($_SERVER['SERVER_NAME'])
{
case 'www.hashstar.com':
$this->default = $this->dev;
break;
case 'www.hashstar.in':
$this->default = $this->prod;
break;
}
}
else
{
$this->default = $this->dev;
}
}
public $dev = array(
'host' => 'localhost',
'login' => 'root',
'password' => '',
'database' => 'dbname',
);
public $prod = array(
'host' => 'localhost',
'login' => 'db_admin',
'password' => 'Admin#.2017',
'database' => 'db_main',
);
public function establish_connection()
{
$connection = new mysqli($this->host, $this->user, $this->pass, $this->db);
if($connection == TRUE)
{
return $connection;
}
else
{
die("Could Not Establish Connection! ".$connection->error);
}
}
}
?>
The problem with this code is that i have declared here varaibles 1st for offline and 2nd for online as i am using git i have to again and again change the codes before pushing to master branch. I even tried to use the .gitignore feature but it isn't working as well but still i wan to set the variables dynamically according to the server host.
I have tried using the switch case thing but its giving an syntactical error while compiling. Can anyone help mw with this code.
Any helps appreciated.
Set your database credentials in a new file that you will then add to .gitignore like so :
$dbConfig = array(
"host" => "localhost",
...
)
then simply access to your $dbConfig in your Connection class

PDO with extended PDOStatement cannot disconnect the connection when set NULL

Tested in PHP 5.5.22 and 5.5.25
When using PDO that has extended PDOStatement, MySQL keep connection until when PHP script are finished.
use PDO;
$dbinfoCode = array(
'userid' => 'userid',
'password' => 'password',
'engine' => 'mysql',
'host' => '192.168.100.2',
'database' => 'test',
);
for ($i = 0; $i < 10000; $i++) {
$dsn = sprintf("%s:host=%s;dbname=%s", $dbinfo['engine'], $dbinfo['host'], $dbinfo['database']);
$pdo = new PDO($dsn, $dbinfo['userid'], $dbinfo['password'], $options);
$pdo->setAttribute (PDO::ATTR_STATEMENT_CLASS, array ('PDOStatement2', array($pdo)));
$pdo = null;
}
class PDOStatement2 extends PDOStatement {
}
I can see increasingly stacked "Sleep" processes on MySQL query. Finally, MySQL throw error "Too many connections".
SHOW PROCESSLIST;
If there is no setAttribute about PDO::ATTR_STATEMENT_CLASS, The MySQL connection is disconnected in working order.
$pdo = new PDO($dsn, $dbinfo['userid'], $dbinfo['password'], $options);
//$pdo->setAttribute (PDO::ATTR_STATEMENT_CLASS, array ('PDOStatement2', array($pdo)));
$pdo = null;
I have no idea about it wheather is this a bug or has another solutions.
Finally, I found the solution.
$pdo object on following statement will be duplicated
$pdo->setAttribute (PDO::ATTR_STATEMENT_CLASS, array ('PDOStatement2', array($pdo)));
Use &$pdo instead of $pdo.
$pdo->setAttribute (PDO::ATTR_STATEMENT_CLASS, array ('PDOStatement2', array(&$pdo)));

how to handle invalid database in zend framework 1

I am using Zend framework 1.12.I have one ajax based UI that sends an user account information(stored in master database) to controller. Every user account has its related DB. But when I select an user that has no related db, controller sends application error. I want some message to be send to UI.
private function _initDB()
{
global $databaseip, $username, $password;
try {
// I can access this scope with valid db name
// for multi user && multi db
$this->_pdo = new Zend_Db_Adapter_Pdo_Mysql(
array(
'host' => $databaseip,
'username' => $username,
'password' => $password,
'dbname' => $this->_dbname,
)
);
} catch (Zend_Exception $e) {
// I want some message to be passed to UI.
// can't access this scope with invalid dbname
// as users list stores in master database
// may be db-admin deleted database of that user
// but forgot to delete that user from master-users database
}
}
Thanks in advance:

Yii2 Create Database Connection

I want to create a database connection programmatically without using the config file. I have a form wherein the user enters the database details like the hostname, username, password and the database name. On the basis of these details a new test connection is made and if it passes it should generate the necessary files.
This is what I have tried:
// Create Test DB Connection
Yii::$app->set('id', [
'class' => 'yii\db\Connection',
'dsn' => $dsn,
'username' => $form->username,
'password' => $form->password,
'charset' => 'utf8'
]);
try {
// Check DB Connection
if (Yii::$app->db->getIsActive()) {
// Write Config
$config['components']['db']['class'] = 'yii\db\Connection';
$config['components']['db']['dsn'] = $dsn;
$config['components']['db']['username'] = $username;
$config['components']['db']['password'] = $password;
$config['components']['db']['charset'] = 'utf8';
Configuration::setConfig($config);
$success = TRUE;
return $this->redirect(['init']);
}else{
$errorMsg = 'Incorrect Configurations';
}
} catch (Exception $e) {
$errorMsg = $e->getMessage();
}
I have tested this again and again and even with correct configurations it is giving an error.
All the help is appreciated. Thanks in advance!
You can define a new connection this way:
$db = new yii\db\Connection([
'dsn' => 'mysql:host=localhost;dbname=example',
'username' => 'root',
'password' => '',
'charset' => 'utf8',
]);
$db->open();
After the DB connection is established, one can execute SQL statements like the following eg:
$command = $db->createCommand('SELECT * FROM post');
$posts = $command->queryAll();
// or
$command = $connection->createCommand('UPDATE post SET status=1');
$command->execute();
you can look at this for doc and guide
http://www.yiiframework.com/doc-2.0/guide-db-dao.html
http://www.yiiframework.com/doc-2.0/yii-db-connection.html
I realised my mistake. When using Yii::$app->set() for setting up the db connection, you have to even manually open the connection using Yii::$app->db->open(). Yii doesn't open up the connection for you.

how to connect to the database in openshift application

I did as following
MySQL 5.1 database added. Please make note of these credentials:
Root User: xxxxxxx
Root Password: xxxxxxx
Database Name: php
Connection URL: mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/
You can manage your new MySQL database by also embedding phpmyadmin-3.4.
The phpmyadmin username and password will be the same as the MySQL credentials above.
phpMyAdmin 3.4 added. Please make note of these MySQL credentials again:
Root User: xxxxxxx
Root Password: xxxxxxx
URL: https://php-doers.rhcloud.com/phpmyadmin/
and i try to connect db using bellow PDO code .but it does not work
$dbh = new PDO('mysql:host=mysql://$OPENSHIFT_MYSQL_DB_HOST:$OPENSHIFT_MYSQL_DB_PORT/;dbname=php', "xxxxxx, "xxxxxx");
I don't know what is the connection URL mean ?
There is an error in your connection string plus $OPENSHIFT_MYSQL_DB_* are env variables and need to be fetched via getenv php function.
So try the following:
define('DB_HOST', getenv('OPENSHIFT_MYSQL_DB_HOST'));
define('DB_PORT',getenv('OPENSHIFT_MYSQL_DB_PORT'));
define('DB_USER',getenv('OPENSHIFT_MYSQL_DB_USERNAME'));
define('DB_PASS',getenv('OPENSHIFT_MYSQL_DB_PASSWORD'));
define('DB_NAME',getenv('OPENSHIFT_GEAR_NAME'));
$dsn = 'mysql:dbname='.DB_NAME.';host='.DB_HOST.';port='.DB_PORT;
$dbh = new PDO($dsn, DB_USER, DB_PASS);
Open php myadmin from webconsole , and on left corner you will get some Ip
That is like xx.xx.xx.xx:3306 , so your hostname is xx.xx.xx.xx
Ip address wil work , I have tried and worked for me
below code worked for me ,try this it might help you
var mysql = require('mysql');
var mysql = require('mysql');
exports.pool = mysql.createPool({
host: process.env.OPENSHIFT_MYSQL_DB_HOST || 'localhost',
port: process.env.OPENSHIFT_MYSQL_DB_PORT || '3306',
user: process.env.OPENSHIFT_MYSQL_DB_USERNAME || 'root',
password: process.env.OPENSHIFT_MYSQL_DB_PASSWORD || '',
database: 'chichat' || 'chichat',
multipleStatements : true,
charset: 'utf8'
});
I would like to add some information to future reference.
Today I am trying to deploy a Drupal installation to Open Shift (OS) and tried to configure MySql.
I connected to OS via SSH (rhc ssh ), went to app-root/data/sites/default. Following cat settings.php to see how OS configure database.
Here it is:
// When run from Drush, only $_ENV is available. Might be a bug
if (array_key_exists('OPENSHIFT_APP_NAME', $_SERVER)) {
$src = $_SERVER;
} else {
$src = $_ENV;
}
$databases = array (
'default' =>
array (
'default' =>
array (
'database' => $src['OPENSHIFT_APP_NAME'],
'username' => $src['OPENSHIFT_MYSQL_DB_USERNAME'],
'password' => $src['OPENSHIFT_MYSQL_DB_PASSWORD'],
'host' => $src['OPENSHIFT_MYSQL_DB_HOST'],
'port' => $src['OPENSHIFT_MYSQL_DB_PORT'],
'driver' => 'mysql',
'prefix' => '',
),
),
);
$conf['file_private_path'] = $src['OPENSHIFT_DATA_DIR'] . 'private/';
$conf['file_temporary_path'] = $src['OPENSHIFT_TMP_DIR'] . 'drupal/';
So I created a php folder into git repository (see OS documentation about Drupal), copied a clean Drupal install to it and paste code above to settings.php.
After pushing to git, restarted OS app and worked!

Categories