Solved

PHP, MySQL - connecting to a database

Posted on 2011-03-10
19
506 Views
Last Modified: 2012-06-22
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
0
Comment
Question by:raulmonda
  • 5
  • 5
  • 4
  • +2
19 Comments
 
LVL 7

Expert Comment

by:Vimal DM
ID: 35105936
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
 
LVL 15

Accepted Solution

by:
Jagadishwor Dulal earned 200 total points
ID: 35105939
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
 
LVL 4

Expert Comment

by:WhiteSeed
ID: 35105943
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
 

Author Comment

by:raulmonda
ID: 35105954
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
 
LVL 15

Assisted Solution

by:Insoftservice
Insoftservice earned 200 total points
ID: 35105959
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
 
LVL 15

Expert Comment

by:Insoftservice
ID: 35105979
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
 
LVL 4

Assisted Solution

by:WhiteSeed
WhiteSeed earned 100 total points
ID: 35105983
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
 
LVL 15

Assisted Solution

by:Insoftservice
Insoftservice earned 200 total points
ID: 35105988
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
 

Author Comment

by:raulmonda
ID: 35106022
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
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 15

Assisted Solution

by:Jagadishwor Dulal
Jagadishwor Dulal earned 200 total points
ID: 35106040
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
 
LVL 15

Expert Comment

by:Jagadishwor Dulal
ID: 35106050
Ok to connect database two
$conn=mysql_connect("localhost", "user_2", "password_2");
mysql_select_db("database_name_2", $conn);

0
 
LVL 4

Expert Comment

by:WhiteSeed
ID: 35106055
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
 
LVL 15

Expert Comment

by:Insoftservice
ID: 35106076
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
 
LVL 15

Expert Comment

by:Insoftservice
ID: 35106097
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
 

Author Comment

by:raulmonda
ID: 35106123
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
 
LVL 15

Expert Comment

by:Jagadishwor Dulal
ID: 35106259
Your host login  may be different than you mysql database login.
0
 

Author Comment

by:raulmonda
ID: 35106540
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
 
LVL 4

Expert Comment

by:WhiteSeed
ID: 35108184
Tra, you must use user and pass only for ente after you can selce all your database
0
 

Author Closing Comment

by:raulmonda
ID: 35108599
Thank you all. i did it, finally.

Regards,
Raul
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now