Query from a different database than the default

I’m making a layout for a wordpress page.

The layout needs to connect to a second database (both databases are in the same domain).

But the problem is, when i execute just the file it works. But when i included inside the wordpress layout i don’t get data, no errorrs, nothing

The script is just:

 $con = mysql_connect('host','user','pass');
 mysql_select_db('db', $con);
 $q = mysql_query('SELECT * FROM vars', $con);
 var_dump(mysql_fetch_array($q));

As i say.
If i execute the file alone:

http://example.com/blog/connect.php

it works great, and returns data.

But if i do inside the layout (creating a wordpress page, and giving the layout to it)
Returns nothing.

Any idea what can be happening there?

Solutions Collecting From Web of "Query from a different database than the default"

I don’t know why the mysql_connect isn’t working inside WordPress. But an easier way of doing it would be to use the $wpdb class. Try replacing your code with this:

$second_db = new $wpdb( 'user', 'pass', 'dbname', 'host' );
$q = $second_db->get_results( 'SELECT * FROM vars' );
var_dump( $q );

and see if you get the results you want. (note that the order of the variables passed to the $wpdb constructor is different from the order used by mysql_connect)

goldenapples probably has the best solution, but to answer your question specifically, you need to set the new_link parameter in the mysql_connect function to true.

 $con = mysql_connect('host','user','pass', true);