I have an api written in PHP for a backend service that supports my Android app. I'm in the process of setting up different environments - development, staging, production - each with they're own database. The API performs queries to its respective MySQL database and everything is up and running just great in development.
My question is about the proper technique for handling different database connections for the api in each environment? Is there an easier way to change the database that my php->mysql connections use than changing them all by hand manually before deploying from, say, development to staging?
I'm coming from an Android environment, so what comes to mind right away is Gradle's build flavors and how that allows different code to be used based on the specific build variant you want.
I think that's a good use case for Apache environment variables, which can be set in the httpd.conf file (or an .htaccess file).
Basically, you can something like:
SetEnv DATABASE_NAME "MyDB"
in your httpd.conf file, and then in PHP use:
$_SERVER['DATABASE_NAME']
to access it.
In general, it's good practice to keep environment-specific things out of your code so that your code is more portable. Your case is a perfect example.
Edit (by rpm):
Be sure to restart apache after modifying the httpd.conf file. I had issues getting this answer to work, but restarting Apache fixed everything.
What we do is put the database connection parameters in a separate include file, e.g.
$db_host = "xxx";
$db_user = "xxx";
$db_password = "xxx";
$db_database = "xxx";
Then the other scripts can use
require_once('db_params.php');
and use these variables when making the database connection.
Then we just use different contents of the script in different environments.
Related
i have simple site on some vps. i used wamp server and additional setup postgresql instead mysql. site works fast on localhost and from public ip, but...
i have webix grid on one page and php file put data from database into this grid, when page are loading. when i on localhost, grid loading time is 5 sec. I think for 35k row its not bad. But when i loaded page from web via another pc, loading time grow 4-5 times - above 20 second.
internet connection is fast, it looks like some server setting slow down transfering data from php or executing php code. I had same problem with transfering files on server from ftp, and solve it via disabling some checking options in server.
Here is my php code
require_once("../codebase/data_connector.php");
require_once("../codebase/db_postgre.php");
$conn_string = "host=127.0.0.1 port=5432 dbname=demo user=postgres password=postgres";
$dbconn = pg_pconnect($conn_string);
$dbtype = "Postgre";
$data = new JSONDataConnector($dbconn, $dbtype);
//$data->dynamic_loading(35);
$data->render_sql("SELECT id,count,contragent,value,inn,kpp FROM mart_customers", "id", "count, contragent, value, inn, kpp");
pg_close($dbconn);
Do anybody have idea, what problem can be now? i tried do some famous thing, like change localhost on 127.0.0.1 and add apache into firewall exclusion, but nothing changed.
My options: windows server 2012 R2 + wamp + postgreSQL
I strongly suggest you use a development environment which matches your production/live environment as closely as possible.
For this, you could use VirtualBox (https://www.virtualbox.org/) which allows you to spin up a guest machine on your host in which you can use any OS, server, etc together with any dependencies on a project by project basis. There are others but I've only got experience with the VB so can't comment on others.
Try using Vagrant together with VirtualBox: https://www.vagrantup.com/. Vagrant makes the provisioning of your virtual environments easy and reproducible without much effort.
In our team, I used to be the only developer, coding directly on our remote dev server but we're hiring more developers so we have a need to move the codebase to our local machines so we don't encounter any file collisions.
However, even though I want to use a local codebase, I don't want to use a local database. Syncing the database seems like a hassle and is to be honest not really needed. So we're sticking to multiple codebases, but one database.
How can I run Wordpress on my local machine, while still using our remote server database? How do I set this up in MAMP?
I'm kind of new in setting up servers/ports/databases etc so it's not my strong suite. The problem which I don't know how to get around is the urls.
For instance, our WP sites have the url format:
site1.portal.dev
site2.portal.dev
When I type these URLs I want the codebase to be local but the database to be our remote dev server.
Update the config to point to the remote database. Job done.
As long as the configuration of that database allows you to connect to it, it's very simple.
An example of updating the wordpress config
I work in a multi-developer team. I've found that the best option is to have a full local environment.
We use wp-migrate-db pro for copying the dev database down locally. Once configured (per site) it takes a minute to grab the latest copy from dev.
Having this separation allows your team to make changes for their local development efforts (such as entering bad data, test pages, posts etc) without affecting other developer efforts.
This approach also works well for working with developers of various skill levels...and helps to reduce bigger issues that you may come across later on.
Using your site1.portal.dev should work, as the site_url and home_url. When you click on a link in your dev portal, it will continue to use site1.portal.dev, as WordPress thinks your site resides there. The database just holds the information, it doesn't matter where it resides.
You can connect to your remote mysql instance by providing the correct host, username, password. Usually it would be localhost, but in your case, you will want whatever the IP/DNS address for the machine that is hosting your mysql server is.
You can test the mysql connection with
mysql <database> -h <host> -u <username> -p
add -P <port> if your mysql server is listening on a different port.
I know this is an old question, I just post the answer I found that works for me in case anyone is looking for the solution of "How can I run Wordpress on my local machine, while still using our remote server database"
Install WordPress on your server (http://yourdomain.com)
Configure it with your database
Make sure whitelisting your local machine IP in "Remote MySQL" within your server's hosting panel
Pull down the entire WordPress directory onto your local machine
into a project folder
Add project folder to MAMP or your local web server app of choice
(make a note of your Server Name)
Open your LOCAL copy of wp-config.php Change 'DB_HOST' to
'yourdomain.com'
And add the following just above 'require_once(ABSPATH .
'wp-settings.php'); in wp-config.php file
define('WP_CACHE', true); $currenthost = $_SERVER['HTTP_HOST']; $mypos = strpos($currenthost, 'localhost'); if ($mypos === false) { define('WP_HOME','http://yourdomain.com'); define('WP_SITEURL','http://yourdomain.com'); } else { define('WP_HOME','http://localhost'); define('WP_SITEURL','http://localhost'); }
Replace each instance of 'localhost' with your 'Server Name' in MAMP. (localhost is default)
Source URL: https://coderwall.com/p/ck8v4a/remote-database-with-local-wordpress-instance
I've been developing PHP pages for several weeks now and am getting much more confident in my code. I've obtained a hosting account through Bluehost, and am ready to begin making some live pages. Previously I have been using XAMPP on Windows and developing all of my pages on my local computer. I'm trying to determine the best practice for creating my page locally and then easily moving it to my hosting server. I use Filezilla to transfer my files. Here are my main questions:
1.) How can I ensure my local and live MySQL databases stay in sync? I have been manually creating the database locally, and then taking the same code and applying it to my live server. (I have phpmyadmin locally and on the live server, but dont know how to use it to streamline this process)
2.) I have to change the mysql password and connection credentials on all files before moving them from local server to live server. Is there a way around this?
For question 1 you could dump the database and import it at the production end each time you do an upload, or you could use mysql replication.
For question 2 it is quite common to have the database connection details in a separate php file and then include that file at the top of each page that needs to connect to the database
Then you can just change that one file, or only upload the one with the production database details.
db.php
<?php
$dbuser="";
$dbpass="";
$dbname="";
$dbserver="";
?>
myfile.php
<?php
include("db.php");
$conn = mysql_connect($dbserver, $dbuser, $dbpass);
mysql_select_db($dbname);
//....
?>
You could point your mysql_connect() host to your new server's IP address. Therefore, no matter where your code is, it will connect to the socket.
$link = mysql_connect('<your ip here>', 'mysql_user', 'mysql_password');
I always make my projects so that I have to change 1 line of code to fluctuate between dev and production.
I have a base file where i specify my environment like this:
$env = 'dev'
Then in my database setup variables i have something like this:
if($env == 'dev') {
specify dev variables
} else if($env == 'prod') {
specify prod variables
}
The beauty of this is that when i want to move between dev and prod, i only have to change 1 variable.
Use a version control system such as svn or git; look at phpmig for database management, look at deployment tools such as capistrano, make sure you test on a replica of the production server (even if you just use a virtual host)
I'm pretty much in the same position as you and here is how I plan to do it.
I don't plan to sync my local database with the live one but just move the local database once to the online one when I'm done. The way I do that is just, in PHPMyAdmin select the database I want and export it as a .sql file. Then on the online server I simply import that file.
The best way I know is to have a separate file where you have a function which looks something like this:
function connectToDB(){
$mysqli = new mysqli("localhost", "root", "123", "myDatabase");
return $mysqli;
}
Then when you want to use that you just import the file in the top of your other PHP files and use it like this:
$mysqli = connectToDB();
This is my way of doing it. If someone knows a better way, I would be happy know it.
Deploying from development to production is not a trivial task and can be very complicated. Companies invest a lot of resources in order to make deployment a logical and stable process. I recommend to break your question into pieces and ask more specific.
As response to your questions, what I'd do:
1) When deployment requires a change in the database structure, write those changes in sql scripts. When you deploy you'll need to run those scripts and update the code (as you can figure out, the time in between will make the application unstable or broken). Before anything, take a copy of the production database onto development and try the scripts first on development. You will get so databases in sync each time you deploy.
2) How you save passwords depends on whether you are using frameworks or not. Following frameworks, it's a good approach to define an environment variable and set passwords according to the environment (dev or production).
As regards to code deployment, even if you are a unique developer, I'd use svn or git to save your projects under versions control. It will make code updates much more simple and help you to roll back if desired provided you create tags for each deployment.
Best practices are to write database migration scripts, version them. Then each time you upload to production, you store the values of these versions in the database. Only run the versions that you have not run before.
Have different local config files outside of your repository. This allows you to maintain the necessary application config in the repo with a main config file, then the local config file overrides database and environment settings.
I usually have a config-file with some global variables for database connectivity settings (such as db host, db name, user, pass).
I also really like to be able to just drag and drop all files from my dev machine to the production server. However, development db host etc may be different from the one on the production server.
Is there an easy way of, in PHP, saying something like "if I'm on the dev-machine, use these values"? (I'd prefer to avoid hacks based on host IP / name.) I'm thinking of something like perhaps setting something in php.ini or httpd.conf so that for instance $DEV_MACHINE, is set to true on the dev machine.
You can set up an Apache variable with SetEnv, and query it with PHP's apache_getenv().
I usually use a file called config-local.php which is not under the source control.
If the file is absent, the app shows a warning page saying "finish the setup", or just runs a master to set up database credentials etc.
You can always use the URL. The dev url and the prod url should be different. And should be pretty stable.
But the ideal way is to keep the creds separated. You don't want the prod creds getting stolen if the dev server is hacked. So it is really best to suck it up and just keep them separate.
I need to connect to a remote mysql database in PHP.
Specifically I have this as a constant:
define("DATABASE_SERVER", "localhost");
...
$db = #mysql_connect(DB_SERVER, DB_USER, DB_PASS);
I want to copy the site to my local machine but still connect to the main database.
Can I do this? if so, how? All I have is FTP access.
You need the IP/URL of the DB and put that instead of localhost.
You need to make sure the DB configuration allows remote connections/outside the local network.
Once you get the IP of the DB (should be given by the support team, if it is being supported), you will know.
If all you need to do is copy the data and build it locally on your machine, so you don't destroy live data, use the export tab in PHPmyadmin. I assume you don't have too much data.
PHPmyadmin->select the DB (from the left frame)->press the export TAB (top, right frame).
Should be clear from there.
You can export it as SQL and run this SQL on your local machine.
I would guess that your database server is refusing remote connections. If you have cPanel there's a section called something like "Remote Database Access" where you can enable them to certain IP ranges.
I suggest that you export the database in question, and import it locally. This way, you won't destroy live data if you mess up.
Many, if not most, hosting providers also provide a DB interface like phpMyAdmin. You can export the database from there.
+1 gnud. You shouldn't use the production database for development work, even if you could configure it to listen for external access on a public internet interface(*). One slip of the mouse and you're scribbling over important live data. Instead you should be working on a standalone development server of your own, from which you can push the code changes to the live server when you they're working and tested.
(*: Which is in itself a very bad idea: if the passwords are too weak or you're running an old version of MySQL with exploits available you are going to get hacked by automated probes very quickly.)
You'd normally export the database from the shell using the mysqldump dbname > dbdump.sql command, and import it on your local server by piping it into mysql dbname < dbdump.sql. There might also be a MySQL admin web interface installed on the server you could use. But if all you've got is FTP, you haven't really been given the tools you need to do development work. See if you can get an empty or dummy database to test the site with.
(What's more, FTP is a nasty business... really in this century you should be using SFTP.)
The simplest approach is to have DATABASE_SERVER be defined as database (or something equally meaningful) and put an entry in your hosts file. On your local machine this can point to the remote address, on the server this will point to 127.0.0.1.
define('DATABASE_SERVER', database);
On windows your sites file is:
c:\windows\system32\drivers\etc\hosts
with:
database <remote_ip>
Linux:
/etc/hosts
with:
database 127.0.0.1
Side note: is your remote DB a production DB? If so you shouldn't really be using the remote DB for development work, unless you're using a separate dev DB - even then I wouldn't run the risk of rogue dev queries eating up the remote DB resources.
Update: Doh, missed you're limited to FTP access.