SQL database error

saxasm

New Member
Messages
1
Reaction score
0
Points
0
I'm trying to make a system to register on mysite.

Unfortunately i get loads of errors when i try to connect to the database.


So, what should the parameters be to mysql_connect() be here? I'm a bit of a noob when it comes to php-programming, but i have a few years of C++ experience, so learning it shouldn't be a problem. :)

When i try what i think is intuitive ("database_name","database_username",database_password") i get errors. :eek4:

So how should i be doing it?
 

OdieusG

New Member
Messages
50
Reaction score
0
Points
0
MySQL/PHP connections start with:
$link = mysql_connect(<SERVER>, <USERNAME>, <PASSWORD>)

I'm thinking once you connect, you're not selecting a database to use, most common error of all....just do this
mysql_selectdb(<tablename>, $link)
Put that in the code, and use the aforementioned function to connect, so it should look like:
$link = mysql_connect(<server>, <username>, <password>);
$result = mysql_selectdb(<databasename>, $link);

I you want to do typechecking to make sure it didn't fail, you could always add after that code:
if(!$result) { print mysql_error(); }

Hope that was what you were looking for
 

trike97

New Member
Messages
5
Reaction score
0
Points
0
Code:
  // Define database connection constants
  define('DB_HOST', 'localhost');
  define('DB_USER', 'username');//put in username
  define('DB_PASSWORD', password');//put in password
  define('DB_NAME', 'databaseName');       //put in DB name


 //connect to database
         $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
         or die('Error connecting to MySQL server.');

         //display existing entries
        $query = "SELECT field FROM dataBase";
        $result = mysqli_query($dbc, $query);
        $row = mysqli_fetch_array($result);

define constants for the database in case you change your password you wont have to change it on every page, and then put constants on seperate page and link to it.
 

garrettroyce

Community Support
Community Support
Messages
5,609
Reaction score
252
Points
63
@trike97 Although your suggestion works well, it's not good coding practice to define passwords. Most of the time you will see coders use the password once and then unset the variable it is held in to be even more secure.

What I do is create an abstract class with a static property that is the database connection:

Code:
abstract class DB {
public static $DB;
// inline parameters mean that the password will fall out of scope after this function executes
// and no one can ever see them unless they can access the code
final public static function connect($server,$user,$password) {
    self::$DB = mysql_connect($server,$user,$password); } } //password is not defined after this point


DB::connect('localhost', 'username', 'password);

// now any time you want to access your connection you can access it by using DB::$DB
 
Top