PHP, MySQL - connecting to a database

hi experts,

new in PHP and MySQL im having a problem. on my small project i came up to the point i need to work with database to register users, etc. I dont really understand the syntax of "mysql_connect() and mysql_select_db()" functions. Given the database name "my_database", database user "my_user" and the password for accessing the database "my_password", which are the syntaxes for these 2 functions?
Any help in this matter will be highly appreciated (and paid ;) ).

Regards,
Raul
raulmondaAsked:
Who is Participating?
 
Jagadishwor DulalBraces MediaCommented:
Hi raulmonda
I hope you already have your database and tables.
mysql_connect() a function which connect with database. Like your question first of all let me define all the required things for mysql_conncet(). First you will need database as you mention above is "my_database", second is username for database "my_user" and the password is "my_password". So you are here ready to connect with your database. mysql_connect function use syntax like below:
mysql_connect(hostname, username, password bool new, int flags);

So now mysql_select_db() function is used to select the specific database from your mysql server.
The syntax is:
mysql_select_db(string database_name, int liink_identifier)

Now here I am showing your example:
let me create variables which we need to connect with database.

$dbhost="localhost"//or your host
$dbuser="my_user";
$dbpass="my_password";
$dbname="my_database"
$conn=mysql_connect($dbhost, $dbuser, $dbpass) or die ('Cannot connect to mysql database');
mysql_select_db($dbname, $conn) or die('Can not find the Database');

Open in new window

0
 
Vimal DMSenior Software EngineerCommented:
Hai,

Find the below code and start using it - make this as an file,

when you want to execute a query you need to include this particular file



      $config['site_url']       = 'http://sitename/';
      $config['site_title']       = '';
      $config["sharename"]       = "/";
      
      // Default value for database strings
      $config['hostname']       = "localhost";
      $config['username']       = "root";
      $config['password']               = "";
      $config['dbname']             = "";
      $config["dbtype"]            = "MySQL";
      $config['admin_email']       = "";
      
      
      // Creates a MySQL connection
      $dbConn = mysql_connect("localhost","root","");
      mysql_select_db('dbname', $dbConn) or die("not selected").mysql_error();      
0
 
WhiteSeedCommented:
the function to connect in a database is:

mysql_connect(hostname,username,password) // return true if the connection issuccessfull

// hostname
$nomehost = "localhost";   
// user for the connection in MySQL
 $nameuser = "username";
// password for the user autentification
$password = "password";
//connect with mysql_connect()
$conn = mysql_connect($hostname,$nameuser,$password);

Open in new window


the function to disconnect:

mysql_close() // return false, if the connection is successfull

Open in new window


select a database:

//you must use 2 parametres, the db name and the conncetion var
mysql_select_db("MyForum",conn);

Open in new window

0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

 
raulmondaAuthor Commented:
hi,
Thanks for answers.

jagadishdulal, on my webspace i have 3 databases each with its name, user and password. mysql_connect () function will connect to the database that i wan,t if i specify its name only later, when i call mysql_select_db() function? Thats the point my confusion comes from.

vimalmaria, your second second coding line is correct?

Regards,
Raul
0
 
InsoftserviceCommented:
hi,
small info abt db connection

mysql_connect(servername,username,password);

servername  =>      Optional. Specifies the server to connect to. Default value is "localhost:3306"
username =>      Optional. Specifies the username to log in with. Default value is the name of the user that owns the server process
password =>      Optional. Specifies the password to log in with. Default is ""

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password'; //by default its null i.e ''

$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die    ('Error connecting to mysql');

$dbname = 'petstore';
mysql_select_db($dbname);
?>
for further explanation pls visit
http://www.php-mysql-tutorial.com/wikis/mysql-tutorials/connect-to-mysql-database.aspx
http://www.w3schools.com/PHP/php_mysql_connect.asp
0
 
InsoftserviceCommented:
hi,

$dbh1 = mysql_connect($hostname, $username, $password);
$dbh2 = mysql_connect($hostname, $username, $password, true);

mysql_select_db('database1', $dbh1);
mysql_select_db('database2', $dbh2);

mysql_query('select * from tablename', $dbh1);
mysql_query('select * from tablename', $dbh2);
0
 
WhiteSeedCommented:
this is a procedure for connceting in the database mysql_connect() after this you enter in another fase of "select database"

//you can do:
$conn = mysql_connect("localhost","user","pass");
mysql_select_db("Database1",$conn);
//some operation with db1
mysql_select_db("Database1",$conn);
//some operation with db2
//....
 mysql_close(); 

Open in new window

0
 
InsoftserviceCommented:
hi,


http://x10hosting.com/forums/programming-help/112801-php-connect-multiple-mysql-databases.html
http://php.net/manual/en/function.mysql-connect.php

If you use PHP5 (And you should, given that PHP4 has been deprecated), you should use PDO, since this is slowly becoming the new standard. One (very) important benefit of PDO, is that it supports bound parameters, which makes for much more secure code.

You would connect through PDO, like this:

try {
  $db = new PDO('mysql:dbname=databasename;host=127.0.0.1', 'username' 'password');
} catch (PDOException $ex) {
  echo 'Connection failed: ' . $ex->getMessage();
}

$result = $db->query("select * from tablename");
foreach ($result as $row) {
  echo $row['foo'] . "\n";
}

$stmt = $db->prepare("select * from tablename where id = :id");
$stmt->execute(array(':id' => 42));
$row = $stmt->fetch();

try {
  $db1 = new PDO('mysql:dbname=databas1;host=127.0.0.1', 'username' 'password');
  $db2 = new PDO('mysql:dbname=databas2;host=127.0.0.1', 'username' 'password');
} catch (PDOException $ex) {
  echo 'Connection failed: ' . $ex->getMessage();
}
0
 
raulmondaAuthor Commented:
Thanks for answers.

now confusion is even bigger. considering the following scenario:

im having 3 databases

database_name_1, user_1,  password_1
database_name_2, user_2,  password_2
database_name_3, user_3,  password_3

how i connect to say database_name_2?

Regards,
Raul
0
 
Jagadishwor DulalBraces MediaCommented:
First you need to connect with mysql server that is
mysql_connect() function;
and then after you need to select your db using
mysql_select_db() function which include database name and link identifier

mysql_select_db("databasename", $conn)
0
 
Jagadishwor DulalBraces MediaCommented:
Ok to connect database two
$conn=mysql_connect("localhost", "user_2", "password_2");
mysql_select_db("database_name_2", $conn);

0
 
WhiteSeedCommented:
i think you have 3 db in 1 host all with the same user and password. use mysql_connect for the connction and after select the databases with select_db
0
 
InsoftserviceCommented:
hi,
$hostname= 'localhost';
$dbh1 = mysql_connect($hostname, 'user_1', ' password_1'); //connect to db1
$dbh2 = mysql_connect($hostname,  'user_2', ' password_2'); //connect to db2
$dbh3 = mysql_connect($hostname,  'user_3', ' password_3'); //connect to db3

mysql_select_db('database_name_1', $dbh1);
mysql_select_db('database_name_2', $dbh2);
mysql_select_db('database_name_3', $dbh2);

mysql_query('select * from tablename', $dbh1);
mysql_query('select * from tablename', $dbh2);
mysql_query('select * from tablename', $dbh3);
0
 
InsoftserviceCommented:
Hi,
In the above scenario u can take any one part which ever u want.
i.e if u want to connect to db1 than take
$dbh1 = mysql_connect($hostname, 'user_1', ' password_1'); //connect to db1
mysql_select_db('database_name_1', $dbh1);
mysql_query('select * from tablename', $dbh1);

similarly for other database and table.
considering that its one hostname ie localhost it can be change as per ur need

0
 
raulmondaAuthor Commented:
Yes, im having 3 databases in hosted in 1 host. Now, for mysql_connect() i should use the user and the password i use to login to the host?
0
 
Jagadishwor DulalBraces MediaCommented:
Your host login  may be different than you mysql database login.
0
 
raulmondaAuthor Commented:
the host i use did not required any pass or user name when i created the database. I assume, then, there is no user or pass to access MySQL server? just the host ones?
0
 
WhiteSeedCommented:
Tra, you must use user and pass only for ente after you can selce all your database
0
 
raulmondaAuthor Commented:
Thank you all. i did it, finally.

Regards,
Raul
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.