Select from multiple sql-databases using one query - mysql

Currently I will use two queries to select data from different databases.
Here´s the main sections from the code..
query from database 1
mysql_select_db("data1");
mysql_select_db("data2");
//bought databases connected
$query1 = "select * from ex.1 where value1='".$value1."' and value2='".$value2."' order by number ASC;";
$run1 = mysql_query($query1);
query from database 2
$query2= " select * from ex.2 where value1='".$value1."' and value2='".$value2."' order by number ASC;";
$run2 = mysql_query($query2);
Both tables in different databases will include same information from the strings "$value1" and "$value2".
I would like to combine these two strings in one query. Meaning that all information from two different databases will be selected.
I tried to use JOIN the following way:
$query = "select * from database1.ex.1 JOIN database2.ex.2 where value1='".$value1."' and value2='".$value2."' order by number ASC;";
$run = mysql_query($query);
but no success..
Meaning from all this is that I would like to echo mysql-data to the same table from two different database.
while ($row=mysql_fetch_array($run)){
echo '</tr><td>'.($row['something']).'</td><td>'.($row['more']).'</td><td>'.($row['and more']).'</td><td>'.($row['and more']).'</td><td>'.($row['and something from the database2']);
This way all information should be echoed nicely, following the few strings which will found from both databases.
Is this understandable?

Instead of using mysql_* for your PHP scripts, you should use MySQLI as mysql is being deprecated.
$db = new mysqli(host, user, password, database;
You should also escape the strings to be more secure and check to see if the connection has been successful as well:
$dbhost = "xxx.xxx.xxx.xxx";
$dbuser = "xxxxxxx";
$dbpass = "xxxxxx";
$dbbase = "xxxxxx";
$db = new mysqli($dbhost, $dbuser, $dbpass, $dbbase);
if($db->connect_errno) {
die('Could not connect to the database: ' . $db->connect_error);
}
You can follow this and repeat for multiple databases!

You have the join part right, but you have got the clause where instead of on:
$query = "SELECT * FROM database1.ex.1 as db1 JOIN database2.ex.2 as db2
ON(db1.value1='".$value1."' and db2.value2='".$value2."') order by number ASC;";
You can change db1.value1/db1.value2 for db2.whatever.

Related

Codeigniter - how to delete row on inner join? [duplicate]

I have a problem with my query and I need to join two tables from different databases now my problem is how can I execute my query. I got my syntax format from here
Please visit first this link so you could understand why my SQL syntax is like this http://www.x-developer.com/php-scripts/sql-connecting-multiple-databases-in-a-single-query
Im using CodeIgniter and here is an Idea of what my query looks like: Notice the way I'm selecting my columns: DATABASE_NAME.TABLE_NAME.COLUMN_NAME
$ENROLLEES = $this->load->database('ENROLLEES', TRUE);
$ACCOUNTS = $this->load->database('ACCOUNTS', TRUE);
$SELECT = "SELECT $ACCOUNTS.BALANCES_TABLE.IDNO, $ACCOUNTS.BALANCES_TABLE.balance";
$FROM = "FROM $ACCOUNTS.BALANCES_TABLE";
$WHERE = "$ACCOUNTS.BALANCES_TABLE.IDNO IN (SELECT $ENROLLEES.ENROLLEES_TABLE.IDNO FROM $ENROLLEES.ENROLLEES_TABLE)";
$SQL = $SELECT ." ". $FROM ." ". $WHERE;
MAIN PROBLEM: How to Execute my query?
If we do like this in codeIgniter:
$ENROLLEES->query($SQL); or $ACCOUNTS->query($SQL);
How can I execute my query that Im having multiple databases? What will I provide here[database]->query($SQL); ?
$sql="Select * from my_table where 1";
$query = $this->db->query($SQL);
return $query->result_array();
If the databases share server, have a login that has priveleges to both of the databases, and simply have a query run similiar to:
$query = $this->db->query("
SELECT t1.*, t2.id
FROM `database1`.`table1` AS t1, `database2`.`table2` AS t2
");
Otherwise I think you might have to run the 2 queries separately and fix the logic afterwards.
I can see what #Þaw mentioned :
$ENROLLEES = $this->load->database('ENROLLEES', TRUE);
$ACCOUNTS = $this->load->database('ACCOUNTS', TRUE);
CodeIgniter supports multiple databases. You need to keep both database reference in separate variable as you did above. So far you are right/correct.
Next you need to use them as below:
$ENROLLEES->query();
$ENROLLEES->result();
and
$ACCOUNTS->query();
$ACCOUNTS->result();
Instead of using
$this->db->query();
$this->db->result();
See this for reference:
http://ellislab.com/codeigniter/user-guide/database/connecting.html
http://www.bsourcecode.com/codeigniter/codeigniter-select-query/
$query = $this->db->query("select * from tbl_user");
OR
$query = $this->db->select("*");
$this->db->from('table_name');
$query=$this->db->get();
return $this->db->select('(CASE
enter code hereWHEN orderdetails.ProductID = 0 THEN dealmaster.deal_name
WHEN orderdetails.DealID = 0 THEN products.name
END) as product_name')
$this->db->select('id, name, price, author, category, language, ISBN, publish_date');
$this->db->from('tbl_books');

I am trying to replace :search when the query is executed but it does not seem to be replaced

After reviewing this SO, I am having some trouble using prepared statements.
I have added the following to my db connection:
$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
And here are my query statements:
$query = "SELECT schedules.schedule_name, users.name, schedules.schedule_id
FROM schedules
INNER JOIN users
ON schedules.admin_id=users.user_id
WHERE schedules.schedule_name
LIKE '%:search%'
ORDER BY schedules.schedule_name";
$stmt = $db->prepare($query);
$result = $stmt->execute(array('search' => $search_string));
$search_results = $stmt->fetchAll();
As you can see in the LIKE, I am trying to replace :search when the query is executed but it does not seem to be replaced.
When you do a parameterized query, it is not simply a string replace, and you don't surround it with singlequotes:
$query = "SELECT schedules.schedule_name, users.name, schedules.schedule_id
FROM schedules
INNER JOIN users
ON schedules.admin_id=users.user_id
WHERE schedules.schedule_name
LIKE :search
ORDER BY schedules.schedule_name";
But you want to have % wildcards around the term right? Add them when you inject it:
$result = $stmt->execute(array('search' => '%' . $search_string . '%' ));

merge multiple sql queries

In the header of the pages of my site, I have multiple SQL queries. For example:
$sql_result = mysql_query("SELECT blah2 FROM misc WHERE id='1'", $db);
$rs = mysql_fetch_array($sql_result); $blah2 = $rs[blah2];
$sql_result = mysql_query("SELECT * FROM ip_bans WHERE IP='$ip'", $db);
if (mysql_num_rows($sql_result) != 0) { header("Location: banned.php"); }
$sql_result = mysql_query("SELECT * FROM accounts WHERE username='$un' AND pw='$pw'", $db);
$rs = mysql_fetch_array($sql_result);
// do all account login check etc
$sql_result = mysql_query("SELECT * FROM members WHERE id='$id'", $db);
$rs = mysql_fetch_array($sql_result);
// get members data
..and more.
All this info is needed for each page of my site. Is there a way to combine these, or just limit the ammount of queries? I'd imagine this would get quite intensive on the database over time.
I'm not too good with JOINs and things, is that what i need?
You want to use UNION.
Here is a good tutorial: http://www.tizag.com/sqlTutorial/sqlunion.php
I would recommend you to only use it where it's "natural" and not merge to many different queries.

How to append a mysql table to another table in a different database

I would like to grab a table from one database and append this data to a table in another database. However, they have similar numbers (including the id) which need to be updated before they can be copied over. Is there a function available that could do this automatically? Or do I need to write a script in between?
So far I've got:
#!/bin/sh
mysqldump -uuser1 -ppw1 database1 table1 > /home/user/public_html/database1.sql --skip-add-drop-table --skip-create-options
mysql -uuser2 -ppw2 database2 < /home/user/public_html/database1.sql
rm /home/user/public_html/database1.sql
You could select from one table and insert it into another. The results will be "appended" to the original data.
insert into new_table (id, name) select old_id, old_name from old_table;
To append a table from one database to a table from an other database
insert into new_database.new_table (id, name) select old_id, old_name from old_database.old_table;
Sounds like something that would be a lot safer to do via script, which seems simple enough - just grab the data from the first DB and perform batch inserts into the other, letting mysql handle the ids itself. This should take about 10-30 LOC in any descent scripting language, and gives you more control over the outcome.
I solved it by creating a php script that creates new connections for each new database. This script empties the main table first before it will append the data of the other tables. Having the first entry on NULL and having the $row[x] start on 1 makes sure it appends.. Don't know if it's the best solution, but it works.
<?php
$db_user = "database_all_usr";
$db_pw = "";
$db_database = "database_all_db";
mysql_connect("localhost", $db_user, $db_pw) or die(mysql_error());
mysql_select_db($db_database) or die(mysql_error());
$sql = "TRUNCATE TABLE table_all";
mysql_query($sql) or die(mysql_error());
copy_table("database1_db","database1_usr","",$db_database,$db_user,$db_pw);
copy_table("database2_db","database2_usr","",$db_database,$db_user,$db_pw);
function copy_table($db_current,$db_user_current,$db_pw_current,$db_host,$db_user_host,$db_pw_host){
mysql_connect("localhost", $db_user_current, $db_pw_current) or die(mysql_error());
mysql_select_db($db_current) or die(mysql_error());
$sql = "SELECT * FROM table";
$result = mysql_query($sql) or die(mysql_error());
mysql_connect("localhost", $db_user_host, $db_pw_host) or die(mysql_error());
mysql_select_db($db_host) or die(mysql_error());
while ($row = mysql_fetch_row($result)) {
$sql = "INSERT INTO table_all VALUES (NULL, '$row[1]', '$row[2]')"; //adapt to the amount of columns
mysql_query($sql) or die(mysql_error());
}
}
?>

Connect to a MySQL database and count the number of rows

I need to connect to a MySQL database and then show the number of rows. This is what I've got so far;
<?php
include "connect.php";
db_connect();
$result = mysql_query("SELECT * FROM hacker");
$num_rows = mysql_num_rows($result);
echo $num_rows;
?>
When I use that code I end up with this error;
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in C:\Documents and Settings\username\Desktop\xammp\htdocs\news2\results.php on line 10
Thanks in advance :D
You would probably be better of asking the database to aggregate the number of rows instead of transferring them all to php and doing the counting there.
SELECT COUNT(*) FROM hacker
take a habit to run all queries this way:
$sql = "SELECT * FROM hacker";
$res = mysql_query($query) or trigger_error(mysql_error().$sql);
and you will always have comprehensive error information
and take appropriate corrections
also, as it was mentioned above, the only reliable way to count rows is SELECT count(*) query
$sql = "SELECT count(*) FROM hacker";
$res = mysql_query($query) or trigger_error(mysql_error().$sql);
$row = mysql_fetch_row($res);
$count = $row[0];
change your code as following:
$result = mysql_query("SELECT * FROM hacker");
echo mysql_error();
You have an SQL-Error or your not connected to the database