Cleaning Up Your Code with Multiple Files PHP Help

Even if you don’t realize it yet, there’s something problematic about the script you created in the previous section. Look at the first few MySQL calls you make

<?php
mysql_connect(“your.database. host” ,
“your-username”, “your-password”)
or die(“<p>Error connecting to database: ”
mysql_error() . “</p>”);
echo “<p>connected to MySQL!</p>”;
mysql_select_db(“your-database-name”)
or die(“<p>Error selecting the database your-database-name: ”
mysql_error() . “</p>”);
echo “<p>connected to MySQL, using database your-database-name.</p>”;
//-And so on …
?>

You’re manually typing your database host, your user name, your password, and your database name into your script. Suppose that you have 10 scripts; you’re typing that 10 times. The chances for misspelling something are pretty high.

Not only that, what happens when you change your password? Or if you upgrade to a better hosting plan to handle all the web traffic your apps are generating and need to change your database host? You’ve got to track down every place you used that information, in every PHP script. That’s not only a nightmare, it also keeps you from writing new code and making more cash. Not good.

What you need is a way to store those pieces of information where you can keep them up to date, and where your code can refer to them correctly every time. Programmers call that eostroctiro ot.r the information. AI)strac(!on is a way of hiding the implementation-the way something works-from programs that use that something. You basically have a symbol, or a name, and that name refers to some bit of information with a lot more detail. And even if that detail changes, the name still points to the right information

It’s like saying “Bob” and meaning your friend, instead of calling him “that 29-year old guy with the full head of hair.” That way, every year you can call the same friend “Bob,” without changing your (and his) description

In PHP,abstraction uses variables, and you’ll see how that works in the next section .

Replacing Hand-Typed Values with Variables

Instead of including your actual host name, user name, and password as in the code on , you want your code to look more like the following:

<?php
mysql_connect($database_host, $username, $password)
or die(“<p>Error connecting to database: ”
mysql_error() . “</p>”);
echo “<p>Connected to MySQL!</p>”;
mysql_select_db($database_name)
or die(“<p>Error selecting the database your-database-name: ”
mysql_error() . “</p>”);
echo “<p>Connected to MySQL, using database your-database-name.</p>”;
I I And so on …
?>.

You’re really just writing something that looks a bit like a variable in place of hand typing the user name or database name. Now, you can define those variables above your connection code:

<?php
$database_host = “your.database.host”;
$username = “your-username”;
$password = “your-password”;
$database_name = “your-database-name”;
// Database connection code
?>

But is this really that much better? You’re still entering these hand-typed values into your script. You haven’t solved the problem; you’ve just moved it to a different part of the script. What you need to do is to store your values in a separate file.

Abstracting Important Values into a Separate File

To avoid typing values such as your database name and user name into every script=and keep them up to date-you need to put them some place where all your PHP scripts, including  can access them. Open a new file, and call it Now, drop your variables into this new file:

<?php
II Database connection constants
$database_host ; “your.database.host”;
$username ; “your-username”;
$password ; “your-password”;
$database_name ; “your-database-name”;
?>

Try to run your connection script again; you should see your table listing, exactly as in Figure 5-5, which means things are working again.

Require or Include?

There’s another command in PHP that’s very similar to require: include. include does exactly what require does in that it says to PHP to load another file. The difference is that if that file can’t be loaded, include just is suesa warning, and lets PHP continue to run the later commands in your script. require completely shuts things down, but include allows your script to keep going.

But here’s the thing. Are you 12,,,,, going to bother including a file if you don’t need that file? In most cases, probably not. You’re including that file because you need it; you really r ! “,’2 that file to run. So, in almost every situation, you should use require to grab another file, not include. If something goes wrong, you want to know about it. You don’t want the rest of your code running, becauseit’s probably going to error out anyway.

Variables Vary, but Constants Stay Constant

There’s just one more nagging little problem with your code: you’re still using variables for-your user name and password, along with the database host and database name. And what’s a variable? Something that So, PHP will happily let you do this in

What you really want is for those values in app_confJq ..ono to be constant and never change. You can do this with the special define function. Open up d!JrJ_confi9IJrlP and change your code:

<?php
II Database connection constants
define(“DATABASE_HOST”, “your.database.host”);
define(“DATABASE_USERNAME”, “your-username”);
define(“DATABASE_PASSWORD”, “your-password”);
define(“DATABASE_NAME”, “your-database-name”);
?>

You define the name of a constant and the value for that constant, and PHP creates a new constant. Now, you can type DATABASE_HOST into your code, and PHP reottv sees your. database. host, which is the name of your database’s host server. Perfect! In addition, because this is a constant, not a variable, your scripts can’t change it anywhere along the line

Note that the constants are also in all-uppercase letters. That’s not required, but it’s another one of those “speak like a PHP programmer” things, as described in the note on You want constants to look different than variables, and using all uppercase names is one way to do that. Constants also don’t have the $ character before their names.

Go ahead and tryout again. You should get a perfectly good list of table names. But this time, you have constants for your important information, safely tucked away in a file separated out of

Start Small, Add Small, Finish Small

You might be wondering why you couldn’t have just started with and the completed, working version of Or, at a minimum, you could have just dropped all the database connection code into ‘”,. at once and then handled the printing code all at once. Isn’t that how real developers write code?

Well, yes and no. Lots of developers do write code like that. They type anywhere from 10 to 50 lines of code into their script and then try it out. Lots of things will break because developers type too fast and make mistakes. But then, they’ll fix each problem, one by one by one. And for lots of develop, ers, that’s just fine.

But, that’s not very efficient. On top of that, you’re usually toruseo on the last step (like printing out the tables), and so you might not spend much time figuring out the best way to handle the in-between steps. You might not use { and} to simplify the statement that prints $row[ 0], or you might skip a die because you’re thinking about HTML output, not handling .the case in which the database password isn’t right

But. here’s the big reveal, and why these elite developers are elite: this results in better code. Working small, from start to finish, means that you’re focusing on one thing and doing that one thing really well. You aren’t rushing to something else. And that means what you’re working on is solid and works. This approach does take more time in the beginning, but results in roo-souo code that breaks far less often.

So take your time, and work small. Your code will be better, and your customers will love you because your code is still running while they’re on the phone trying to get help with a broken app from “the other guys

Posted on January 13, 2016 in Connecting PHP to MySQL

Share the Story

Back to Top
Share This