mysql multiple tables query command to php array - getting error - php

Below is my SQL Query which i am able to run successfully in PhpMyAdmin .
[ data from multiple tables similar to IMDB database ]
SELECT
`data`.`code`,
`data`.`movie`,
`movies`.`id`,
`movies`.`name`,
`data`.`person`,
`persons`.`name`,
`persons`.`code`,
`data`.`mode`,
`modes`.`name`
FROM
`data`
INNER JOIN `movies` ON (`data`.`movie` = `movies`.`id`)
INNER JOIN `persons` ON (`data`.`code` = `persons`.`code`)
INNER JOIN `modes` ON (`data`.`mode` = `modes`.`code`)
where `data`.`movie`=1
Below is PHP CODE generated by PhpMyAdmin (create PHP Code button) from above command but not fetching any results when used in PHP page (webpage) ,
$sql = "SELECT \n"
. " `data`.`code`,\n"
. " `data`.`movie`,\n"
. " `movies`.`id`,\n"
. " `movies`.`name`,\n"
. " `data`.`person`,\n"
. " `persons`.`name`,\n"
. " `persons`.`code`,\n"
. " `data`.`mode`,\n"
. " `modes`.`name`\n"
. "FROM\n"
. " `data`\n"
. " INNER JOIN `movies` ON (`data`.`movie` = `movies`.`id`)\n"
. " INNER JOIN `persons` ON (`data`.`code` = `persons`.`code`)\n"
. " INNER JOIN `modes` ON (`data`.`mode` = `modes`.`code`)\n"
. "where `data`.`movie`=1 LIMIT 0, 30 ";

Try
$sql = "SELECT
`data`.`code`,
`data`.`movie`,
`movies`.`id`,
`movies`.`name`,
`data`.`person`,
`persons`.`name`,
`persons`.`code`,
`data`.`mode`,
`modes`.`name`
FROM
`data`
INNER JOIN `movies` ON (`data`.`movie` = `movies`.`id`)
INNER JOIN `persons` ON (`data`.`code` = `persons`.`code`)
INNER JOIN `modes` ON (`data`.`mode` = `modes`.`code`)
where `data`.`movie`=1";
The \n and . from your question are not required.

Related

Using WHERE clause with multiple left join in php

I successfully did a LEFT JOIN using PHP, however, I am having a little difficulty adding a WHERE clause to enable me select unique record from all existing details in all the tables where a match is found.
This is my code :
<?php
$sql = "SELECT staff.*, staff_bio.bio_id, staff_cert.*, staff_edu.*, staff_pos.*, staff_res.*\n"
. " FROM staff staff\n"
. "LEFT JOIN staff_bio \n"
. " ON staff.nuc_id = staff_bio.bio_id\n"
. "LEFT JOIN staff_cert\n"
. " ON staff.nuc_id = staff_cert.pro_id\n"
. "LEFT JOIN staff_edu\n"
. " ON staff.nuc_id = staff_edu.edu_id\n"
. "LEFT JOIN staff_pos\n"
. " ON staff.nuc_id = staff_pos.rank_id\n"
. "LEFT JOIN staff_res\n"
. " ON staff.nuc_id = staff_res.res_id\n"
. "WHERE staff.nuc_id = $userRow['staff_no'] ";//this is where i'm having issues
?>
My final output should be something like :
<?php echo $userRow['sch_name']; ?>
<?php echo $userRow['fac_name']; ?>
<?php echo $userRow['dep_name']; ?>
All coming from different tables. Any help will be greatly appreciated.
You can do like this:
. " WHERE staff.nuc_id = ".$userRow['staff_no'] ;//this is where i'm having issues
Why do you need to concatenate query, it can be written as if you want formatting :
<?php
$sql = "SELECT staff.*, staff_bio.bio_id, staff_cert.*, staff_edu.*, staff_pos.*, staff_res.*
FROM staff staff
LEFT JOIN staff_bio
ON staff.nuc_id = staff_bio.bio_id
LEFT JOIN staff_cert
ON staff.nuc_id = staff_cert.pro_id
LEFT JOIN staff_edu
ON staff.nuc_id = staff_edu.edu_id
LEFT JOIN staff_pos
ON staff.nuc_id = staff_pos.rank_id
LEFT JOIN staff_res
ON staff.nuc_id = staff_res.res_id
WHERE staff.nuc_id = ".$userRow['staff_no'];//this is where i'm having issues
?>

Select query returning 1 result instead of 3 because of AVG

The select query below returns 1 row when it should be 3. I am pretty sure it is because of the AVG(k.sumtotal) field.
If I rewrite the query and take out that AVG(k.sumtotal) column and take out the FROM inv_ratings AS k, I get my 3 rows.
I can't figure out why this table (inv_ratings) or this AVG(k.sumtotal) column restrict the number of rows to 1. I looked online for hours trying to find information about returning results using the AVG clause and didn't find much. Do I have to use a group by clause, I tried that and only get errors.
$p = "SELECT i.invention_id, i.inv_title, i.date_submitted, i.category_id,"
. " i.approved, c.category_id, c.category, u.image_name, AVG(k.sumtotal)"
. " FROM inv_ratings AS k INNER JOIN inventions AS i USING (invention_id)"
. " INNER JOIN categories AS c USING (category_id)"
. " INNER JOIN images AS u USING (invention_id)"
. " WHERE c.category_id = $cat AND i.approved = 'approved'"
. " HAVING u.image_name < 2"
. " ORDER BY date_submitted"
. " DESC LIMIT $start, $display";
$q = mysqli_query($dbc, $p) or trigger_error("Query: $p\n<br />mysqli Error: " . mysqli_error($dbc));
You are running into one of MySQL's gotchas:
http://dev.mysql.com/doc/refman/5.5/en/group-by-handling.html
I hate that MySQL ever allows this syntax because it only causes confusion. But what you probably want is (to use MySQL's hackish behavior, please note that if there are multiple values for any of the fields besides invention_id or sumtotal, you get a random value from that column):
$p = "SELECT i.invention_id, i.inv_title, i.date_submitted, i.category_id,"
. " i.approved, c.category_id, c.category, u.image_name, AVG(k.sumtotal)"
. " FROM inv_ratings AS k INNER JOIN inventions AS i USING (invention_id)"
. " INNER JOIN categories AS c USING (category_id)"
. " INNER JOIN images AS u USING (invention_id)"
. " WHERE c.category_id = $cat AND i.approved = 'approved'"
. " GROUP BY i.invention_id "
. " HAVING u.image_name < 2"
. " ORDER BY date_submitted"
. " DESC LIMIT $start, $display";
Or, to not use MySQL's hackish behavior:
$p = "SELECT i.invention_id, i.inv_title, i.date_submitted, i.category_id,"
. " i.approved, c.category_id, c.category, u.image_name, AVG(k.sumtotal)"
. " FROM inv_ratings AS k INNER JOIN inventions AS i USING (invention_id)"
. " INNER JOIN categories AS c USING (category_id)"
. " INNER JOIN images AS u USING (invention_id)"
. " WHERE c.category_id = $cat AND i.approved = 'approved'"
. " GROUP BY i.invention_id, i.inv_title, i.date_submitted, i.category_id,"
. " i.approved, c.category_id, c.category, u.image_name "
. " HAVING u.image_name < 2"
. " ORDER BY date_submitted"
. " DESC LIMIT $start, $display";

Data from different tables have the same name, how to retrieve data?

Here is my code:
$sql = "SELECT table1.Insert_ID, table1.Type, table1.Date "
. "table2.User, table2.Date "
. "FROM Insert AS table1 "
. "INNER JOIN Contact AS table2 ON table2.Contact_ID = table1.Contact_ID";
$x =0;
while($row = odbc_fetch_array($res)){
$x++;
$values= ($x . ": " . " Insert ID:". $row['Insert ID'] . " Date Created: " . $row['Date'] . " Date Modified:" . "\n");
print($values);
}
I want Date from both table1 and table2, how do I proceed to retrieve the data if they both have the same name?
Use an alias.
SELECT table1.Insert_ID, table1.Type, table1.Date as Date1 "
. "table2.User, table2.Date as Date2 "
. "FROM Insert AS table1 "
. "INNER JOIN Contact AS table2 ON table2.Contact_ID = table1.Contact_ID";
Column aliases.
$sql = "SELECT table1.Insert_ID, table1.Type, table1.Date as T1Date "
. "table2.User, table2.Date as T2Date"
. "FROM Insert AS table1 "
. "INNER JOIN Contact AS table2 ON table2.Contact_ID = table1.Contact_ID";

PHP MySQL - Inner Join only if not null

I have a mysqli SELECT query that is using an Inner Join and I noticed a big problem: it doesn't select rows where the column value for the condition is null (because NULL doesn't exist in the second table). Here's my code:
<?php
$sql = mysqli_connect(/* CONNECTION */);
$query = "SELECT " .
"e.EQUIPMENT_ID, " .
"e.CUSTOMER_ID, " .
"e.DESCRIPTION, " .
"e.LOCATION, " .
"e.JOB_SITE, " .
"e.PROJECT_NAME, " .
"jb.DESCRIPTION AS JOB_SITE_NAME " .
"FROM equipments e " .
"INNER JOIN jobsites jb ON jb.JOBSITE_ID = e.JOB_SITE " .
"WHERE e.CUSTOMER_ID = 1 ".
"ORDER BY e.EQUIPMENT_ID ASC";
$results = mysqli_query($sql, $query);
if(!isset($data)) $data = array(); $cc = 0;
while($info = mysqli_fetch_array($results, MYSQLI_ASSOC)){
if(!isset($data[$cc])) $data[$cc] = array();
///// FROM TABLE equipments /////
$data[$cc]['EQUIPMENT_ID'] = $info['EQUIPMENT_ID'];
$data[$cc]['DESCRIPTION'] = $info['DESCRIPTION'];
$data[$cc]['LOCATION'] = $info['LOCATION'];
$data[$cc]['PROJECT_NAME'] = $info['PROJECT_NAME'];
$data[$cc]['JOB_SITE_ID'] = $info['JOB_SITE'];
///// FROM TABLE jobsites /////
$data[$cc]['JOB_SITE'] = $info['JOB_SITE_NAME'];
$cc++;
}
print_r($data);
?>
So, as I said, the code returns values but only if the column "JOB_SITE" inside "equipments" has a jobsite id (not null). The ugly solution is to create a row inside the table "jobsites" with a jobsite_id named "empty", but if I can skip this, I will.
Is there a way to join only if e.JOB_SITE is not null ?
You can use LEFT JOIN in SQL query.
$query = "SELECT " .
"e.EQUIPMENT_ID, " .
"e.CUSTOMER_ID, " .
"e.DESCRIPTION, " .
"e.LOCATION, " .
"e.JOB_SITE, " .
"e.PROJECT_NAME, " .
"jb.DESCRIPTION AS JOB_SITE_NAME " .
"FROM equipments e " .
"LEFT JOIN jobsites jb ON jb.JOBSITE_ID = e.JOB_SITE " .
"WHERE e.CUSTOMER_ID = 1 ".
"ORDER BY e.EQUIPMENT_ID ASC";
This query will return NULL VALUE for column JOB_SITE_NAME if there is no row matching jb.JOBSITE_ID in equipments table

ORDER BY Not working with GROUP BY

I have written sql code using group by and order by but in here order by not working can any one help me
SELECT " . DB_PREFIX . "leaderboard_scores.* , SUM(" . DB_PREFIX . "leaderboard_scores.score) as total_score, " . DB_PREFIX . "customer.firstname,
" . DB_PREFIX . "customer.lastname
FROM " . DB_PREFIX . "leaderboard_scores
JOIN " . DB_PREFIX . "customer ON " . DB_PREFIX . "leaderboard_scores.philips_store_id = " . DB_PREFIX . "customer.customer_id
GROUP BY " . DB_PREFIX . "leaderboard_scores.phi_store_id
ORDER BY " . DB_PREFIX . "leaderboard_scores.week DESC
This query work without php errors but given middle rows without giving top weeks. weeks store using times stamp
actual query
SELECT rc_leaderboard_scores.* , SUM(rc_leaderboard_scores.score)
as total_score, rc_customer.firstname, rc_customer.lastname
FROM rc_leaderboard_scores
JOIN rc_customer
ON rc_leaderboard_scores.phi_store_id = rc_customer.customer_id
GROUP BY rc_leaderboard_scores.phi_store_id
ORDER BY rc_leaderboard_scores.week DESC
If you need to return the last record for every customer, you need a JOIN with a subquery that returns MAX(week) for every customer id:
SELECT
rc_leaderboard_scores.*,
m.total_score,
rc_customer.firstname,
rc_customer.lastname
FROM
(SELECT phi_store_id,
MAX(`week`) as max_week,
SUM(score) as total_score,
FROM rc_leaderboard_scores
GROUP BY phi_store_id) m
INNER JOIN
rc_leaderboard_scores
ON rc_leaderboard_scores.phi_store_id = m.phi_store_id
AND rc_leaderboard_scores.`week` = m.max_week
INNER JOIN
rc_customer ON m.phi_store_id = rc_customer.customer_id

Categories