merge multiple sql queries - mysql

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.

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');

Select from multiple sql-databases using one query

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.

Which one is Faster, SUB-Query or IN-Query?

If I want to select whether i am following the threads or not.
I have two approaches to do so... but I don't know which one would be more better in terms of performance and speed. Can anyone help me out?
Approach 1
$cui = $_SESSION['user_id'];
$data = mysqli_query($con,"
SELECT t.*,( select count(follow_id) from follows where object_id =
t.thread_id AND object_type='thread' AND user_id = $cui) as me_follow FROM threads t
");
while($row = mysqli_fetch_assoc($data)){
/*
$row['me_follow'] = 0 if i aint following
$row['me_follow'] = 1 if i am following
*/
}
Approach 2
$cui = $_SESSION['user_id'];
$data = mysqli_query($con,"SELECT * FROM threads");
$ids = array();
while($row = mysqli_fetch_assoc($data)){
$ids[] = $row['thread_id'];
}
$ids = join($ids,",");
$data = mysqli_query($con,"SELECT COUNT(*) FROM follows WHERE object_id IN($ids) AND user_id = $cui");
One round-trip wins over two. This is because there is some overhead in sending SQL to the server, having it parse it, execute it and send the results back. It is (usually) better to do everything in one round-trip.

Echo value from id using another query?

as a php noob im teaching myself but have hit a little problem and could use a helping hand please.
I'm currently making a query to tbl_products to grab info as follows:
$mysql_hostname = "localhost";
$mysql_user = "hidden";
$mysql_password = "hidden";
$mysql_database = "hidden";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Oops some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Oops some thing went wrong");// we are now connected to database
$result = mysql_query("SELECT * FROM tbl_products ORDER BY bankIds"); // selecting data through mysql_query()
while($data = mysql_fetch_array($result))
{
echo ''.$data['bankIds'].'|'.strip_tags($data['sku']).'|'.strip_tags($data['productTitle']).'|'.strip_tags($data['productTitle']).'|'.strip_tags($data['prodDesc']).'|'.strip_tags($data['seed']).',http://cdn.shopify.com/s/files/1/0709/2915/files/'.strip_tags($data['productImg']).'<br/>';
}
That works fine, but now i want to display the name of ['bankIds'] by making another query (if needed) to the table named "tbl_seedBank".
tbl_seedBank
id
bankTitle
At the moment "$data['bankIds']" will echo out the id number, i want to be able to grab the bankTitle from the id and echo it out instead of the id number...
Hope this makes sencse lol
Thank you so much for taking the time to read about my problem.
~ Rory
you can use the Inner Join for it..
try by executing below query
$result = mysql_query("SELECT a.bankIds,a.sku,a.productTitle,a.productTitle,a.prodDesc,a.seed ,a.productImg,b.bankTitle FROM tbl_products a JOIN tbl_seedBank b ON a.bankIds=b.id ORDER BY bankIds");
if i understand correct you need to make a join in your query
SELECT * FROM tbl_products ORDER BY bankIds INNER JOIN tbl_seedBank ON tbl_seedBank = bankIds
see more:
http://dev.mysql.com/doc/refman/5.0/en/join.html

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