简体   繁体   中英

PHP: mysql_query and it's connection explanation

I recently started to learn PHP and found out that the common way to connect to a database is:

// create connection to database
$connection = mysql_connect("localhost", "root", "password")
// Select database
$db_select = mysql_select_db("myDB", $connection);
// and finally the query..
$result = mysql_query("SELECT * FROM table", $connection);

Now my question is, why we have to use $connection in third step ?! as we are using "myDB" database I expect to write the third step this way :

// and finally the query..
$result = mysql_query("SELECT * FROM table", $db_select);

but it seems, that's not how it's done in php. can somebody explain it why ?

The connection represents a database server session , which maintains the database state for you. The currently selected database is simply one part of a session's state, so by passing the connection you are implicitly also passing the currently selected database (along with various other necessary information). In other words, the connection is more general than the selected database .

(As others have already noted, it isn't necessary to explicitly pass the connection when your program only needs to access a single database on a single server. MySQL will use the most recently connected session by default.)

It's not required. However, it is very useful. If you connect to multiple databases on the same page, you may want to use them both. However, if you don't specify which connection, it'll just use the last one that you successfully connected to.

<?php
$forum = mysql_connect(...);
$users = mysql_connect(...);

$me = mysql_query("", $users);
$last_forum_post = mysql_query("", $forum);
?>

If you only have one connection, however, then you don't need to put it in.

Function description

mysql_query ( string $query [, resource $link_identifier ] )

mysql_query()-> send a query to data base (for the currently active database on the server associated with the specified link identifier).

Parameters

  • query -> The SQL query.

  • link_identifier -> If the connection identifier is not specified, the last link opened by mysql_connect () is assumed. If no such link is found, it will try to create one as if mysql_connect () was called with no arguments. If no connection is found or established, an acknowledgment of error level E_WARNING is generated.

You are taking mysql_select_db() wrong.
It is not something essential.
You can use mysql without this function all right.
this is actually no more than alias for the USE dbname query.

Moreover, you can work with 2 or more databases at once within one connection.

So, it just makes no sense to use DB resource instead of connection resource.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM