0

I want to use a single file for my php application to connect to a database when the user register for the first time or login in

what is the code is it same as below is good:

$username="root";
$password="root";
$database="test";



    function Save($name)
    {
        global $username;
        global $password;
        global $database;

        $link = mysql_connect('localhost', $username, $password);
        if (!$link) {
            die('Could not connect: ' . mysql_error());
        }
        @mysql_select_db($database) or die( "Unable to select database");
        $query = "INSERT INTO test (name)" .
                 "VALUES ('" . $name . "')";
        mysql_query($query);
        mysql_close();
    }

Also, how can i do the require for that file? it is located in the root of the application folder should but i back slash first after require '/filename.php' or should i put double dots first?

5 Answers 5

2

If the file is in the same directory, you could simply use: include_once "db.php";

If it is in parent directory(ie, one level up), then use: include_once "../db.php";

Another one is to append the global DOCUMENT_ROOT with the filename(like others have given examples below).

And also, avoid mysql_* functions. Use PDO or mysqli instead.

Wish you good luck. :)

Sign up to request clarification or add additional context in comments.

Comments

1

Your question essentailly boils down to "how can I include a file that is in the root from anywhere". Well, there's two answers.

The first answer is to just use inlude($_SERVER['DOCUMENT_ROOT']."/connect.php");, but that's a lot to type, especially if you have a lot of includes.

Personally, I like to start my script with chdir($_SERVER['DOCUMENT_ROOT']); Then I don't have to worry about where I am anymore - I will always be in the root folder.

Comments

0
  1. Probably it is not good that you open mysql connection on every save, if there will be many such calls per request.
  2. inlude($_SERVER['DOCUMENT_ROOT'] . '/db.php');

Comments

0

A few comments: First, if you don't need to use the password and username and database elsewhere, you should just define them in the function.

Second, If I'm not mistaken if you put the "/" in front of the path that will take you all the way down to the root of the filesystem, which I'm guessing this user wouldn't have access to. That being said, I would use ".." to navigate up the hierarchy. So use: require_once("../path/to/file.php")

Comments

0

Rather that putting the include file in the document root, you should create a directory for common include files, and add it to the include_path setting in php.ini. Then you can just do include 'connect.php';.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.