I have a query that returns close to a 1000 records. Using pagination, I'm showing a 100 records per page. Great...no problem. I can also sort by last name or first name in either ascending of descending order. ok so far. The first page returns records for last name starting with A to C. The problem I'm having is that when I click last name to descend I get records with last name starting with Z. The records at the end of my query, I want to get results going from C to A (what is shown on my first page...repeating the same functionality in each page.
Here is what I got...
$orderColumn = 'lastName';
$orderDirection = 'ASC';
if( isset($_POST["oc"]) && $_POST["oc"] !== '' ) { $orderColumn = $_POST["oc"]; }
if( isset($_POST["od"]) && $_POST["od"] !== '' ) { $orderDirection = $_POST["od"]; }
$per_page = 100;
$query = "SELECT * FROM table as t
LEFT JOIN table_2 as t2 ON t.pk_uID = t2.fk_uID
LEFT JOIN table_3 as t3 ON t3.fk_utID = t2.pk_utID
WHERE t3.fk_utID = 7 and t.interviewed = 0";
$result = $db->query($query);
$count = mysql_num_rows($result);
$total = ceil($count/$per_page);
if ($_GET['page']) {
$page = $_GET['page'];
}
$offset = (($page-1)*$per_page);
$query2 = "SELECT firstName as first, lastName as last FROM table
LEFT JOIN table_2 as t2 ON t.pk_uID = t2.fk_uID
LEFT JOIN table_3 as t3 ON t3.fk_utID = t2.pk_utID
WHERE t3.fk_utID = 7 and interviewed = 0 order by $orderColumn $orderDirection LIMIT $offset, $per_page";
$res = $db-> query($query2);
while($row = mysql_fetch_array($res)){
echo "<span style='display: inline-block; width: 15%;'>$row[first]</span>";
echo "<span style='display: inline-block; width: 15%;'>$row[last]</span>";
}
To what I was saying in comment.. BTW I'm on my mobile phone so this may be unformatted and or take a while...
Select what_you_need
From
( select your_inner_select
From table t
LEFT JOIN table_2 as t2 ON t.pk_uID = t2.fk_uID
LEFT JOIN table_3 as t3 ON t3.fk_utID = t2.pk_utID
WHERE t3.fk_utID = 7 and interviewed = 0 LIMIT $offset, $per_page
ORDER BY $orderColumn ASC
)t
order by $orderColumn $orderDirection
I am currently getting details from my 'social_posts' table, and then adding it's tags, the number of likes, and the number of answers it has to the resulting object. Is there a way I can be doing this without having to do extra queries in a loop?
$query = "SELECT * FROM social_posts JOIN users ON social_posts.user_id = users.id";
$posts = $this->db->query($query);
if ($posts->num_rows() > 0) {
foreach ($posts->result() as $p => $post) {
// Get the question's tags
$tags = $this->db->query("SELECT * FROM social_tags
WHERE post_id = ?", $post->post_id);
// Get the number of likes
$likes = $this->db->query("SELECT id FROM social_likes
WHERE post_id = ?", $post->post_id);
// Get the number of answers
$answers = $this->db->query("SELECT id FROM social_responses
WHERE post_id = ?", $post->post_id);
$post->tags = $tags->result();
$post->likes = $likes->num_rows();
$post->answers = $answers->num_rows();
$post->author = array(
"firstname" => $post->firstname,
"thumbnail" => $post->thumbnail,
);
}
return $posts->result();
} else {
return FALSE;
}
You may try this SQL:
SELECT
social_posts.*,
users.*,
GROUP_CONCAT(social_tags.name) AS tags,
COUNT(social_likes.id) AS likes,
COUNT(social_responses.id) AS answers
FROM
social_posts
JOIN users ON social_posts.user_id = users.id
LEFT JOIN social_tags ON social_tags.post_id = social_posts.id
LEFT JOIN social_likes ON social_likes.post_id = social_posts.id
LEFT JOIN social_responses ON social_responses.post_id = social_posts.id
GROUP BY
social_posts.id
You will get the tags as comma delimited string. Of course you need to adjust the column names to fit your database.
This is my code but it's not working:
$select = $db->select()
->from(array('p' => 'products'), 'p.product_id')
->columns(array('x' => new Zend_Db_Expr('(SELECT...)'
)))
->where('x = ?', 'value');
// Alternatively use columns('p.product_name')
How can I retrieve x and compere it in where clause?
This is the actual query:
SELECT `abstract_submission`.*,
(SELECT GROUP_CONCAT(CONCAT(user.firstName, " ", user.lastName) SEPARATOR ",")
FROM mamba_event.abstract_submission_reviewer reviewer INNER JOIN
mamba_account.account_user user ON user.id = reviewer.userId
WHERE reviewer.submissionId = mamba_event.abstract_submission.id AND
user.isEnabled = 1)
AS `reviewers`,
(SELECT GROUP_CONCAT(CONCAT(author.firstName, " ", author.lastName) SEPARATOR ",")
FROM mamba_event.abstract_author author INNER JOIN
mamba_event.abstract_submission_author map ON author.id = map.authorId
WHERE map.submissionId = mamba_event.abstract_submission.id)
AS `allAuthors`,
(SELECT COUNT(`abstract_paper`.`id`) FROM `mamba_event`.`abstract_paper`
WHERE `abstract_paper`.`submissionId` = `abstract_submission`.`id`)
AS `numPapers`,
(SELECT `paperNumber` FROM `mamba_event`.`abstract_paper`
WHERE `abstract_paper`.`submissionId` = `abstract_submission`.`id` AND
`abstract_paper`.`currentStatus` = 3 LIMIT 1)
AS `acceptedPaperNumber`,
(SELECT IF ((COUNT(1) > 0), 'Paper has been uploaded','None') AS hasUploadedPaper
FROM `mamba_event`.`abstract_paper` paper
WHERE paper.submissionId = `mamba_event`.`abstract_submission`.`id`)
AS `hasUploadedPaper`,
(SELECT GROUP_CONCAT(CONCAT(user.firstName, " ", user.lastName) SEPARATOR ",")
FROM `mamba_event`.`abstract_submission_reviewer` reviewer INNER JOIN
`mamba_account`.`account_user` user ON user.id = reviewer.userId
WHERE reviewer.submissionId = `mamba_event`.`abstract_submission`.`id`
AND reviewer.hasConflictOfInterest = 1
AND user.isEnabled = 1)
AS `reviewersWithConflict`,
(SELECT AVG(`score`) FROM `mamba_event`.`abstract_submission_score`
WHERE `submissionId` = `abstract_submission`.`id`)
AS `averageScore`,
(SELECT AVG(`score`) FROM `mamba_event`.`abstract_paper_score`, `mamba_event`.`abstract_paper`
WHERE `abstract_paper_score`.`paperId` = `abstract_paper`.`id`
AND `abstract_paper`.`submissionId` = `abstract_submission`.`id`
AND (`abstract_paper`.`currentStatus` = 1
OR `abstract_paper`.`currentStatus` = 3))
AS `averagePaperScore`,
(SELECT AVG(`score`*`scoreWeight`) FROM `mamba_event`.`abstract_submission_score` INNER JOIN
`mamba_event`.`abstract_request_criteria` ON `criteriaId` = `abstract_request_criteria`.`id`
WHERE `submissionId` = `abstract_submission`.`id`)
AS `averageWeightedScore`,
(SELECT AVG(`score`*`scoreWeight`) FROM `mamba_event`.`abstract_paper_score` JOIN
`mamba_event`.`abstract_paper` INNER JOIN
`mamba_event`.`abstract_request_criteria` ON
`criteriaId` = `abstract_request_criteria`.`id`
WHERE `abstract_paper_score`.`paperId` = `abstract_paper`.`id`
AND `abstract_paper`.`submissionId` = `abstract_submission`.`id`
AND (`abstract_paper`.`currentStatus` = 1
OR `abstract_paper`.`currentStatus` = 3))
AS `averageWeightedPaperScore`, `author`.`email`
AS `authorEmail`, `author`.`salutation`
AS `authorTitle`, `author`.`firstName`
AS `authorFirstName`, `author`.`lastName`
AS `authorLastName`, `author`.`organisation`
AS `authorOrganisation`, `author`.`position`
AS `authorPosition`, `author`.`department`
AS `authorDepartment`, `author`.`phone`
AS `authorPhone`, `author`.`fax`
AS `authorFax`, `address`.`line1`
AS `addressLine1`, `address`.`line2`
AS `addressLine2`, `address`.`line3`
AS `addressLine3`, `address`.`line4`
AS `addressLine4`, `address`.`city`
AS `addressCity`, `address`.`stateCode`
AS `addressStateCode`, `address`.`countryCode`
AS `addressCountryCode`, `address`.`postalCode`
AS `addressPostalCode`, `author`.`biography`
AS `authorBiography`, `request`.`title`
AS `request`, `request`.`blindReview`, `request`.`hasCustomTypes`, `file`.`content_type`, `file`.`original_filename` AS `filename`, `author`.`speakerId`,
(SELECT GROUP_CONCAT(
CONCAT('',ifnull(author.firstName,'-'),' ',
ifnull(author.lastName,'-'),'
(',ifnull(author.organisation,'-'),',
',ifnull(author.authorCountryCode,'-'),')')
SEPARATOR ",")
FROM `mamba_event`.`abstract_author` author LEFT JOIN
`mamba_event`.`abstract_submission_author` sa
ON sa.authorId = author.id
WHERE sa.submissionId = `abstract_submission`.`id`)
AS `authorDetails`,
(SELECT GROUP_CONCAT(`field`.`fieldValue`)
FROM `mamba_abstract`.`author_field_value_varchar` `field`
WHERE `field`.`fieldId` = '2185'
AND `field`.`authorId` = `abstract_submission`.`presenterId`)
AS `field2185`,
(SELECT GROUP_CONCAT(`field`.`fieldValue`)
FROM `mamba_abstract`.`author_field_value_varchar` `field`
WHERE `field`.`fieldId` = '2335'
AND `field`.`fieldValue` = 'BSCS'
AND `field`.`authorId` = `abstract_submission`.`presenterId`)
AS `field2335`,
(SELECT GROUP_CONCAT(`field`.`fieldValue`)
FROM `mamba_abstract`.`author_field_value_varchar` `field`
WHERE `field`.`fieldId` = '2336'
AND `field`.`authorId` = `abstract_submission`.`presenterId`)
AS `field2336` FROM `mamba_event`.`abstract_submission`
INNER JOIN `mamba_event`.`abstract_request` AS `request` ON requestId = request.id
LEFT JOIN `mamba_account`.`account_file` AS `file` ON fileId = file.id
INNER JOIN `mamba_event`.`abstract_author` AS `author` ON `presenterId` = `author`.`id`
LEFT JOIN `mamba_general`.`address` ON `author`.`addressId` = `address`.`id` WHERE ((`abstract_submission`.`isEnabled` = '1') AND (`abstract_submission`.`eventId` = '1893')) AND (`field2335` LIKE "%BSCS%") ORDER BY `request` asc LIMIT 15
You could do it with HAVING, like Muhammad Zeeshan said.
$select = $db->select()
->from(array('p' => 'products'), 'p.product_id')
->columns(array('x' => new Zend_Db_Expr('(SELECT...)')))
->having('x = ?', 'value');
Could I somehow only use only 1 sql query for this?
showthread.php
// Get Topic subject etc
$threadID = isset($_GET['threadID']) ? intval($_GET['threadID']) : 0;
$result = mysql_query("SELECT * FROM topics WHERE id = $threadID");
// Fetch rows
$row = mysql_fetch_assoc($result);
$subject = htmlspecialchars($row['subject']);
echo '<h2>'.$subject.'</h2>';
// Get posts that belong to this topic!
$posts = mysql_query("SELECT * FROM posts INNER JOIN users ON users.id = posts.user_id WHERE posts.topic_id = $threadID");
// posts.....
while ($post = mysql_fetch_assoc($posts)) {
echo '<br>'.$post['message'].'';
}
From my understanding, you should be able to get all the information you need from something like this? (Plus or minus any missing columns)
SELECT topics.subject, posts.message
FROM posts
INNER JOIN users ON users.id = posts.user_id
INNER JOIN topics ON topics.id = posts.topic_id
WHERE posts.topic_id = $threadID
Use mysqli
Use real_escape_string
Use Prepared statement or PDO
I have an app that uses the codeigniter CXTags tagging library.
The database structure is as follows:
posts
id
tags_ref
row_id
table
tag_id
tags
id
safe_tag
tag
My query basically goes if $safe_tag is not null then join tags_ref on post.id = tags_ref.row_id, join tags on tags_ref.tag_id = tags.id, where tags_ref.table = 'posts' and tags.safe_tag = 'food'
SELECT * FROM posts
JOIN tags_ref ON posts.id = tags_ref.row_id
JOIN tags ON tags_ref.tag_id = tags.id
WHERE tags.safe_tag = $safe_id
Unfortunately the query I've written in active record is not functioning properly. The query works perfectly when £safe_tag is null but when it's not I get wrong results.
function get_posts($id = NULL, $safe_tag = NULL) {
if($safe_tag != NULL){
echo $safe_tag;//debugging
$table = 'posts';
$this->db->join('tags_ref', 'posts.id = tags_ref.row_id');
$this->db->join('tags', 'tags_ref.tag_id = tags.id');
$this->db->where('tags_ref.table', $table);
$this->db->where('tags.safe_tag',$safe_tag);
}
//if an id was supplied
if ( $id != NULL ) {
$this->db->where('posts.city_id',$id);
}
// execute query
$query = $this->db->get('posts');
...
Here is the query with profiling on:
SELECT *
FROM (`posts`)
INNER JOIN `tags_ref` ON `posts`.`id` = `tags_ref`.`row_id`
INNER JOIN `tags` ON `tags_ref`.`tag_id` = `tags`.`id`
WHERE `tags_ref`.`table` = 'posts'
AND `tags`.`safe_tag` = 'food'
AND `posts`.`city_id` = '2'
Can someone have a look? I think I need a fresh set of eyes on it.
Your forgot to actually run the query inside your first if{}
if($safe_tag != NULL){
echo $safe_tag;//debugging
$table = 'posts';
$this->db->join('tags_ref', 'posts.id = tags_ref.row_id');
$this->db->join('tags', 'tags_ref.tag_id = tags.id');
$this->db->where('tags_ref.table', $table);
$this->db->where('tags.safe_tag',$safe_tag);
$this->db->get(); // here
}