Going by the advice that join are better than nested queries, I've converted all my nested queries to join. However, upon converting to join, I'm unable to retrieve data into my array from the SQL result.
Here are my queries :
Without join
$a="SELECT F_DATE, COUNT(F_DATE) as COUNT_F
from FWH
where FI_NAME IN
(
SELECT I_NAME from INS_W WHERE INSTANCE_ID IN
(
SELECT I_MAP_ID FROM T_MAP where T_MAP_ID =
(
SELECT T_ID FROM TWY WHERE T_NAME = 'abc'
)
)
)
AND F_DATE between '$S_D' AND '$E_D'
GROUP BY F_DATE";
With join
$a="SELECT t1.F_DATE AS DATE_F, COUNT(t1.F_DATE) as COUNT_F
from FWH t1
JOIN INS_W t2 ON(t1.FI_NAME = t2.I_NAME)
JOIN T_MAP t3 ON(t2.INSTANCE_ID = t3.I_MAP_ID)
JOIN TWY t4 ON(t3.T_MAP_ID = t4.T_ID)
WHERE t4.T_NAME = 'abc' AND
t1.F_DATE BETWEEN '$S_D' AND 'E_D'GROUP BY t1.F_DATE";
Here's the PHP code to retrieve data
$link = mysql_connect("ip", "user", "passs");
$dbcheck = mysql_select_db("db");
if ($dbcheck) {
$chart_array_1[] = "['F DATE','F COUNT']";
$result = mysql_query($a);
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$f_date=$row["DATE_F"];
$f_count=$row["COUNT_F"];
$chart_array_1[]="['".$f_date."',".$f_count."]";
}
}
}
mysqli_close($link);
The SQL queries themselves run fine when tested directly on MySQL DB.
For some reason, when I use joins, I'm forced to use row[0], row[1] etc instead of fetching values using the name of column. I do not understand the reason behind this. However, this is the only way out in my case. Code below for those who may get stuck in a similar situation as me.
$link = mysql_connect("ip", "user", "passs");
$dbcheck = mysql_select_db("db");
if ($dbcheck) {
$chart_array_1[] = "['F DATE','F COUNT']";
$result = mysql_query($a);
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$chart_array_1[]="['".$row[0]."',".$row[1]."]";
}
}
}
mysqli_close($link);
Related
I have checked all previous versions of this question and in those cases it was evident as to why it wasn't working but when I query my database it is returning no rows. There is only one row right now so I am completely confused as to why the query returns empty. Any advice would be helpful.
$prodSQL = "SELECT * FROM products INNER JOIN shopPage ON products.storePage_id = shopPage.storePage_id
INNER JOIN gallery ON products.gallery_id = gallery.gallery_id
INNER JOIN image ON products.image_id = image.image_id WHERE products.storePage_id = ".$_GET['shop_id'];
$productInfo = $conn->query($prodSQL) or die ("Couldn't execute query: ".mysqli_error($prodSQL));
$row = $productInfo->fetch_assoc();
$gallery_id = $row['gallery_id'];
$mainTitle = $row['storePage_title'];
if($productInfo->num_rows === 0)
{
echo 'No results';
}
$productInfo->close();
I have the following code:
// db connection info set up earlier
$sql= "SELECT `TABLE_1.ID`, `TABLE_2.ID`, `POTATO` FROM `TABLE_1.ID` LEFT JOIN `TABLE_2` ON `TABLE_1`.`ID` = `TABLE_2`.`ID_OF_OTHER_TABLE`;";
$rows = mysqli_query($connection, $sql);
foreach ($rows as $row){
$potato = $row["POTATO"];
$id = $row["TABLE_2.ID"];
}
I can't get TABLE_2.ID. I've tried to doing a print_r to get the proper format, but it says it's a mysqli object and I don't get much more info than that. However, I can get potato. So I'm guessing it's a calling syntax issue, but I've searched multiple sites (stack and google included) and not found a clear answer. So, what do I need to do instead of
$id = $row["TABLE_2.ID"];
?
Assign aliases to the columns with the same name.
$sql= "SELECT `TABLE_1`.`ID` AS t1_id, `TABLE_2`.`ID` AS t2_id, `POTATO`
FROM `TABLE_1.ID`
LEFT JOIN `TABLE_2` ON `TABLE_2`.`ID_OF_OTHER_TABLE` = `TABLE_1`.`ID`;";
$rows = mysqli_query($connection, $sql);
foreach ($rows as $row){
$potato = $row["POTATO"];
$id = $row["t2_id"];
}
You can't left join a table with itself, you also cannot have a table that isn't joined = something from another table that cannot be joined to itself.
This will work:
// db connection info set up earlier
$sql= "SELECT TABLE_1.ID, TABLE_2.ID, POTATO
FROM
TABLE_1.ID
LEFT JOIN TABLE_2 ON TABLE_1.ID = TABLE_2.ID";
$rows = mysqli_query($connection, $sql);
while ($row = mysqli_fetch_assoc($rows)) {
echo ($row['ID']);
}
mysql_free_result($rows);
I am using a code something like below to get data from the second table by matching the id of first table. Code is working well, but I know it slow down the performance, I am a new bee. Please help me to do the same by an easy and correct way.
<?php
$result1 = mysql_query("SELECT * FROM table1 ") or die(mysql_error());
while($row1 = mysql_fetch_array( $result1 ))
{
$tab1_id = $row1['tab1_id'];
echo $row['tab1_col1'] . "-";
$result2 = mysql_query("SELECT * FROM table2 WHERE tab2_col1='$tab1_id' ") or die(mysql_error());
while( $row2 = mysql_fetch_array( $result2 ))
{
echo $row2['tab2_col2'] . "-";
echo $row2['tab2_col3'] . "</br>";
}
}
?>
You can join the two tables and process the result in a single loop. You will need some extra logic to check if the id of table1 changes, because you'll only want to output this value when there's a different id:
<?php
// Join the tables and make sure to order by the id of table1.
$result1 = mysql_query("
SELECT
*
FROM
table1 t1
LEFT JOIN table2 t2 ON t2.col1 = t1.id
ORDER BY
t1.id") or die(mysql_error());
// A variable to remember the previous id on each iteration.
$previous_tab1_id = null;
while($row = mysql_fetch_array( $result1 ))
{
$tab1_id = $row['tab1_id'];
// Only output the 'header' if there is a different id for table1.
if ($tab1_id !== $previous_tab1_id)
{
$previous_tab1_id = $tab1_id;
echo $row['tab1_col1'] . "-";
}
// Only output details if there are details. There will still be a record
// for table1 if there are no details in table2, because of the LEFT JOIN
// If you don't want that, you can use INNER JOIN instead, and you won't need
// the 'if' below.
if ($row['tab2_col1'] !== null) {
echo $row['tab2_col2'] . "-";
echo $row['tab2_col3'] . "</br>";
}
}
Instead of having 2 while loops, what you can do is join the 2 tables and then iterate over the result.
If you're not sure what join is look here: https://dev.mysql.com/doc/refman/5.1/de/join.html
Also here is a fairly simple query written using join: Join Query Example
You can use this. One relation with two tables:
<?php
$result1 = mysql_query("SELECT tab2_col2, tab2_col3 FROM table1, table2 where tab2_col1 = tab1_id ") or die(mysql_error());
while($row1 = mysql_fetch_array( $result1 ),)
{
echo $row2['tab2_col2'] . "-";
echo $row2['tab2_col3'] . "</br>";
}
?>
Like Sushant said, it would be better to use one JOIN or simpler something like that:
SELECT * FROM table1, table2 WHERE `table1`.`id` = `table2`.`id
I am currently trying to get a data(M_Name) from a table called Merchant.
Following are my codes:
<?php
$response = array();
$link = mysql_connect('localhost','root','') or die ('Could not connect: '.mysql_error());
mysql_select_db('ichop') or die ('Could not connect to database');
$result = mysql_query("select * from offer") or die(mysql_error());
if(mysql_num_rows($result) > 0){
$response["offers"] = array();
while($row = mysql_fetch_array($result)){
$offer = array();
$offer["offer_id"] = $row["Offer_ID"];
$offer["start_date"] = $row["Start_Date"];
$offer["end_date"] = $row["End_Date"];
$offer["o_desc"] = $row["O_Desc"];
$offer["short_desc"] = $row["Short_Desc"];
$offer["merchant_ID"] = $row["Merchant_ID"];
$offer["m_name"] = mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'");
array_push($response["offers"], $offer);
}
$response["success"] = 1;
echo json_encode($response);
} else {
//no offer found
$response["success"] = 0;
$response["message"] = "No offer found";
echo json_encode($response);
}
?>
When I run this PHP file using web browser, I couldn't get the desired name for the merchant even though the data is there in the database...it would just return me "null".
{"offers":[{"offer_id":"1","start_date":"2013-05-17","end_date":"2013-05-18","o_desc":"AAA","merchant_ID":"2","m_name":null}],"success":1}
What have I done wrong or what am I still missing? Please help..thanks!
I would rather use LEFT JOIN mysql function and get all relevant data at first query from both of your tables
SELECT * FROM offer a LEFT JOIN MERCHANT b ON a.Merchant_ID = b.MERCHANT_ID
so you won't have to make any extra query and you can store your value directly in your array
$offer["m_name"] = $row['M_Name'];
Then I would like you to remember that mysql_* functions are deprecated so i would advise you to switch to mysqli or PDO
The mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'"); does not return a value from the DB, you need to follow it up with for example mysql_fetch_array like you did with the other query to the DB.
There is a solution more simple: use a JOIN, which combines two tables.
SELECT offer.*, MERCHANT.M_Name
FROM offer
LEFT JOIN MERCHANT ON(MERCHANT.MERCHANT_ID = offer.merchant_ID)
look like you have to return an result from query instead of while,
mysql_fetch_array(mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'"));
but had better you make some error hadling first
You can use below one
$resMerchant = mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'");
$rowMerchant = mysql_fetch_assoc($resMerchant);
$offer["m_name"] = $rowMerchant['M_Name'];
$offer["m_name"] = mysql_query("SELECT M_Name FROM MERCHANT WHERE MERCHANT_ID = '".$row["merchant_ID"]."'")
mysql_query() does not return a string but a resource. You'll have to fetch the result.
Also, don't forget that mysql_* is now deprecated.
[edit]
As stated by Fabio, you'd rather use JOIN on your query. At the moment, you are making a request in your loop. That's useless (INNER JOIN or LEFT JOIN are what you want) and very resource consumming.
I have some PHP/MySQL code that pulls data from multiple different tables (using Inner Joins). It looks something like this:
$query = "SELECT * FROM table1 INNER JOIN table2 USING (key)";
$data = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($data)) {
echo $row[1];
}
So the code is simple enough, but what I want to do is echo the table each row is in inside of that while loop, since it could be in one of 2 tables.
I saw there was some old mysql functions like mysql_field_table and mysql_tablename that would do the trick, but they all seem to be deprecated.
Would appreciate any advice on how to accomplish this.
You could select the data with a special identifier for each table instead of using *
select table1.row1 as t1r1, table2.row1 as t2r1,..... from .....
And inside php you could look for the strings t1 and t2 and do stuff accordingly.
What you can do is echo more than one field from your result table (which hopefully now contains information from both the tables.
$query = "SELECT * FROM table1 INNER JOIN table2 USING (key)";
$data = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($data))
{
echo $row[1] . " " . $row[2];
}
...and then $row[3] etc...
Or access the column name/field by the column name or alias provided by AS.
$query = "SELECT * FROM table1 INNER JOIN table2 USING (key)";
$data = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_assoc($data))
{
echo $row["c_name1"] . " " . $row["c_name2"];
}
Where "c_name1" and "c_name2" are your column names.
Use an AS keyword to rename all columns.
$select_clause = '';
$tables = array('tblA', 'tblB');
foreach($tables as $tbl) {
mysql_query('SHOW COLUMNS FROM ' . $tbl);
while ($row = mysql_fetch_assoc())
$select_clause .= '`'.$tbl.'`.`'.$row['Field'].'` AS `'.$tbl
.'_'.$row['Field'].'`,';
}
$select_clause = substr($select_clause, 0, -1);
mysql_query('SELECT '.$select_clause.' FROM /*...*/ ');