Trying to global database connection in all functions in a .php file.
sql.php:
<?php
$servername = "XXXXX";
$username = "XXXXX";
$password = "XXXXX";
$dbname = "XXXXX";
$conn = new mysqli($servername, $username, $password, $dbname);
mysqli_set_charset($conn, "utf8");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
save.php
$conn = require_once('../path/to/sql.php');
function save()
{
global $conn;
$sql = "INSERT INTO `content` (title, text, cat)
VALUES ('".$_POST["title"]."', '".$_POST["text"]."', '".$_POST["category"]."')";
if ($conn->query($sql) === TRUE) {
show();
}
$conn->close();
}
well i want to get sql.php with require_once and then make it global then put this in save() function.
error is:
Fatal error: Call to a member function query() on a non-object in
/homepages/3/xxxxxxxx/htdocs/xxxxxxxx/xxxxxxxx/content.php on line 37
actually i don't know this way to make it global is correct or not, so please help me to choose best way to make a global database connection inside the functions.
Try
define('DATABASE_USERNAME', 'root');
define('DATABASE_PASSWORD', 'password');
define('DATABASE_HOST', 'localhost');
define('DATABASE_DBNAME', 'db');
$conn = new mysqli(DATABASE_HOST, DATABASE_USERNAME, DATABASE_PASSWORD, DATABASE_DBNAME);
Named constants are great for static global data.
Also you just need to do
require_once 'path/to/sql.php';
And not
$conn = require_once 'path/to/sql.php';
$conn is already being set in your require_once.
Related
I am trying to connect to my MySQL database using the following PHP code
<?php
require "credentials.php";
$conn = mysqli_connect($hostname, $username, $password, $databaseName);
if(mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
And I am getting the following output:
Failed to connect to MySQL: Connection refused
What could be the reasons that this is happening, and how can I fix it?
Thanks in advance.
from your code it seems that you are using undefined variables to connect to database. if you load them from external file, than use something like this in that file:
define("DBPASSWORD", "database_pass");
define("DBUSERNAME", "databaseusername");
define("DBNAME", "database");
define("DBHOST", "database_host");
and than use in file you shown us:
$conn = mysqli_connect(DBHOST, DBUSERNAME, DBPASSWORD, DBNAME);
OR another way, the way I can't recomend is using globals.
WARNING: I discourage using globals, when not needed.
Your credentials.php should look like that:
global $databaseName;
global $password;
global $username;
global $username;
$databaseName= "db_name";
$password= "db_password";
$username= "db_username";
$hostname= "db_host";
and than in other places, first you need to call the globals before usage.
require "credentials.php";
global $databaseName;
global $password;
global $username;
global $username;
$conn = mysqli_connect($hostname, $username, $password, $databaseName);
I am using my website database with php mysql_connect but my hosting provider is saying I need to use mysqli_connect.
When I edit connection file and update change method its not working with mysqli.
Currently using this code:
MSQL Method:
$con=mysql_connect("localhost","username","password");
mysql_select_db("databasename");
and for mysqli I am using this code but fail
MYSQLI Method:
$con = mysqli_connect("localhost","my_user","my_password","my_db");
Please help. Why is mysqli not working? Is my method wrong?
Try this:
Example (MySQLi Object-Oriented)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
` $dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
Example (MySQLi Procedural)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?>
This question already has answers here:
Connect to Multiple Databases using MySQLi
(3 answers)
Closed 6 years ago.
Ok so this is my code for the connection:
$servername = "host";
$username = "user";
$password = "pass";
$db1 = "db1";
$db2 = "db2";
// Create connection
$conn = new mysqli($servername, $username, $password, $db1); // $db1 is here as the default, is this ok?
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Then I run a function with this connection and it works for the $db1:
$sql = "SELECT etc etc;
$result = $conn->query($sql);
etc etc
The problem is when I try to change the db to $db2, I use this:
$conn->select_db($db2);
And now it only returns the value of the 2nd Database ($db2), and the one from $db1 doesn't show up on the page anymore, it doesn't show any value.
Thanks for Reading.
You have use two different connections while connecting different databases:
Database One Connection:
$conn = new mysqli($servername, $username, $password, $db1);
$sql = "SELECT etc etc;
$result = $conn->query($sql);
Database Two Connection:
$conn1 = new mysqli($servername, $username, $password, $db2);
$sql = "SELECT etc etc;
$result = $conn1->query($sql);
The Problem is that you have already assigned the conn to DB1 and hence if you run by selecting the DB2 it will be displaying error or no results will be produced. Hence while selecting multi databases you can use different connection variables.
the one from $db1 doesn't show up on the page anymore, it doesn't show any value.
what about making it $conn->select_db($db1); back?
Create two config files
db1.php
$servername = "host1";
$username = "user1";
$password = "pass1";
$db = "db1";
db2.php
$servername = "host2";
$username = "user2";
$password = "pass2";
$db = "db2";
//connection to db1
include("db1.php");
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//db1 codes
--------------------
//connection to db2
include("db2.php");
$conn = new mysqli($servername, $username, $password, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//db2 codes
I am using Cpanel to develop my application. It gives the error
Fatal error: Call to a member function set_charset() on a non-object in /home/restaur /public_html/restaurant/includes/connect_database.php on line 3
when I access to "www.yyyyy.com/filename/"
And here is my connect_database script
<?php
include($_SERVER['DOCUMENT_ROOT'].'/YOUR_FOLDER/variables/variables.php');
$connect->set_charset('utf8');
?>
my close_database script
<?php
include($_SERVER['DOCUMENT_ROOT'].'/YOUR_FOLDER/variables/variables.php');
$connect->close();
?>
my variable script
<?php
// database configuration
$host ="db_host_name";
$user ="db_username";
$pass ="db_pasword";
$database = "database_name";
$connect = new mysqli($host, $user, $pass,$database) or die("Error : ".mysql_error());?>
it should be like
$host ="db_host_name";
$user ="db_username";
$pass ="db_pasword";
$database = "database_name";
// variables.php
$connect = new mysqli($host, $user, $pass, $database);
/* check connection */
if ($connect->connect_errno) {
printf("Connect failed: %s\n", $connect->connect_error);
exit();
}
Now in connect_database.php
// Make sure your included path is correct
include($_SERVER['DOCUMENT_ROOT'].'/YOUR_FOLDER/variables/variables.php');
global $connect;
$connect->set_charset('utf8');
this will help you to know more in depth global
I was having this exact issue, i was having encoding problems but adding
$connect->set_charset('utf8');
(my variable was actually $conn->set_charset('utf8');) just after
$conn = new mysqli($servername, $username, $password, $dbname);
and it worked beautifully.
I'm having a problem with a function that connects me to the database using mysqli. What I'm aiming to have is to just type getConnected(); where I need the connection.
This is the code:
function getConnected()
{
$host = 'localhost';
$user = 'logintest';
$pass = 'logintest';
$db = 'vibo';
$mysqli = new mysqli($host, $user, $pass, $db);
if ($mysqli->connect_error) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
}
This is the error I get when I try to use $mysqli after calling getConnected():
Notice: Undefined variable: mysqli in C:\xampp\htdocs\xampp\loginsystem\index.php on line 19
As some users have suggested (and is the best way), return the mysqli instance
function getConnected($host,$user,$pass,$db) {
$mysqli = new mysqli($host, $user, $pass, $db);
if($mysqli->connect_error)
die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());
return $mysqli;
}
Example:
$mysqli = getConnected('localhost','user','password','database');
You don't need to create such function. The connection to mysqli is only 3 lines of code when done properly. Definition and execution of such function would add twice as much.
Remember to always follow the three steps when opening a connection:
Enable mysqli error reporting.
Create instance of mysqli class.
Set the proper charset. Recommended one is utf8mb4
If you would like to have these 3 lines wrapped in a function you could do something like this:
function getConnected(): \mysqli {
$host = 'localhost';
$user = 'logintest';
$pass = 'logintest';
$db = 'vibo';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli($host, $user, $pass, $db);
$mysqli->set_charset('utf8mb4');
// return the instance of mysqli class
return $mysqli;
}
However, hardcoding the values does not make much sense. The values should be coming either from environment variables (e.g. read using getenv() function) or from config file. For example:
function getConnected(): \mysqli {
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli(getenv('DB_HOST'), getenv('DB_USER'), getenv('DB_PASS'), getenv('DB_NAME'));
$mysqli->set_charset('utf8mb4');
// return the instance of mysqli class
return $mysqli;
}