php multiple databases issue - php

I've set two database conections as below
$con1 = mysql_connect("localhost", "root", "pwd") or die (mysql_error());
$con2 = mysql_connect("localhost", "wordpress", "pwd", true) or die(mysql_error());
mysql_select_db("lab_ancp", $con1) or die(mysql_error());
mysql_select_db("wordpress",$con2) or die(mysql_error());
and it works fine
so then i do some queries on a page like this:
$sql="select unome from associado where uid=$uid";
$result=mysql_query($sql,$con1) or die(mysql_error());
and it works fine, after that i do a second query like this:
$sql="select ID, post_content, post_title, post_excerpt, meta_value
from wp_posts join (
select post_id, meta_value
from wp_postmeta
join (
select post_id from wp_postmeta
where meta_key='destaque' and meta_value='s'
)as t1 using(post_id)
where meta_key='pft_widescreen'
) as t2 on (wp_posts.ID=t2.post_id)
ORDER BY RAND() LIMIT 1";
//echo $sql . "<br />";
$row=mysql_fetch_assoc(mysql_query($sql,$con2)) or die(mysql_error());
and again everything is just fine, but then....
$sql="select * from eventos where edatade>='$hoje' or edataate>='$hoje'";
$result=mysql_query($sql, $con1) or die (mysql_error());
gives this error:
**
SELECT command denied to user
'wordpress'#'localhost' for table
'eventos'
**

From the error it seems you should verify permissions for the wordpress user on the eventos table. Your code seems to be correct.
If you want to verify this, maybe try a "SELECT * from eventos" using the second connection. Do this as the first query in the script.

Well
Its solved.
Don't askme the reason but i've tried to change the order in the first two roww, i.e put $con2 before $con1 and the queries now simply work fine.
I suspect that the ..."true" parameter has something to do with that.
Thx guys.

http://se2.php.net/manual/en/function.mysql-select-db.php#39095
http://se2.php.net/manual/en/function.mysql-select-db.php#93487
Seems to be a problem with the mysql_select_db, the second link is one solution.
I would recommend using phps mysqli (MySQL Improved Extension) instead of old mysql stuff (don't know if it solves your problem, but it solves other problems you might walk in to).

I suspect that the reason is that the connection is still in memory so when you try to execute the second query, this use the last connection. I have the similar problem with Joomla two databases use issue. I am looking for the fix for this problem, I think that is a missing rule in our code.
HEY!!! I get it, the problem is that when you create the second connection, for default PHP return the same reference for the last one. So if you need a new connection you should prepare a mysql_connect with $new_link to true, like this
$myconn = #mysql_connect($this->db2_host,$this->db2_user,$this->db2_pass, true);
The last parameter means that you need a new reference and not the last one. You can find more information:
HERE and HERE
Hope it helps.

Related

How can I connect to two databases

i am trying to connect to two databases to create a search engine for a couple of my databases. Heres a test code. can someone tell me what i am doing wrong or if it is possible. thanks.
mysql_connect("localhost","user","pass");
mysql_select_db("db1");
mysql_select_db("db2");
$search=mysql_query("SELECT * from db1.repairs, db2.order from db1,db2");
while($row=mysql_fetch_array($search)){
echo $row['first_name']." ".$row['esn']." ".$row['order_type']."<br>";
}
You can query across databases if you specify the database name before the table name like this
SELECT a.col1, b.col2
FROM db1.table1 AS a
INNER JOIN db2.table2 AS b ON a.someIdFromA = b.someIdFromB
As Korcholis mentions the problem is in your select. Also you do not want to use the mysql_* functions if you can avoid it. PDO or MySqli are preferred.
Edit
At least this works using MySQL. I would bet it works for most other RDBMSes as well, but I don't have others handy to test and I can't say if this conforms to SQL standards or not. Comments anyone?
You can use
<?php
$db1 = mysql_connect("localhost","user","pass");
$db2 = mysql_connect("remote","user","pass");
mysql_select_db("db1", $db1);
mysql_select_db("db1", $db2);
$query1 = mysql_query("USE somedatabase", $db1);
$query2 = mysql_query("USE otherdatabase", $db2);
Or try with a class that handles these connections in a different instances
http://www.joni2back.com.ar/programacion/php-class-for-mysql-databases/
mysql_connect returns a $resource. You can connect twice and select a database with each one (in fact, you can select a database from the connect itself), and then use each connection.
However, your problem is that your SELECT is incorrect. You are trying to select fields from tables from databases, which is not correct. In fact, you cannot fetch two different databases in a so fancy way, because they are considered two sets of information independent and unrelated between them. That's why tables exist, to fit that problem.
This other answer, however, may have a solution.
Otherwise, you could connect to each database using two mysql_connect and two resources, fetch the values, and cross them yourself. Not the best option, I know, but an answer that could fit your needs.
PS: If you are beginning the project right now, switch to Mysqli or PDO. Mysql is deprecated.
Try to review this, and maybe you can't query a database with querying FROM:
<?php
$con1 = mysqli_connect("$hostname", "$user1", "$password1", "$db1");
if (mysqli_connect_errno($con1)) {
echo mysqli_connect_error();
}
$con2 = mysqli_connect("$hostname", "$user2", "$password2", "$db2");
if (mysqli_connect_errno($con2)) {
echo mysqli_connect_error();
}
$search1 = mysqli_query($con1, "SELECT * from $db1table");
$search2 = mysqli_query($con2, "SELECT * from $db2table");
/* Other PHP codes here */
mysqli_close($con1);
mysqli_close($con2);
?>
You can even improve this code, nor minimized it!

How to select from mysql db php

Are these 2 equivalent, if not how can I make them. I'm using php/Mysql (I'll use mysqli later)
mysql_select_db("db_App", $link);
$result = mysql_query("SELECT * FROM AppOne");
OR
$result = mysql_query("SELECT * FROM db_App.AppOne"); // how can I get this to work like above?
You'll always have to select a database. From then on, specifying the database in the query is useless. It's better not to specify it there anyway, as that'd make you run into troubles if your database changes at some point.
if you skip the $link in mysql_select_db("db_App", $link);
they should do the same.

Why will the following SQL command not work with mysql_query in PHP?

SELECT *
FROM `enzymes`
INNER JOIN `compounds`
ON compounds.compound_id = enzymes.compound_id
WHERE `ec` LIKE '1.11%'
it works in phpmyadmin and mysql workbench.
It won't work regardless whether I backtick everything use mysql_real_escape_string and add the database name where appropriate. the phpmyadmin php code won't work either.
ERRORS: Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in....
same error for all other query-resource dependent functions
Upd:
case 'ec':
$dbl = mysql_connect(DB_ADDRESS, DB_USER, DB_PASSWORD);
mysql_select_db("kegg", $dbl);
//a)connection is fine
//b)tried with explicitly providing the db name vs with pre-selection
$sql = "SELECT * FROM enzymes INNER JOIN `compounds` ON compounds.compound_id=enzymes.compound_id";
print_r($sql);
$result = mysql_query( $sql, $dbl);
print mysql_error ($dbl);
while ($row = mysql_fetch_assoc($result)) {
print_r($row)
$items[ $row['name'] ] = $row['compound_id'];
}
,,,
Solution: Thanks everyone,- Brad gave the crucial answer first.
$sql = "SELECT enzymes.*, compounds.*\n"
. "FROM enzymes\n"
. " INNER JOIN compounds\n"
. " ON compounds.compound_id = enzymes.compound_id\n"
. "WHERE enzymes.ec LIKE '1.11%' LIMIT 0, 30 ";
A similar topic came up recently where it was suggested that it only works when selecting specific fields. The crucial solution when all data is desired is to resolve ambiguities to:
enzymes.*, compounds.*
Given that error, mysql_query is returning a boolean FALSE, indicating an error. Try this:
$result = mysql_query(...your query here...) or die(mysql_error());
to see exactly what the error is.
My gut is telling me the database is confused by your column references. When you start doing joins, and especially when you have columns names that may match, it's good practice to be explicit on what you're selecting, comparing, etc. e.g.
SELECT enzymes.*
FROM enzymes
INNER JOIN compounds
ON compounds.compound_id = enzymes.compound_id
WHERE counpounds.ec LIKE '1.11%'
But, without knowing the exact error that's occurring, this can only be a guess.
UPDATE
Now that I see the error, make sure you're testing for a proper query response. When you call mysql_query (or whatever you use), check the resource for failure before trying to fetch the result. Most connection libraries have a *_error or *_last_error method you can call to see what caused the failure.
There are a number of reasons that a query will work in environments like phpMyAdmin but not through PHP's mysql functions. For starters, make sure you've selected the proper database with a USE command via PHP's mysql_select_db function (docs). When using phpMyAdmin, that is being performed in the background automatically, not so with a PHP script.
If you specify the names of the database in your query, the previous step won't be required, BUT, your code will be that much harder to maintain if there is ever a change in the database name.
To specify the table, do this: SELECT field1, field2 FROM database_name.table_name WHERE...
Second, if you are using double or single quotes incorrectly, the variables might not be parsed or other such issues: this will cause your query to be invalid. A code sample would help determine if this is the case.
This indicated that you should pass an mySQL resource in whith the mysql_query.
look at:
resource mysql_query ( string $query [, resource $link_identifier ] )
You will get the $link_identifier when opening a connection:
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
Avoid column ambiguous error in MySQL INNER JOIN.
Please try:
SELECT compounds.compound_id as cid, enzymes.compound_id as eid
FROM `enzymes`
INNER JOIN `compounds`
ON compounds.compound_id = enzymes.compound_id
WHERE `enzymes`.`ec` LIKE '1.11%'
And if you'll get similar pairs of ids, the problem is here.

Run MySQL INSERT Query multiple times (insert values into multiple tables)

basically, I have 3 tables; users and projects, then I have 'users_projects' to allow the one-to-many formation. When a user adds a project, I need the project information stored and then the 'userid' and 'projectid' stored in the usersprojects table. It sounds like its really straight forward but I'm having problems with the syntax I think!?
As it stands, I have this as my INSERT queries (values going into 2 different tables):
$projectid = $_POST['projectid'];
$pname = $_POST['pname'];
$pdeadline = $_POST['pdeadline'];
$pdetails = $_POST['pdetails'];
$userid = $_POST['userid'];
$sql = "INSERT INTO projects (projectid, pname, pdeadline, pdetails) VALUES
('{$projectid}','{$pname}','{$pdeadline}','{$pdetails}')";
$sql = "INSERT INTO users_projects (userid, projectid) VALUES
('{$userid}','{$projectid}')";
$result = mysql_query($sql, $connection)
or die("MySQL Error: ".mysql_error());
header("Location: frontview.php");
exit();
You simply forgot to execute the sql between each query. Add the
mysql_query($sql, $connection)
or die("MySQL Error: ".mysql_error());
between each query and you are supposed to be fine.
b.t.w (1) it always helpful to test with a console open with tail -f on the sql log (under /var/log/mysql/ )
b.t.w.(2) You are having heavy security issues in your code.
b.t.w (3) You might want to consider using PDO/Mysqli and not the old mysql extension.
b.t.w (4) It would make your life simpler to use some kind of wrapper (a good class) to approach the DB and not do it directly everywhere in your code.
Yeah, two things I would check would be
1) are the queries being executed? Like the other poster mentiond, are you executing the SQL queries in between setting the SQL?
2) if you print/debug/display somehow the variables that you are inserting, are they getting populated? If you're seeing things get inserted, but some of the data is blank then something might be blowing up before that and those variables would be blank.
I may be misunderstanding but are you putting header("Location: main.php"); in the middle of you script?
$projectid=mysql_insert_id($connection);
I called this after my first query, this will get the AutoIncrement value from your projects table and store it in $projectid, then the second query will use it.
so after execution of my first query, I put the above code there, without changing anything else!!
You seem to be trying to execute mysql_query() only once. You have two queries, so it needs to be used twice, once on each query:
$sql = "INSERT INTO projects (projectid, projectname, projectdeadline, projectdetails) VALUES
('{$projectid}','{$projectname}','{$projectdeadline}','{$projectdetails}')";
$result = mysql_query($sql, $connection)
or die("MySQL Error: ".mysql_error());
$sql = "INSERT INTO usersprojects (userid, projectid) VALUES
('{$userid}','{$projectid}')";
$result = mysql_query($sql, $connection)
or die("MySQL Error: ".mysql_error());
Alternatively, you could use mysqli_multi_query(), but that might require a significant rewrite of your code to use the mysqli interface.

SQL_CALC_FOUND_ROWS / FOUND_ROWS() does not work in PHP

I use SQL_CALC_FOUND_ROWS in Mysql SELECT statement, to get the number of lines my SELECT would return without a LIMIT clause.
$sql = new mysqli('localhost', 'root', '');
$sql->select_db('mysql');
$s1 = $sql->query('select SQL_CALC_FOUND_ROWS * from db limit 0, 3');
$s2 = $sql->query('select FOUND_ROWS()');
if($row = $s2->fetch_row()) printf('%d/%d', $s1->num_rows, $row[0]);
On my WinXP dev station it return 3/0 everytime for several weeks. When I use another MySQL server from my station it return 3/0 too.
On anothers PC the same code runs fine, and return the correct number (3/17 for example, if I have 17 records in mysql.db table). Every XP PC have the same PHP/Mysql version, and it ran fine in the past on my PC
Using Mysql Query Browser with the same SQL queries I get the right number.
Could anyone give me an idea of solution, without re-install all?
Sorry, my previous request was awfully unclear.
Thank you.
When I ran something analogous to your example on the mysql command line, it would work; but running it from php, it failed. The second query has to "know about" the first one, so I figure somehow that persistence/memory linking the two queries was getting messed up by the php.
(It turns out that Wordpress uses this type of query to do its pagination - so our larger problem was that the pagination in a wordpress install suddenly stopped working when we moved to php 5.2.6 ... eventually tracked it down to the FOUND_ROWS()).
Just for the sake of posting for people who may run into this in the future... for me it was the php setting "mysql.trace_mode" - this defaulted "on" in 5.2.6 instead of "off" like previously, and for some reason prevents the FOUND_ROWS() from working.
As a "fix", we could either put this in every php page (actually, in a common "include"):
ini_set("mysql.trace_mode", "0");
or add this to the .htaccess:
php_value mysql.trace_mode "0"
Thanks again,
Jerry
Are you using a MySQL query method that allows for multiple queries.
From MySQL documentation.
To obtain this row count, include a SQL_CALC_FOUND_ROWS option in the SELECT statement, and then invoke FOUND_ROWS() afterward
Example:
mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name
-> WHERE id > 100 LIMIT 10;
mysql> SELECT FOUND_ROWS();
Also just for fun, there's a great discussion about the race condition of FOUND_ROWS()'s usage here.
Another way would be to use mysqli_multi_query as stated in the PHP manual by passing both queries containing SQL_CALC_FOUND_ROWS and FOUND_ROWS separated with a semicolon
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT SQL_CALC_FOUND_ROWS * FROM db limit 0, 3;";
$query .= "SELECT FOUND_ROWS()";
/* execute multi query */
if ($mysqli->multi_query($query)) {
do {
/* store first result set */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
$result->free();
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
}
/* close connection */
$mysqli->close();
?>
The quickest solution is to subquery your actual query like this:
SELECT SQL_CALC_FOUND_ROWS * FROM (SELECT whatever FROM whatever WHERE whatever LIMIT whatever) ax;
select FOUND_ROWS();
Now you will get the correct results. I think the main reason being that SQL_CALC_FOUND_ROWS mainly tracks rows found (i.e. without LIMITS) not rows returned.
I had the same issue. The solution was stupid, I was using $wpdb->query instead of $wpdb->get_var. So you want to do
$wpdb->get_var('select FOUND_ROWS()');
if you're on WordPress
Well, it was a problem with mysql php extension bundled with php 5.2.6. Mysqli run fine, and another php version too.
Sorry for noise and unclear question.
If you have the same problem, my advice is to re-install PHP or change version.

Categories