Page 1 of 1

PHP variable import

Posted: Sat Nov 20, 2010 9:04 pm
by Pazuzu156
I need help!

In my php scripts, i have multiple pages connecting to more than one database. I need to know how to add a variable into an external page that i will link in the other pages.

like so:

Code: Select all

<?php

$connect = mysql_connect("localhost","root","") or die ("Error: Cannot connect to host");
mysql_select_db("com") or die ("Error: Cannot connect to database");
$queryget = mysql_query("SELECT * FROM user ORDER BY id ASC") or die ("Error: Invalid Query");

?>
How do I get this from a page and link that page to another page without typing all of this out?

Re: PHP variable import

Posted: Sat Nov 20, 2010 11:22 pm
by requinix
What? Are you trying to find a way that you can put the database connection stuff in one place instead of copying it into each file that needs it?

Two steps.

Step 1: Put the database credentials somewhere. For example, you could have a PHP script

Code: Select all

<?php

$cred = array(
    "foo" => array(
        "host" => "localhost",
        "username" => "root",
        "password" => "",
        "database" => "com"
    ),
    // ...
);

?>
It really, really doesn't matter how you store them. What does matter is whether someone could access it from the web: by using a PHP file it'll get executed instead of displayed to the user, but by using something else (such as a .txt file) anyone who browsed to it would see the information.
In that case just put the file somewhere not web accessible. If you have a public_html directory then put the file somewhere not in there.

Step 2: Write a bit of code to grab the information from that file and use it to connect. If you used a PHP file (like above) called "cred.php" then you could have

Code: Select all

<?php

function connect($to) {
    include "cred.php";
    $connection = mysql_connect($cred[$to]["host"], $cred[$to]["username"], $cred[$to]["password"]);
    mysql_select_db($cred[$to]["database"], $connection);
    return $connection;
}

?>
Step 3 (I lied): Include that connect() function file whenever you need it, and call it like

Code: Select all

connect("foo");

But there are a billion other ways of doing this. Look around and find one you like.

Re: PHP variable import

Posted: Sun Nov 21, 2010 12:35 am
by Pazuzu156
Thanks so much for this bit of information.