phpincludeinclude-pathmysql-connect

Whats wrong with my PHP include for database connection?


Im trying to move my database connection script to an external (and therefore more secure) file. However, it isnt working.

Here my PHP page (with include link)

<?php
include 'block/datalogin.php';
..etc

And heres block/datalogin.php

$dbhost = "localhost";
$dbuser = "************";
$dbpass = "***********";
$dbname = "************";
@mysql_connect($dbhost, $dbuser, $dbpass) or die("unable to
connect to database."
);
mysql_select_db($dbname) or die ("Unable to select");

Im sure the paths and login info are correct.

Any suggestions?


Solution

  • First off, Don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.


    <?php
        $dbhost = "localhost";
        $dbuser = "************";
        $dbpass = "***********";
        $dbname = "************";
        $conn=mysql_connect($dbhost, $dbuser, $dbpass) or die("unable to connect to database.");
        mysql_select_db($dbname) or die ("Unable to select");
    ?>
    

    Then use the $conn variable in your query's

    mysql_query("SELECT * from ....",$conn);