This question already has answers here:
How to pass database connection instance between PHP files without redeclaring it
(3 answers)
How to use mysqli query using a separate connection.php file? [closed]
(2 answers)
Closed 3 years ago.
I am working on a project in php. where I have multiple files having data connection.And on the start of every file I write this code.
$servername = "localhost";
$abcusername = "root";
$abcpassword = "password";
$dbName = "db";
When I have to change password , I edit every file and change password that is very hassle process for me.
Can someone help me that how to to store server information in one file and give the link in all other files.
Create db.php file and place
$servername = "localhost";
$abcusername = "root";
$abcpassword = "password";
$dbName = "db";
$con = mysqli_connect($servername, $abcusername, $abcpassword, $dbName) or trigger_error("Unable to connect to the database");
and just use
include 'db.php';
in all of your files and use $con for posting your data to server eg:
mysqli_query($con,"your sql command");
You can simulate a rudimentary environment file by simply having an array with various information.
Lets assume we have a file called env.php:
$connections = [
'connection_1' => [
'driver' => 'mysql',
'username' => 'some username',
'password' => 'some password',
'servername' => 'some servername',
'db_name' => 'some db_name',
'port' => 123456,
],
'connection_2' => [
// ....
],
'connection_2' => [
// ....
]
];
After which you can require_once the file in various places.
With that said I recommend you take a look on how different frameworks handle environmental variables(symfony example here).
I don't expect you to implement the symfony example but it would give you a good idea on how to implement your own.
Related
This question already has an answer here:
Can't connect to GoDaddy mysqli database via PHP script
(1 answer)
Closed 2 years ago.
I am trying to connect a database to a website. I am using GoDaddy and I am finding it difficult to input the following things in php.
$host = "Where do I find this? Is this a number? Do I put the IP Address: Port Number?";
$dbusername = "Does it contain quotes?" Or is it just the username?;
$dbpassword = "Does it contain quotes?" Or is it just the password;
$dbname = "Does it contain quotes?" Or is it just the database name;
// Create connection
$conn = new mysqli ($host, $dbusername, $dbpassword, $dbname);
I am assuming the port number is right next to the localhost.
$host => Specifies a hostname or an IP address(For example: localhost).
$username => Specifies the MySQL username(For example: my_user).
$password => Specifies the MySQL password(For example: my_password ).
$dbname : => Specifies the default database to be used(For example: my_db).
All these contain a name with quotes on them.
For example:
$mysqli = new mysqli("localhost","my_user","my_password","my_db");
This question already has answers here:
Connect to SQL Server through PDO using SQL Server Driver
(6 answers)
Closed 4 years ago.
How can connect my mssql dtabase to my website i am using this code:
<?php
$user= 'abhi';
$pass = '';
$db_conn = new PDO('mssql:host=localhost;dbname= Abhishek', $user, $pass);
?>
I know it's not exactly what you're asking, but do you really want to connect manually to a database and create your own sql?, with all dangers and annoying coding with it?
If I were you I'd use something lightweight like Medoo - will save you a lot of time.
see https://medoo.in
<?php
require 'vendor/autoload.php';
use Medoo\Medoo;
$database = new Medoo([
'database_type' => 'mssql',
'database_name' => 'name',
'server' => 'localhost',
'username' => 'your_username',
'password' => 'your_password'
]);
$result = $database->select("account", [
"user_name",
"email"
];
I've installed Moodle with Postgres. The db configuration looks like (yeah, I did it in a bit hackish way):
$CFG->dbtype = 'pgsql'; // 'pgsql', 'mariadb', 'mysqli', 'mssql', 'sqlsrv' or 'oci'
$CFG->dblibrary = 'native'; // 'native' only at the moment
$CFG->dbhost = "my-moodle-db.net' connect_timeout=10 sslmode=verify-full sslrootcert='/path/to/cas/allCAs.pem"; // eg 'localhost' or 'db.isp.com' or IP
$CFG->dbname = $pwd_name; // database name, eg moodle
$CFG->dbuser = 'moodle'; // your database username
$CFG->dbpass = $pwd_pwd; // your database password
$CFG->prefix = 'mdl_'; // prefix to use for all table names
$CFG->dboptions = array(
'dbpersist' => true, // should persistent database connections be
...
My installation works almost fine but once in roughly 10 requests I'm getting the following error:
Error: Database connection failed
And the page is rendered immediately though I set connection timeout to 10 above.
Is there any other place to fix connection timeouts in PHP?
Can I make moodle somehow retry the connection before returning the error to me?
I've been trying to connect to my MYSQL database on my newly acquired website through a PDO connection which is quoted below, and it doesn't seem to be working properly, as it fails as soon as I try using a query or to add an entry. All the information seems to be right, but whenever I try using any command, as selecting or adding entries, it gives me this error:
Array ( [0] => 3D000 [1] => 1046 [2] => No database selected ) 1
Here are the lines of my connection:
try {
$db = new PDO('mysql:localhost;dbname=username_dbName', 'username_dbUser', 'password');
}
catch (Exception $e) {
die('Erreur : ' . $e->getMessage());
print 'Unable to Connect. Please contact the website administrator.';
}
And here is the code I used to test if queries worked.
$req = $db->prepare('INSERT INTO testTable(number)
VALUES(:number)');
$req->execute(array('number' => 13)) or die(print_r($req->errorInfo()));
Obviously I use the actual login values for the connection, but it's not working and I can't figure why.
My website is hosted by HostGator, if that can help.
Thanks in advance for your answers!
Try this
try {
$db = new PDO('mysql:dbname=username_dbName;host=localhost', 'username_dbUser', 'password');
}
I think a problem is with localhost you indicate. Some hosting services require you to use something other than localhost. You might perhaps try 127.0.0.1 instead of it.
If it does not help and you are sure your username, password, and database parameters are all the way correct, I believe you will need to ask your hosting provider for a correct mysql server address.
in your real code is username_dbName a variable, like $username_dbName ? In that case you should use double quotes instead of single quotes.
"mysql:localhost;dbname=$username_dbName"
Try
$host = 'localhost';
$dbname = 'username_dbName';
$username = 'username_dbUser';
$pw = 'password';
$db = new PDO("mysql:host=$host;dbname=$dbname", $username, $pw);
EDIT: corrected typo
try this:
'driver' => 'mysql',
'host' => '(use the server IP address)',
'database' => '(database Name)',
'username' => '(database Username)',
'password' => '(the password you entered for that database user)',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => ''
I am attempting to set up a db connection for a mysqli_connect statement $dbc. I had it working in my script with the following:
DEFINE ('DB_USER','myName';
DEFINE ('DB_PASSWORD','somePass123';
DEFINE ('DB_HOST','localhost';
DEFINE ('DB_NAME','sitename';
// make the db connection
$dbc = #mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME)
OR die ('Could not connect to mysql: ' . mysqli_connect_error());
I then posted a question on SO about security and best practice and was advised that if the connection variables (password, host, dbname, user) exist elsewhere in a separate database configuration file, that I should call the variables for the connection from there.
Here is the relevant snippet from the file in config/database/php
$config['default'] = array(
'benchmark' => TRUE,
'persistent' => FALSE,
'connection' => array(
'type' => 'mysqli',
'user' => 'myName',
'pass' => 'somepass123',
'host' => 'localhost',
'port' => FALSE,
'socket' => FALSE,
'database' => 'sitename',
),
'character_set' => 'utf8',
'table_prefix' => '',
'object' => TRUE,
'cache' => FALSE,
'escape' => TRUE
);
So I then tried this:
DEFINE ('DB_USER','$config['default']['connection']['user'])';
DEFINE ('DB_PASSWORD',$config['default']['connection']['pass']);
DEFINE ('DB_HOST',$config['default']['connection']['host']);
DEFINE ('DB_NAME',$config['default']['connection']['database']);
// make the db connection
$dbc = #mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_NAME)
OR die ('Could not connect to mysql: ' . mysqli_connect_error());
Which produced the following error when I tried to load the page:
"Undefined variable: config"
I then tried this:
$dbc = #mysqli_connect(
$config['default']['connection']['host'],
$config['default']['connection']['user'],
$config['default']['connection']['pass'],
$config['default']['connection']['database'])
OR die ('Could not connect to mysql: ' . mysqli_connect_error());
// Set the encoding
mysqli_set_charset($dbc, 'utf8');
// set the query variable
$query = "SELECT MAX(rating_date)
AS last_date
FROM rating
WHERE incident_id = $incident_id;";
//connect and run the query
$result = mysqli_query($dbc, $query);
echo $result->fetch_object()->last_date;
?>
Which then produced the following error:
"Fatal error: Call to a member function fetch_object() on a non-object in..."
I'm not 100% sure what this is telling me. Yesterday I learned that one cannot echo a SQL query in php directly because it's an object so I cut n pasted the part "echo $result->fetch_object()->last_date;" which worked.
It seems that now that I am trying to draw upon the variables from config, rather than just define them in the function, I am unable to connect perhaps due to a scope issue?
The file with the $dbc connection is in a folder themes/myname/views/reports/detail.php
The file with the database configuration details array is in application/config/database.php
It looks like an issue of variable scope?
What would be the best practice here in making my $dbc variable? How do I call the variables from database.php when it exists in a different directory than the file where I'm calling it? Must I include() the whole file?
How about something sane like:
$dbc = #mysqli_connect(
$config['default']['connection']['host'],
$config['default']['connection']['user'],
$config['default']['connection']['pass'],
$config['default']['connection']['database'])
OR die ('Could not connect to mysql: ' . mysqli_connect_error());
You don't gain anything by using define(), you're only trying to avoid putting the raw strings with your username and password into the mysqli_connect() call in case an error occurs and that line gets sent to the client in an error message/stack trace.
Constants are global and you don't need to set them as global to retrieve them from the memory but variables are not, if you are calling the variable $config from inside a function you have two ways to call it:
Set the variable to be global at the first beginning of your function that you are calling this variable from global $config;
OR
Call the variable using the $GLOBALS variable $config = $GLOBALS['config'];