2

I am a beginner with MySQL. I have this code and I would like an explanation on how the function knows which database to use since $conn and $db are defined?

$conn = mysql_connect("localhost","primeb5_mysql","***");
$db = mysql_select_db("primeb5_unigis");
$query = "SELECT * FROM lesson3";
$result = mysql_query($query);"
guido
  • 18,864
  • 6
  • 70
  • 95
  • 2
    If you would like to start using php+mysql I recommend you to use MySQLi or PDO modules... mysql_* functions are deprecated. – Nelson Galdeman Graziano Oct 23 '13 at 13:15
  • 1
    There is only one database defined, and that is in the `mysql_select_db()` function. `mysql_connect()` only contains the database host, username and password. Aside from that, [please don't use mysql_* functions anymore](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php) – George Oct 23 '13 at 13:15
  • just query like this SELECT columns FROM database.table ... – Raymond Nijland Oct 23 '13 at 13:16
  • mysql_query uses the last connection if not given by explicit argument `mysql_query($query, $db)`. You should listen to @NelsonGaldemanGraziano however and not use the mysql_* functions. – Mr47 Oct 23 '13 at 13:16

2 Answers2

3

From PHP manual:

http://php.net/manual/en/function.mysql-query.php

The MySQL connection. If the link identifier is not specified, the last link opened by mysql_connect() is assumed.

So, In case you don't specify the connection (second parameter) to the mysql_query() function, the last one is used.

On the side note, I'd like to notify you, that mysql_* functions have been deprecated in PHP 5.5.0. Do not use them, because if you do, your site might stop working soon.

Rok Kralj
  • 46,826
  • 10
  • 71
  • 80
0

mysql is deprecated use mysqli or PDO instead

You don't have to use an PHP function to select your database

just use this

mysqli_query("SELECT * FROM primeb5_unigis.lesson3");

or join example between multiple databases after ON missing...

mysqli_query("SELECT * FROM database1.table1 INNER JOIN database2.table2 ON ...");

edit

i think topicstarter means connection to database but i leave the answer could be helpfull

Raymond Nijland
  • 11,488
  • 2
  • 22
  • 34