senor tee
senor tee

Reputation: 47

PHP mysql_query parameter order

I'm a bit of a noob but I am having trouble finding the answer to this question. I have two pieces of code and both work but I'm not sure why.

// Connect to the database 
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); 
// Retrieve the score data from MySQL
$query = "SELECT * FROM table";
$result = mysqli_query($dbc,$query);            
mysqli_close($dbc); // close db

In the instance above the connection is the first mysql_query parameter and then the sql query. This came from a book and isn't how the PHP manual defines it as far as I can see.

In the next example the sql is entered first, then the connection and I have to specifically use mysql_select_db. Why do they both work?

//db connection
$dbc = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$db_selected = mysql_select_db("database",$dbc); // select the db
$sql = "SELECT * from table"; // sql query 
$result = mysql_query($sql, $dbc); // make query on db
mysql_close($dbc);  //close the connection after data is acquired

Thanks in advance for any illumination you can supply.

Upvotes: 1

Views: 1839

Answers (5)

Wh1T3h4Ck5
Wh1T3h4Ck5

Reputation: 8509

Because mysql_query() expects query as first parameter and mysqli_query() expects your query as 2nd.

mysqli_query

mysqli_query ( mysqli $link , string $query [, int $resultmode ] )

mysql_query

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

mysql_select_db() is required because mysql_connect() doesn't have database as parameter, instead of mysqli_connect().

Upvotes: 0

Captain Giraffe
Captain Giraffe

Reputation: 14705

Your first example

$result = mysqli_query($dbc,$query);            

Is a function call to the newer mysqli library, http://www.php.net/manual/en/mysqli.query.php

Your second example

$result = mysql_query($sql, $dbc); // make query on db

Is a function call to the mysql library, http://www.php.net/manual/en/function.mysql-query.php
Both calls match the signature and order of arguments to those functions.

Upvotes: 1

jojo
jojo

Reputation: 41

The function mysql_select_db let you choose another db along your code without the need of 'another' new connection, using the same connection you started with mysql_connect.

Upvotes: -1

KARASZI István
KARASZI István

Reputation: 31467

You're using mysqli_query in the first example, and mysql_query in the second.

Two different function with two different parameter order, that's why I "love" PHP.

Upvotes: 1

Dejan Marjanović
Dejan Marjanović

Reputation: 19380

$result = mysqli_query($dbc,$query); // MySQLi (link, query)

$result = mysql_query($sql, $dbc); // MySQL (query, link)

Upvotes: 1

Related Questions