I've got an php script that creates a Connection to my MYSQL Database.
<?php
$connection = new mysqli('127.0.0.1', 'root', 'password', 'table');
if($connection){
echo "Verbindung Erfolgreich";
}
?>
And than I've got other PHP Scripts for my Application. My Question is now, does it everytime opens a new DB Connection for each time i call require_once("dbconnect.php") ? Or does someone know how I can let the Connection open until i close it?
If you use require_once("dbconnect.php") every time the script is executed a connection will open. If you do not want this you can wrap the connection in a function and use that function if you need a database connection.
dbconnect.php:
function db_connect() {
$connection = new mysqli('127.0.0.1', 'root', 'password', 'table');
if ($connection->connect_error) {
die('Connect Error ('.$connection->connect_errno.')'.$connection->connect_error);
}
return $connection;
}
someotherfile.php:
require_once("dbconnect.php")
$dbconnection = db_connect();
... do something with the connection...
$dbconnection->close();; // close connection
Related
my question is about connect with mysql database in other server by php ??
Server A is rec.misuratau.edu.ly, Server B is alrand.ly , I need to code pls.
I am not sure if I understand well. You are asking how to make a connection to mysql database on two different server?
You can do it like this:
First create databases on server, create user define password and grant access to the user.
Create two separate file: First is Config.php
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_HOST', 'http://rec.misuratau.edu.ly'); // replace with servername
define('DB_NAME', 'db');
define('USER_CREATED_SUCCESSFULLY', 0);
define('USER_CREATE_FAILED', 1);
define('USER_ALREADY_EXISTED', 2);
Second is DbConnect.php
class DbConnect {
private $conn;
function __construct() {
}
/**
* Establishing database connection
* #return database connection handler
*/
function connect() {
include_once dirname(__FILE__) . '/Config.php';
// Connecting to mysql database
$this->conn = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
// Check for database connection error
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_set_charset($this->conn,"utf8");
// returing connection resource
return $this->conn;
}
}
LAter you just call the method before sql statements.
Please check the link below as well:
https://www.w3schools.com/php/php_mysql_connect.asp
I have been developing a website recently, and I came across an error. When I tried to do print_r(error_get_last()); It output some text about mysql not being supported anymore, and to use MySQLi. I was all for it. When I edited my database class to support MySQLi, it exits every time it tries to connect. I have put echo 'hi<br />'; before and after the mysqli function, and a or trigger_error("Error: " . print_r(error_get_last())); at the end of it, but all it outputs is hi, and nothing else. My database is created in phpMyAdmin, and has all the correct permissions, but it just cannot connect. This is my connection code:
echo 'hi<br />';
$this->db = mysqli($host, $dbuser, $dbpass, $dbname) or trigger_error("Error: " . print_r(error_get_last()));
echo 'hi<br />';
$this->connect_start = microtime(true);
if ($this->db->connect_errno > 0) die ($this->debug(true));
It is in the constructor of a class that looks like this:
function db($host, $dbname, $dbpass, $dbuser)
and it is called like this:
$db = new db($host, $dbname, $dbpass, $dbuser);
Change this:
$this->db = mysqli()
to
$this->db = new mysqli()
mysqli is not a function, it's a class. If you had error reporting on you'd get a message like this:
PHP Fatal error: Call to undefined function mysqli()
That's the reason why the rest of your code isn't executed, the execution stops right there.
Also note that new mysqli() will never return false, so your or ... part becomes useless. If you want to check for connection errors you have to check $this->db->connect_error after the connection attempt.
There is something, as a newbie, that a I want to understand about About database connections.
I am starting off from a tutorial on PHP which has this structure:
Connect.php:
<?php
$username = "dbusername";
$password = "dbpassword";
$host = "localhost";
$dbname = "dbname";
$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
header('Content-Type: text/html; charset=utf-8');
session_start();
?>
Login.php:
<?php
require("connect.php");
// some code not important for this question,
//that handles login with a session…
?>
various_file_in_the_login_system.php:
<?php
require("connect.php");
// some code that checks if user is logged in with session_ …
// some code that does need the database connection to work
?>
All other files also contain that require("connect.php"); line. It works, but I just don’t know what these connection request to the server – I may not be using the right vocabulary -- end up doing to the server. They are superfluous if the connection is not timed out, are they not?
I found a post which talked about doing a singleton for PDO, and a post which makes me feel like never using persistent connections in my life.
Does this design causes excessive connection churning?
Perhaps servers can handle very many request for connection per second, perhaps a server has its own internal persistent connection mode, or implements connection pooling…
Or the PDO object handle the problem of asking connection too often for no reason…
PDO + Singleton : Why using it?
What are the disadvantages of using persistent connection in PDO
This is what I can recommend for your database connection:
Make a class for the connection:
class Database{
private static $link = null ;
public static function getConnection ( ) {
if (self :: $link) {
return self :: $link;
}
$dsn = "mysql:dbname=social_network;host=localhost";
$user = "user";
$password = "pass";
self :: $link = new PDO($dsn, $user, $password);
return self :: $link;
}
}
Then you can get the connection like this:
Database::getConnection();
The Singleton Pattern is hard to scale - However, I think it will probably be fine for your needs. It takes a lot of load off your database.
I don't think you will be able to avoid the multiple includes.
There is a php.ini setting for prepending a file to every script -> http://www.php.net/manual/en/ini.core.php#ini.auto-prepend-file
How about you change to
require_once('connect.php');
in all locations?
Also you should probably remove session_start() and HTTP header logic from a section of code that has to do with establishing a DB connection. This simply does not make sense there.
To open a DB connection, I currently use this class method :
function openDB() {
// 1. Create a database connection
$conn = mysqli_connect("x" , "x", "x","x");
if (!$conn)
{
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
However, I want to instead use my config file
require("assets/configs/db_config.php");
Obviously this file contains the DB connection information.
How can I do away with
$conn = mysqli_connect("x" , "x", "x","x");
And simply make $conn and make it use DB_Config.php instead?
For you config file return an array of the values you need
return array("host"=>"example.com", "dbname"=>"mydb", "username"=>"dbuser", "password"=>"secret");
Then in your openDb function do this.
function openDB() {
// 1. Create a database connection
$config = include("/path/to/config.php");
$conn = mysqli_connect($config["host"] , $config["username"], $config["password"],$config["dbname"]);
if (!$conn)
{
$this->error_msg = "connection error could not connect to the database:! ";
return false;
}
$this->conn = $conn;
return true;
}
Change
function openDB()
to
function openDB($server, $user, $pass, $dbName)
and pass those variables to mysqli_connect
and pass data from included file.I suppose, you have them in some sort of constants or defines.
Also, it would be good idea to haveDB connection somewhere globally.
Newer to creating php functions and mysql. I have function to connect to a database db_conect_nm(). This is in file db_fns.php, and contains the user and password to connect to my db. I created this to have a more secure db connection. I had it in a directory outside of public_html, and got error PHP Warning: mysqli::mysqli() [<a href='mysqli.mysqli'>mysqli.mysqli</a>]: (28000/1045): Access denied for user 'negoti7'#'localhost' (using password: NO) ...
Looking for solutions, I saw comments which indicated that perhaps this db user did not have permission from root, so I put it in a directory in public_html, same directory as program where it is being called. I still get the same error.
I have tested the connection without being a function, and it works. What is wrong, and why is this not working as a function? I really want to put this somewhere other than in the code directly and make it more secure.
db_fns.php content
<?php
//Database server
$host= 'localhost';
$nm_name= 'myname_databasename'; //sanitized data
$nm_user= 'myname_dbusername';
$nm_pword= 'password';
// db connect to nm database
function db_connect_nm()
{
$nm_connect = new mysqli($host, $nm_user, $nm_pword, $nm_name);
if (!$nm_connect)
throw new Exception('Could not connect to NM database currently');
else
return $nm_connect;
}
?>
I call it from nm_functions.php, db_fns.php is included there.
nm_functions.php
<?php require_once('sanitizedpathto/db_fns.php');
......some code
$conn_nm = db_connect_nm();
$result_sub = $conn_nm->query("select * from subscribers where uname='$username'");
.... more code
?>
Any ideas?
Thanks
Could it be the scope of the variables? Have you tried defining the variables inside the function to test?
Like this:
<?php
// db connect to nm database
function db_connect_nm()
{
//Database server
$host= 'localhost';
$nm_name= 'myname_databasename'; //sanitized data
$nm_user= 'myname_dbusername';
$nm_pword= 'password';
$nm_connect = new mysqli($host, $nm_user, $nm_pword, $nm_name);
if (!$nm_connect)
throw new Exception('Could not connect to NM database currently');
else
return $nm_connect;
}
?>
You are :
first, declaring some variables, outside of any functions
then, trying to use those variables from inside a function.
Variables declared outside of a function are not, by default, visible from inside that function.
About that, you should read the Variable scope section of the manual.
Two possible solutions :
Use the global keyword, to import those variables into your function -- making them visible
Or define constants, instead of variables -- which makes sense, for configuration values.
In the first case, your function would look like this :
// db connect to nm database
function db_connect_nm()
{
// Make these outside variables visible from inside the function
global $host, $nm_user, $nm_pword, $nm_name;
$nm_connect = new mysqli($host, $nm_user, $nm_pword, $nm_name);
if (!$nm_connect)
throw new Exception('Could not connect to NM database currently');
else
return $nm_connect;
}
And, in the second case, you'd first define the constants :
define('DB_HOST', 'localhost');
define('DB_DBNAME', 'myname_databasename');
define('DB_USER', 'myname_dbusername');
define('DB_PASSWORD', 'password');
And, then, use those constants :
// db connect to nm database
function db_connect_nm()
{
$nm_connect = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DBNAME);
if (!$nm_connect)
throw new Exception('Could not connect to NM database currently');
else
return $nm_connect;
}
This second solution is probably more clean than the first one ;-)
Your connection variables are not scoped inside the connection function. You either need to pass them as parameters to the function (preferable) or use the global keyword inside to reference them:
function db_connect_nm($host, $nm_user, $nm_pword, $nm_name)
{
$nm_connect = new mysqli($host, $nm_user, $nm_pword, $nm_name);
//etc...
}
Alternate, not preferred:
function db_connect_nm()
{
global $host, $nm_user, $nm_pword, $nm_name;
$nm_connect = new mysqli($host, $nm_user, $nm_pword, $nm_name);
//etc...
}