Combining connect data into one file - php

I have a PHP file that I use to include when I connect to my db. It looks something like this:
<?php
$mysqlhst = "localhost";
$database = "mydb1";
$username = "my_usr";
$password = "mypas2db1";
try {
$db = new PDO("mysql:host=$mysqlhst;dbname=$database;charset=UTF8", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>
I also have a second database that I frequently access at the same time as the first one. Can I combine both connections like this or is there a better way of doing it?
<?php
$mysqlhst = "localhost";
$database = "mydb1";
$username = "my_usr1";
$password = "mypas2db1";
try {
$db = new PDO("mysql:host=$mysqlhst;dbname=$database;charset=UTF8", $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$database = "mydb2";
$username = "my_usr2";
$password = "mypas2db2";
try {
$db2 = new PDO("mysql:host=$mysqlhst;dbname=$database;charset=UTF8", $username, $password);
$db2->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>

Assuming you're not using Classes, you could DRY (Do-not Repeat Yourself) up your code a little like the following. This allows for extending into even further databases/users/servers in the future if required:
<?php
$connections = [
'db1' => [
'host' = 'localhost';
'database' = 'mydb1';
'username' = 'my_usr1';
'password' = 'mypas2db1';
],
'db2' => [
'host' = 'localhost';
'database' = 'mydb2';
'username' = 'my_usr2';
'password' = 'mypas2db2';
],
];
function getDatabaseConnection($connectionName = 'db1'): ?PDO
{
global $connections;
if (empty($connections[$connectionName]) {
// Throw an exception because this connection doesn't exist.
throw new \Exception(
"Connection: {$connectionName} not specified."
);
}
$data = $connections[$connectionName];
$dbHost = $data['host'] ?: 'localhost';
$dbUsername = $data['username'] ?: '';
$dbPassword = $data['password'] ?: '';
$dbName = $data['database'] ?: '';
if (!$dbUsername || !$dbName) {
// We don't have a username or database to connect to. Fail.
throw new \Exception(
'No valid database name or user provided.'
);
}
$db = new PDO(
"mysql:host={$dbHost};dbname={$dbName};charset=UTF8",
$dbUsername,
$dbPassword
);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $db;
}
// We don't need to specify a connection because we want the default, db1.
$db1 = getDatabaseConnection();
// Specify we want a connection to db2.
$db2 = getDatabaseConnection('db2');

Related

Setting a mysql table in a variable

Okay so I'm using this code to store tables in a variable:
<?php
$host = "localhost";
$user = "x";
$password = "x";
try {
$account = new PDO("mysql:host=$host;dbname=account", $user, $password);
} catch(PDOException $e) {
die('connection cant be made');
}
try {
$player = new PDO("mysql:host=$host;dbname=player", $user, $password);
} catch(PDOException $e) {
die('connection cant be made');
}
and everything I do I get "connection can't be made". So I found another code and I switched to it and everything works.
<?php
$host = "localhost"; // Ip-ul de la server
$user= "xx"; // User-ul de conectare la database
$password = "xx"; // Parola de conectare la database
mysql_connect($server, $user, $password) or die(mysql_error());
mysql_select_db('account');
mysql_set_charset('utf8');
?>
but now I have no db assigned to $account and $player and I can't use my site properly. Ideas?
In $e you have reason why you can't connect to database. Catch exception and do nothing with it...
<?php
define('__DEBUG', true);
try {
$account = new PDO("mysql:host=$host;dbname=account", $user, $password);
} catch(PDOException $e) {
if(__DEBUG) {
print $e->getMessage();
}
die('connection cant be made');
}
for use 2 connections in (not so^) old way style:
$con1 = mysqli_connect();
$con2 = mysqli_connect();
mysqli_query('query', $con1);
mysqli_query('query', $con2);
^ use mysqli_ instead mysql_

how can i transform mysql to PDO connection?

How can I transform the mysql code bellow into pdo connection ? because i have some networking issues.
$gaSql['user'] = "root";
$gaSql['password'] = "";
$gaSql['db'] = "test";
$gaSql['server'] = "localhost";
// DB connection
function dbinit(&$gaSql) {
// if error rezults 500
function fatal_error($sErrorMessage = '') {
header($_SERVER['SERVER_PROTOCOL'] .' 500 Internal Server Error');
die($sErrorMessage);
}
// connecting to mysql
if ( !$gaSql['link'] = #mysql_connect($gaSql['server'], $gaSql['user'], $gaSql['password']) ) {
fatal_error('Could not open connection to server');
}
// select the DB
if ( !mysql_select_db($gaSql['db'], $gaSql['link']) ) {
fatal_error('Could not select database');
}
}
Proper PDO db connection
<?php
$host = '127.0.0.1';
$db = 'your db';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$dbh = new PDO($dsn, $user, $pass, $options);
?>
Reference : https://phpdelusions.net/pdo
I use this in all my pdo connections it works perfectly
You could try something like this:
try {
$pdo = new PDO('mysql:host=' . $gaSql['server'] . ';dbname=' . $gaSql['db'], $gaSql['user'], $gaSql['password']);
} catch (PDOException $ex) {
if ($ex->getCode() == 1049) {
throw new Exception('Unknown Database: ' . $gaSql['db']);
} elseif ($ex->getCode() == 1045) {
throw new Exception('Wrong credentials for user: ' . $gaSql['user']);
}
}
Hope, this helps ;-)

Failing testing database connection in php

I've set up a database using MAMP.
When I try the following test, I only receive a blank page. Fairly new to this, and I've tried different suggestions found on the web with no luck.
Tried using both port and socket.
<?php
$user = 'root';
$password = 'root';
$db = 'test';
$host = 'localhost';
$port = 3306;
$socket = "/Applications/MAMP/tmp/mysql/mysql.sock";
$link = mysql_connect(
"$host:$socket",
$user,
$password
);
$db_selected = mysql_select_db(
$db,
$link
);
if (!$link){
echo "ERROR";
}
else {
echo "Success";
}
mysql_close($link);
?>
<?php
$servername = "localhost";
$username = "root";
$password = "root";
try {
$conn = new PDO("mysql:host=$servername;test", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>
Would you like to try PDO ?!
<?php
$dsn = "mysql:host=localhost;dbname=databasenamehere";
$user = 'root';
$pass = '';
$option = array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try {
$connect = new PDO($dsn, $user, $pass,$option);
$connect->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $r) {
echo 'Failed' . $r->getMessage();
}

PDO object cant acess inside function

In my project i had a file called connection.inc.php which is managing the data base connection using PDO.
include/connection.inc.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "college";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
?>
i included this file in various other pages and it worked perfectly for me. But when i tried to acess the $conn object inside a function it not working. How to fix this problem.
You could do global $conn on top of your functions, but don't. I suggest wrapping it in a singleton instead.
<?php
class Connection {
private static $conn = null;
private $connection = null;
private function __construct() {
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "college";
try {
$this->connection = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Error: " . $e->getMessage(); // Should look into a different error handling mechanism
}
}
public static function getConnection() {
if (self::$conn === null) {
self::$conn = new self();
}
return self::$conn->connection;
}
}
You can access it via Connection::getConnection()
This also has the advantage of not initializing the connection if the current request doesn't need to use it.
Honestly the simplest method is to set the connection inside of a function then you can use that function in other functions.
Example:
error_reporting(E_ALL);
ini_set('display_errors', 1);
function dataQuery($query, $params) {
$queryType = explode(' ', $query);
// establish database connection
try {
$dbh = new PDO('mysql:host='.DB_HOSTNAME.';dbname='.DB_DATABASE, DB_USERNAME, DB_PASSWORD);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e) {
echo $e->getMessage();
$errorCode = $e->getCode();
}
// run query
try {
$queryResults = $dbh->prepare($query);
$queryResults->execute($params);
if($queryResults != null && 'SELECT' == $queryType[0]) {
$results = $queryResults->fetchAll(PDO::FETCH_ASSOC);
return $results;
}
$queryResults = null; // first of the two steps to properly close
$dbh = null; // second step to close the connection
}
catch(PDOException $e) {
$errorMsg = $e->getMessage();
echo $errorMsg;
}
}
How To Use In Another Function:
function doSomething() {
$query = 'SELECT * FROM `table`';
$params = array();
$results = dataQuery($query,$params);
return $results[0]['something'];
}
You need to update your file as
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "college";
//// define global variable
global $connection
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
/// assign the global variable value
$connection = $conn ;
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Error: " . $e->getMessage();
}
?>
Now you can call it any of your function like
function mytest(){
global $connection;
}
The best practice would be to pass the $conn as argument to the function.
But if you really need the function to have no arguments but still use a global variable, then adding this line in your function before using the variable should do the trick:
global $conn; // I want to use the global variable called $conn

php mysql connection get error message

this is my first php code , i am trying to connect to a database with user name = "root" and password = "root"
i have a connection file called dbConnection.php
as following :
<?php
echo "in connection file";
$hostname = "localhost";
$username = "root";
$password = "root";
$db = "ledDB";
echo "<br> db-connection : vars definde ";
//connection to the database
$conn = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
echo "db-connection : initilize connection ";
mysql_select_db($db);
echo "db-connection : connection done";
// Check connection
echo "Connected successfully";
?>
and i call it in a file called what.php :
<?php
echo "Hello";
include "dbConnection.php";
echo "ohhhh";
?>
this returns status code 500 which is internal server error
but i want to know what is the error to fix it how can i get the error message ?
i tried
$conn = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
but it is not returning any thing.
can any one help me please ?
if you are having password on localhost then use password otherwise leave it blank
$con = mysqli_connect("localhost","root","yourpassword","yourdb");
You mysqli_connect() method.
<?php
echo "in connection file";
$hostname = "localhost";
$username = "root";
$password = "root";
$db = "ledDB";
echo "<br> db-connection : vars definde ";
//connection to the database
$conn = mysqli_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
echo "db-connection : initilize connection ";
mysqli_select_db($conn,$db);
echo "db-connection : connection done";
// Check connection
echo "Connected successfully";
?>
First Thing is to Change your connection method to mysqli or my personal favorite PDO.
PDO Example:
class db extends pdo{
//Website Variables
public $sitedb = '';
public $siteconfig;
public $sitesettings = array(
'host' => 'localhost',
'database' => 'yourdb',
'username' => 'youruser',
'password' => 'yourpass',
);
public function __construct(){
$this->sitedb = new PDO(
"mysql:host={$this->sitesettings['host']};" .
"dbname={$this->sitesettings['database']};" .
"charset=utf8",
"{$this->sitesettings['username']}",
"{$this->sitesettings['password']}"
);
$this->sitedb->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
}
}
$db = new db();
Then you can extend your PDO class to new classes after including the db.php page.
Example Select:
class yourclass extends db {
public function SelectUsers() {
global $db;
$query = <<<SQL
SELECT email
FROM users
WHERE active = :active
SQL;
$resource = $db->sitedb->prepare( $query );
$resource->execute( array (
':active' => 1,
));
$count = $resource->rowCount();
foreach($resource as $user){
$this->email = $user['email'];
}
}
}
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "mydb";
// Create connection
$conn = mysqli_connect($servername, $username, $password);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
// make the current db
$db_selected = mysqli_select_db ( $conn , $dbname );
if (!$db_selected) {
die ('Can\'t connect to Database : ' . mysql_error());
}
?>

Categories