Multiple database connection using php userdefined function - php

This is the code for config.php I am including this file in all php files:
<?php
$db_name = 'localhost';
$db_user = 'XXXXXX';
$db_pass = 'XXXXXXXXXX';
function db_connect1()
{
global $db_name, $db_user, $db_pass;
$conn = mysql_connect($db_name, $db_user, $db_pass);
mysql_select_db('test1', $conn) or die('Could not select database.');
return $conn;
}
db_connect1();
?>
Here i need to connect with another one database test2.

You can make multiple calls to mysql_connect(), but if the parameters are the same you need to pass true for another connection
<?php
$db_name = 'localhost';
$db_user = 'XXXXXX';
$db_pass = 'XXXXXXXXXX';
function db_connect1()
{
global $db_name, $db_user, $db_pass;
$conn1 = mysql_connect($db_name, $db_user, $db_pass);
$conn2 = mysql_connect($db_name, $db_user, $db_pass,true);
mysql_select_db('test1', $conn1) or die('Could not select database test1.');
mysql_select_db('test2', $conn2) or die('Could not select database test2.');
$conn = new stdClass();
$conn->conn1 = $conn1;
$conn->conn2 = $conn2;
return $conn;
}
$conn = db_connect1();
Then to query database test1, do this:
mysql_query('select * from tablename', $conn->conn1);
and for database test2:
mysql_query('select * from tablename', $conn->conn2);
?>

try this
$db_name = 'localhost';
$db_user = 'XXXXXX';
$db_pass = 'XXXXXXXXXX';
function db_connect1($dbname) {
global $db_name, $db_user, $db_pass;
$conn = mysql_connect($db_name, $db_user, $db_pass);
if($conn) {
mysql_select_db($dbname, $conn) or die('Could not select database.');
return $conn;
} else {
die("Error occurred while connect to the server.");
}
}
Every time you call the function and set argument.
echo db_connect1('test1');
echo db_connect1('test2');
Echo the function because you are using return keyword and checked that if it returns 1 its means your server connection is ok.

Related

linking my database to my server on xampp for the first time [duplicate]

I'm working on streamlining a bit our db helpers and utilities and I see that each of our functions such as for example findAllUsers(){....} or findCustomerById($id) {...} have their own connection details for example :
function findAllUsers() {
$srv = 'xx.xx.xx.xx';
$usr = 'username';
$pwd = 'password';
$db = 'database';
$port = 3306;
$con = new mysqli($srv, $usr, $pwd, $db, $port);
if ($con->connect_error) {
die("Connection to DB failed: " . $con->connect_error);
} else {
sql = "SELECT * FROM customers..."
.....
.....
}
}
and so on for each helper/function. SO I thought about using a function that returns the connection object such as :
function dbConnection ($env = null) {
$srv = 'xx.xx.xx.xx';
$usr = 'username';
$pwd = 'password';
$db = 'database';
$port = 3306;
$con = new mysqli($srv, $usr, $pwd, $db, $port);
if ($con->connect_error) {
return false;
} else {
return $con;
}
}
Then I could just do
function findAllUsers() {
$con = dbConnection();
if ($con === false) {
echo "db connection error";
} else {
$sql = "SELECT ....
...
}
Is there any advantages at using a function like this compared to a Class system such as $con = new dbConnection() ?
You should open the connection only once. Once you realize that you only need to open the connection once, your function dbConnection becomes useless. You can instantiate the mysqli class at the start of your script and then pass it as an argument to all your functions/classes.
The connection is always the same three lines:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$con = new mysqli($srv, $usr, $pwd, $db, $port);
$con->set_charset('utf8mb4');
Then simply pass it as an argument and do not perform any more checks with if statements.
function findAllUsers(\mysqli $con) {
$sql = "SELECT ....";
$stmt = $con->prepare($sql);
/* ... */
}
It looks like your code was some sort of spaghetti code. I would therefore strongly recommend to rewrite it and use OOP with PSR-4.

Issue connecting to MySQL with PHP

I am trying to connect to MySQL with PHP but i keep getting the following error: "mysqli::__construct(): (HY000/2002): No such file or directory in /Users/markjonathas/Documents/bar/database_connection.php on line 9" I have MAMP downloaded and I am using PHP 7.3.1 and MySQL version 8.0.16.
I have tried to to download Sequel Pro but when I try to connect to the database I get the following error: "MySQL said: Authentication plugin 'caching_sha2_password' cannot be loaded: dlopen(/usr/local/lib/plugin/caching_sha2_password.so, 2): image not found"
//code for database_connection.php:
<?php
$servername = "127.0.0.1:3306";
$username = "root";
$password = "-------";
$database = "barDB";
function db_connect() {
$connection = new mysqli($servername, $username, $password,
$database);
return $connection;
}
function db_disconenct() {
if(isset($connection)) {
$connection->close();
}
}
?>
//code for connecting to database_connection.php:
<?php
require_once("database_connection.php");
$db = db_connect();
?>
Create a file and name it as init.php or whatever you want.
<?php
$db_name = "barDB";
$mysql_user = "root";
$mysql_pass = "-------";
$server_name = "127.0.0.1:3306";
$con = mysqli_connect($server_name, $mysql_user, $mysql_pass, $db_name);
if(!$con){
echo "Server Error";
}else{
}
?>
To access global variables, you have to declare them as global:
function db_connect() {
global $connection, $servername, $username, $password, $database; // <<<<<<<<
$connection = new mysqli($servername, $username, $password, $database);
return $connection;
}
function db_disconenct() {
global $connection; // <<<<<
if(isset($connection)) {
$connection->close();
}
}
Read PHP documentation for details.

php switching to server connection if localhost failed

I'm trying to write a script that connects to an online server if localhost connection failed or inaccessible. I have the script below that connects to a localhost database and if it's not accessible then reroute to a server connection. The script somehow fails to work and I just don't know why. Anyone has any suggestions?
<?php
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'admin';
$DB_CON_A = new PDO("mysql:host={$DB_HOST}", $DB_USER, $DB_PASS);
if(!$DB_CON_A) {
die($DB_CON_A);
$DB_HOST = 'www.xyz.com';
$DB_USER = 'admin';
$DB_PASS = '1235kasK';
$DB_NAME = 'admin';
}
try {
$DB_CON_A = new PDO("mysql:host={$DB_HOST}; dbname={$DB_NAME}", $DB_USER, $DB_PASS);
$DB_CON_A->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo $e->getMessage();
}
Here is my solution for those who's looking for one:
<?php
function ping($DB_HOST) {
exec(sprintf('ping -c 1 -W 5 %s', escapeshellarg($DB_HOST)), $res, $rval);
return $rval === 0;
}
$DB_HOST = 'www.xyz.com';
$connected = ping($DB_HOST);
if ($connected) {
$DB_HOST = 'www.xyz.com';
$DB_USER = 'user';
$DB_PASS = 'pass';
$DB_NAME = 'accounts';
} else {
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'accounts';
}
// Create database if not exists
$DB_CON_C = new PDO("mysql:host={$DB_HOST}", $DB_USER, $DB_PASS);
$DB_CON_C->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$DB_CON_C->query("CREATE DATABASE IF NOT EXISTS $DB_NAME");
$DB_CON_C->query("USE $DB_NAME");
try {
$DB_CON_C = new PDO("mysql:host={$DB_HOST}; dbname={$DB_NAME}", $DB_USER, $DB_PASS);
$DB_CON_C->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo $e->getMessage();
}
?>

Why isn't this php code allowing me to connect to my database?

I'm using a WAMP server and on it I created a database and a table. All the names are correct and the user has full access to everything. When I run the code, it prints out "Unable to select database". Thanks.
<?php
if(isset($_POST["Submit"])){
print_r ($_POST["nutrient"]);
}
session_start();
//establish connection
$server = "localhost";
$db_username = "root";
$db_password = "";
$database = "gainlife_cavin";
$table = "cavintable";
//connect PHP script to database
$connection = mysqli_connect($server, $db_username, $db_password, $database);
//select database to use
#mysql_select_db($database) or die( "Unable to select database");
//$query = "INSERT INTO $table VALUES("")"
//mysql_query($query)
mysql_close();
?>
<body>
</form>
Try something like the following.
<?php
//establish connection
$server = "localhost";
$db_username = "root";
$db_password = "";
$database = "gainlife_cavin";
$table = "cavintable";
//connect PHP script to database
$connection =mysqli_connect("$server","$db_username","$db_password","$database");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Your query here
mysqli_close($connection);
?>
I use simple code 1 line. here is my code that i'm using.
$conn = mysqli_connect($db_host, $db_user, $db_pass, $db_name);
// Evaluate the connection
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
}
You went from MySQLI to not using MySQLI in selecting the database as well as the rest of your code.
Try this. I have change mysqli_connect to mysql_connect and mysql_select_db variable.
//connect PHP script to database
$connection = mysql_connect($server, $db_username, $db_password, $database);
//select database to use
$select = mysql_select_db($connection) or die( "Unable to select database");

PHP: Database Connection Class - Won't Connect

I'm having trouble with my DatabaseConnection class. I cannot seem to get $dbUser or $dbName variables to work for this connection class. I currently have to manually put the values in with quotes. Is there something I am doing wrong?
class DatabaseConnection {
private $dbHost = "localhost";
private $dbUser = "root";
private $dbPass = "";
private $dbName = "test";
function __construct() {
$connection = mysql_connect($dbHost, "root", $dbPass)
or die("Could not connect to the database:<br />" . mysql_error());
mysql_select_db("test", $connection)
or die("Database error:<br />" . mysql_error());
}
}
If you have suggestions for improving my current class, by all means, let me know!
Since this is a class, you have to access your class variables using $this->dbHost, $this->dbUser, etc instead of $dbHost, $dbUser. Php requires that you use $this->variableName for class variables.
EDIT:
Here's your code with the mysql_connect variables changed to access your class variables
class DatabaseConnection {
private $dbHost = "localhost";
private $dbUser = "root";
private $dbPass = "";
private $dbName = "test";
function __construct() {
$connection = mysql_connect($this->dbHost, $this->dbUser, $this->dbPass)
or die("Could not connect to the database:<br />" . mysql_error());
mysql_select_db("test", $connection)
or die("Database error:<br />" . mysql_error());
}
}

Categories