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";
Related
I have this function:
case1:
public function searchArticle($keyword)
{
$keyword = sanitize($keyword, 15);
$sql = "SELECT a.*, c.id as cid, c.name" . Lang::$lang . " as catname, a.title" . Lang::$lang . " as atitle, c.slug as catslug, u.username,"
. "\n (SELECT COUNT(artid) FROM " . self::cmTable . " WHERE artid = a.id) as totalcomments, YEAR(a.created) as year, MONTH(a.created) as month, DATE_FORMAT(a.created, '%d') as day,"
. "\n (SELECT GROUP_CONCAT(DISTINCT participant) FROM " . self::partTable . " WHERE FIND_IN_SET(id,a.participants) > 0)as participants"
. "\n FROM " . self::mTable . " as a"
. "\n LEFT JOIN " . self::ctTable . " as c ON c.id = a.cid" . "\n LEFT JOIN users as u ON u.id = a.uid"
. "\n WHERE MATCH (title" . Lang::$lang . ", body" . Lang::$lang . ") AGAINST ('" . self::$db->escape($keyword) . "*' IN BOOLEAN MODE)"
. "\n AND a.created <= NOW()" . "\n AND (a.expire = '0000-00-00 00:00:00' OR a.expire >= NOW())"
. "\n AND a.active = 1"
. "\n ORDER BY a.created DESC LIMIT 20";
$row = self::$db->fetch_all($sql);
return ($row) ? $row : 0;
}
Every line is as it should be.
Now, when I use code reformat option this code style looks like this:
case2:
public function searchArticle($keyword)
{
$keyword = sanitize($keyword, 15);
$sql = "SELECT a.*, c.id as cid, c.name" . Lang::$lang . " as catname, a.title" . Lang::$lang . " as atitle, c.slug as catslug, u.username," . "\n (SELECT COUNT(artid) FROM " . self::cmTable . " WHERE artid = a.id) as totalcomments, YEAR(a.created) as year, MONTH(a.created) as month, DATE_FORMAT(a.created, '%d') as day," . "\n (SELECT GROUP_CONCAT(DISTINCT participant) FROM " . self::partTable . " WHERE FIND_IN_SET(id,a.participants) > 0)as participants" . "\n FROM " . self::mTable . " as a" . "\n LEFT JOIN " . self::ctTable . " as c ON c.id = a.cid" . "\n LEFT JOIN users as u ON u.id = a.uid" . "\n WHERE MATCH (title" . Lang::$lang . ", body" . Lang::$lang . ") AGAINST ('" . self::$db->escape($keyword) . "*' IN BOOLEAN MODE)" . "\n AND a.created <= NOW()" . "\n AND (a.expire = '0000-00-00 00:00:00' OR a.expire >= NOW())" . "\n AND a.active = 1" . "\n ORDER BY a.created DESC LIMIT 20";
$row = self::$db->fetch_all($sql);
return ($row) ? $row : 0;
}
The closest I can get is to set "Binary expressions" to "wrap always" in "Preferences/Code Style/PHP/Wapping and Braces", but it is still not as it should be and it is not really well readable.
case3:
public function searchArticle($keyword)
{
$keyword = sanitize($keyword, 15);
$sql =
"SELECT a.*, c.id as cid, c.name" .
Lang::$lang .
" as catname, a.title" .
Lang::$lang .
" as atitle, c.slug as catslug, u.username," .
"\n (SELECT COUNT(artid) FROM " .
self::cmTable .
" WHERE artid = a.id) as totalcomments, YEAR(a.created) as year, MONTH(a.created) as month, DATE_FORMAT(a.created, '%d') as day," .
"\n (SELECT GROUP_CONCAT(DISTINCT participant) FROM " .
self::partTable .
" WHERE FIND_IN_SET(id,a.participants) > 0)as participants" .
"\n FROM " .
self::mTable .
" as a" .
"\n LEFT JOIN " .
self::ctTable .
" as c ON c.id = a.cid" .
"\n LEFT JOIN users as u ON u.id = a.uid" .
"\n WHERE MATCH (title" .
Lang::$lang .
", body" .
Lang::$lang .
") AGAINST ('" .
self::$db->escape($keyword) .
"*' IN BOOLEAN MODE)" .
"\n AND a.created <= NOW()" .
"\n AND (a.expire = '0000-00-00 00:00:00' OR a.expire >= NOW())" .
"\n AND a.active = 1" .
"\n ORDER BY a.created DESC LIMIT 20";
$row = self::$db->fetch_all($sql);
return ($row) ? $row : 0;
}
How can I set the code reformat settings in PhpStorm, to force a new line only before . "\n ? (As it can be seen in the case1)
Use the heredoc syntax for the string that contains the query.
You can embed the variables directly into the string (aka variables interpolation). I see you also use class static members and class constants to compose the query and they are not recognized during the string parsing. But you can still embed them using sprintf():
$sql = <<< END_QUERY
SELECT a.*, c.id as cid, c.name%s as catname, a.title%s as atitle, c.slug as catslug, u.username,
(SELECT COUNT(artid) FROM %s WHERE artid = a.id) as totalcomments, YEAR(a.created) as year, MONTH(a.created) as month, DATE_FORMAT(a.created, '%%d') as day,
(SELECT GROUP_CONCAT(DISTINCT participant) FROM %s WHERE FIND_IN_SET(id,a.participants) > 0)as participants
FROM %s as a
LEFT JOIN %s as c ON c.id = a.cid
LEFT JOIN users as u ON u.id = a.uid
WHERE MATCH (title%s, body%s) AGAINST ('%s*' IN BOOLEAN MODE)
AND a.created <= NOW()
AND (a.expire = '0000-00-00 00:00:00' OR a.expire >= NOW())
AND a.active = 1
ORDER BY a.created DESC
LIMIT 20
END_QUERY;
$query = sprintf($query, Lang::$lang, Lang::$lang, self::cmTable, self::partTable, self::mTable, self::ctTable, Lang::$lang, Lang::$lang, self::$db->escape($keyword));
Because the percent sign (%) is a special character for sprintf(), you have to double it in order to let it represent itself (DATE_FORMAT(a.created, '%d') became DATE_FORMAT(a.created, '%%d')).
Or you can avoid using sprintf() if you extract the class static properties, class constants and function calls into local variables before the string:
$lang = Lang::$lang;
$cmTable = Lang::cmTable;
$kword = self::$db->escape($keyword);
// ...
$sql = <<< END_QUERY
SELECT a.*, c.id as cid, c.name{$lang} as catname, a.title{$lang} as atitle, c.slug as catslug, u.username,
// ...
This way the code formatting tools won't touch the query any more. As a bonus, the query is easier to read because it is all text, no more quotes and string concatenation.
I'm trying to join multiple table, let me explain better with my query code example:
if($stmt = $this->db->prepare("SELECT table_users.id AS user_id, table_users.email AS user_email, table_users.GUID as user_guid, "
. "table_roles.slug AS role_slug, table_user_settings.username, table_users.id_roles, "
. "table_users.first_name, table_users.last_name, table_users.mobile_number, table_users.phone_number, "
. "table_users.address, table_users.city, table_users.state, table_users.zip_code, table_users.notes "
. "FROM table_users "
. "WHERE table_users.data = 0 "
. "INNER JOIN table_roles ON table_roles.id = table_users.id_roles "
. "INNER JOIN table_user_settings ON table_user_settings.GUID = table_user.GUID "
. "WHERE table_user_settings.username = ? "
. "WHERE table_user_settings.password = ? "))
{
$stmt->bind_param("ss",$username, $password);
$stmt->bind_result($id, $email, $GUID, $slug, $id_roles, $address, $city, $state, $zip_code, $notes);
$result = $stmt->execute();
$stmt->fetch();
}
var_dump($this->db->error);
$stmt->close();
return $result;
now the error returned from the query is this:
string(226) "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'INNER JOIN table_roles ON table_roles.id = table_users.id_roles INNER JOIN table' at line 1"
What is wrong in the query?
You have 3 WHERE clauses in your query, when only 1 is valid and it should go after FROM and INNER JOIN clauses. All conditions in WHERE clause should be separated with AND clause (in this query).
if($stmt = $this->db->prepare("SELECT table_users.id AS user_id, table_users.email AS user_email, table_users.GUID as user_guid, "
. "table_roles.slug AS role_slug, table_user_settings.username, table_users.id_roles, "
. "table_users.first_name, table_users.last_name, table_users.mobile_number, table_users.phone_number, "
. "table_users.address, table_users.city, table_users.state, table_users.zip_code, table_users.notes "
. "FROM table_users "
. "INNER JOIN table_roles ON table_roles.id = table_users.id_roles "
. "INNER JOIN table_user_settings ON table_user_settings.GUID = table_user.GUID "
. "WHERE table_users.data = 0 AND "
. "table_user_settings.username = ? AND "
. "table_user_settings.password = ? "))
You might want to check out the valid SQL syntax in MySql doc: http://dev.mysql.com/doc/refman/5.7/en/select.html
There is a syntax error in your query:
WHERE table_users.data = 0 this should come after JOIN
if($stmt = $this->db->prepare("SELECT table_users.id AS user_id, table_users.email AS user_email, table_users.GUID as user_guid, "
. "table_roles.slug AS role_slug, table_user_settings.username, table_users.id_roles, "
. "table_users.first_name, table_users.last_name, table_users.mobile_number, table_users.phone_number, "
. "table_users.address, table_users.city, table_users.state, table_users.zip_code, table_users.notes "
. "FROM table_users "
. "INNER JOIN table_roles ON table_roles.id = table_users.id_roles "
. "INNER JOIN table_user_settings ON table_user_settings.GUID = table_user.GUID "
. "WHERE table_users.data = 0 AND "
. "WHERE table_user_settings.username = ? AND "
. "WHERE table_user_settings.password = ? "))
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
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
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.