I have the following table and I want to select all (via php query) but only the rows that matches course1, I tried the following but it doesn't work.
$comments = array();
$result = mysql_query("select * from comments where course1='$post_id' order by id ASC");
what's the right query?
+----+-----------+----------+-----+-------------------------+---------------+-------------
| id | post_id | name | url | email | body | dt |
+----+-----------+----------+-----+-------------------------+---------------+-------------
| 1 | course2 | john | | john#john.com | comments by john | 2012-11-16 |
| 2 | course1 | wiki | | wiki#wiki.com | comments by wiki | 2012-11-16 |
| 3 | course2 | daniel | | daniel#gmail.com | comments by daniel | 2012-11-16 |
| 4 | course2 | ram | | ram#ram.com | comments by ram | 2012-11-16 |
| 5 | course1 | velu | | velu#velu.com | comments by velu | 2012-11-16 |
+----+-----------+----------+-----+-------------------------+---------------+-------------
Try this: SELECT * FROM comments WHERE post_id='course1' order by id ASC
I think you'd muddled your column names and search values in your sql
try this:
$result = mysql_query("select * from comments where post_id='$post_id' order by id ASC");
You need to reference the field name you're searching on:
$result = mysql_query("select * from comments where post_id='$post_id' order by id ASC");
Where your $post_id string variable contains value "course1".
Related
I'm needing to retrieve shared values from a table based on a value from another table, but don't show duplicates.
Example of what tables I have...
Table - members
+-----------------+
| ID | NAME |
+-----------------+
| 1 | Bob |
| 2 | Jack |
| 3 | Jane |
| 4 | Bruce |
| 5 | Clark |
| 6 | Peter |
+-----------------+
Table - groups
+--------------------------------+
| ID | NAME | MANAGER_ID |
+--------------------------------+
| 1 | Group A | 1 | (Bob)
| 2 | Group B | 2 | (Jack)
| 3 | Group C | 1 | (Bob)
+--------------------------------+
Table - group_members
+--------------------------------+
| ID | GROUP_ID | MEMBER_ID |
+--------------------------------+
| 1 | 1 | 3 | (Group A - Jane)
| 2 | 1 | 4 | (Group A - Bruce)
| 3 | 1 | 5 | (Group A - Clark)
| 4 | 1 | 6 | (Group A - Peter)
| 5 | 2 | 3 | (Group B - Jane)
| 6 | 3 | 4 | (Group B - Bruce)
| 7 | 3 | 5 | (Group C - Clark)
+--------------------------------+
What I am needing
(Note: I'm using * in queries here to shorten code.)
If 'Bob' sees all his groups.
Look at 'group_members' table and show all members that belong to it...
$q = SELECT * FROM groups WHERE manager_id = $id;
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch-assoc($r) {
$q2 = SELECT *, count(MEMBERS_ID) AS group_count FROM group_members LEFT JOIN members ON group_members.MEMBER_ID = members.id WHERE group_id = '$row[GROUP_ID]';
$r2 = mysqli_query($dbc, $q2);
while ($row2 = mysqli_fetch-assoc($r2) {
echo $row2['name'];
}
}
This shows me the list as expected.
+------------------------+
| NAME | GROUP COUNT |
+------------------------+
| Jane | 1 |
| Bruce | 1 |
| Clark | 1 |
| Peter | 1 |
| Bruce | 1 |
| Clark | 1 |
+------------------------+
I Add GROUP BY group_members.group_id to my 2nd query and that shows.
+------------------------+
| NAME | GROUP COUNT |
+------------------------+
| Jane | 1 |
| Bruce | 2 |
| Clark | 2 |
| Peter | 1 |
+------------------------+
Which is perfect... But here is the problem
if I add a WHERE members.name LIKE \'%clark%\' then it outputs...
+------------------------+
| NAME | GROUP COUNT |
+------------------------+
| | |
| | |
| Clark | 1 |
| | |
| | |
| Clark | 1 |
+------------------------+
It ignores GROUP BY and shows blank rows where other entries would show.
So with all that said. Does any one know why or a better way to do this please?
Been at it for a while now and would really appreciate any assistance.
EDITED:
Here's the full query with all the columns used:
$q = SELECT * FROM groups WHERE manager_id = $id;
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch-assoc($r) {
$q2 = SELECT members.id) AS memid, members.first, members.last, members.comname, members.email, members.sector, (members.status) AS memstatus, (group_members.id) AS groupid, (group_members.member_id) AS memidgroup, group_members.group_id, COUNT(group_members.member_id) AS groupcount, member_roles.role FROM members LEFT JOIN group_members ON members.id = group_members.member_id LEFT JOIN member_roles ON members.role_id = member_roles.id WHERE group_id = '$row[GROUP_ID]' AND members.name LIKE '%clark%' GROUP BY group_members.group_id;
$r2 = mysqli_query($dbc, $q2);
while ($row2 = mysqli_fetch-assoc($r2) {
echo $row2['name'];
}
}
Your query or problem is not completely stated. One cannot guess or assume.
Post your last query as well as all queries dont worry about saving the space.
Those blank rows have data that why they are in the table.
Base on your explanation or your query, here is my simple answer
SELECT id,
(select groups.id from groups where groups.id = group_members.group_id )AS group_members_id,
(select groups.name from groups where groups.id = group_members.group_id )AS group_members_name,
(select members.id from members where members.id = group_members.member_id )AS members_id,
(select members.name from members where members.id = group_members.member_id )AS members_name,
count((select members.id from members where members.id = group_members.member_id ) )as members_id_count FROM group_members WHERE (select members.name from members where members.id = group_members.member_id ) LIKE '%clark%' group by members_id
As you mentioned
WHERE members.name LIKE \'%clark%\'
you were selecting data from the members table whereas you have to select the data from group_members table.
Here is the scenario. I have different levels of users. the user creation process is like this:
admin -> reseller -> marketer -> autoservice
I am trying to write a SQL query to select all autoservices created by a specific reseller. all users are saved in users table which has the following simplified structure:
+----+--------+--------------+-------------+-----------+
| id | userid | username | role | createdby |
+----+--------+--------------+-------------+-----------+
| 1 | 334455 | reseller1 | reseller | admin |
| 2 | 245578 | marketer1 | marketer | reseller1 |
| 3 | 235677 | autoservice1 | autoservice | marketer1 |
| 4 | 253569 | autoservice2 | autoservice | marketer1 |
| 5 | 234267 | autoservice3 | autoservice | marketer1 |
| 6 | 245468 | marketer2 | marketer | reseller1 |
| 5 | 434567 | autoservice4 | autoservice | marketer2 |
| 5 | 532263 | autoservice5 | autoservice | marketer2 |
| 5 | 634262 | autoservice6 | autoservice | marketer2 |
+----+--------+--------------+-------------+-----------+
The query should select autoservice1, autoservice2, autoservice3, autoservice4, autoservice5, autoservice6 and all their fields. currently I'm doing this with a combination of MySQL and php. First I select all marketers created by reseller1:
$sql="SELECT * FROM marketers WHERE createdby=:createdby";
$st=$conn->prepare($sql);
$st->bindvalue(":createdby",'reseller1',PDO::PARAM_STR);
$st->execute();
$usersArray=$st->fetchAll();
$NumberOfusers=$st->rowcount();
Then I loop through the results:
$MembersGeoData=array();
$MembersCount=0;
for($i=0;$i<$NumberOfusers;$i++) {
$sql="SELECT * FROM autoservices WHERE createdby=:createdby";
$st=$conn->prepare($sql);
$st->bindvalue(":createdby",$usersArray[$i]['username'],PDO::PARAM_STR);
$st->execute();
$tempUsersArray=$st->fetchAll();
$tempNumberOfusers=$st->rowcount();
$MembersGeoData=array_merge($MembersGeoData,$tempUsersArray);
$MembersCount+=$tempNumberOfusers;
}
This works but seems to be very inefficient. How can I do this with one sql query?
Assuming that your hierarchy is exactly correct (it is never skipped and a marketer never creates another marketer), then:
select sa.*
from autoservices sm join
autoservices sa
on sa.role = 'autoservice' and
sm.role = 'marketer' and
sm.username = sa.createdBy
where sm.createdBy = 'reseller1';
You are correct. You should let the database do this work.
I used The answer from #Gordon Linoff and answered my question :
SELECT a.* FROM autoservices AS a
JOIN marketers AS m
ON a.createdby=m.username
WHERE m.createdby='reseller1'
I'd like to use RAND() in a query to be able to do the following:
ODER BY id DESC and allow RAND() to choose between last 3 inserted rows in the table. On the front-end when page is refreshed function rand will choose between 5 - 8 (on the table example) and show any data between those numbers.
Query Example
function rand()
{
$sth = $this->db->prepare("SELECT rows FROM table ORDER BY id LIMIT 1");
$sth->execute();
}
Table Example
+--------------+
| id | name |
+--------------+
| 1 | Jon |
| 2 | Sarah |
| 3 | Stevie |
| 4 | Stew |
| 5 | Dave |
| 6 | Kar |
| 7 | Stevo |
| 8 | Blake |
+----+---------+
EDIT
+----+
| id |
+----+
| |
| |
| |
| |
| |
| |
| |
| || |
If I understand your question correctly, I think you need this:
SELECT id, name
FROM
(SELECT id, name FROM table ORDER BY id DESC LIMIT 3) s
ORDER BY rand()
LIMIT 1
Have you tried this:
SELECT name
FROM users
ORDER BY RAND()
LIMIT 3
http://davidwalsh.name/mysql-random
I have a challenge I can't seem to handle.
+------+--------+-----------+-------+
| id | user | genres | books |
+------+--------+-----------+-------+
| 1 | John | crimes | 2 |
| 2 | John | scienc | 1 |
| 3 | John | nature | 4 |
| 4 | Pete | nature | 3 |
| 5 | Pete | crime | 2 |
| 6 | Mary | nature | 20 |
+------+--------+-----------+-------+
I would like to have a SQL query that gets the total amount of books the users own, no matter the genre and would like to ORDER them by who has the most.
In this example, you see that Mary has 20 books, Pete 5 and John has 7 so my desired result would be an array like:
result[0][user] = "Mary";
result[0][total] = 20;
result[1][user] = "John";
result[1][total] = 7;
result[2][user] = "Pete";
result[2][total] = 5;
How can I get this into one SQL? Should I use CONCAT or TOP or something? I use MySQL & PHP.
You need GROUP BY with SUM
SELECT `user`, SUM(books) AS total_books
FROM `table`
GROUP BY `user`
ORDER BY total_books DESC
If you only want the first 10 then you can use
SELECT `user`, SUM(books) AS total_books
FROM `table`
GROUP BY `user`
ORDER BY total_books DESC LIMIT 10`
By the way, you might want to rethink your schema slightly. Duplicating info is against the principles of normalisation. You might want to add a new owners table:
+-----------+-------------+
| owner_id | owner_name |
+-----------+-------------+
| 1 | John |
| 2 | Pete |
| 3 | Mary |
+-----------+-------------+
and then reference this by owner_id in your books table.
select user, sum(books) as total
from your_table
group by user
order by sum(books)
limit 10
SELECT sum(books) as book_count, user FROM `books` GROUP BY (user) order by book_count DESC
I have tables illustrated below
//reference type table
+---+-----------+---------+
|ID |Article_ID |Ref_Types|
+---+-----------+---------+
| 1 | 1 | article |
| 2 | 1 | book |
| 3 | 1 | article |
| 4 | 1 | article |
| 5 | 2 | book |
+---+-----------+---------+
//book references table
+---+-----------+--------+
|ID |Article_ID |Title |
+---+-----------+--------+
| 1 | 1 | book1 |
| 2 | 1 | book2 |
| 3 | 2 | book3 |
| 4 | 2 | book4 |
| 5 | 2 | book5 |
+---+-----------+--------+
//article references table
+---+-----------+-----------+
|ID |Article_ID |Title |
+---+-----------+-----------+
| 1 | 1 | article1 |
| 2 | 1 | article2 |
| 3 | 2 | article3 |
| 4 | 2 | article4 |
| 5 | 2 | article5 |
+---+-----------+-----------+
I have to look into first table and check the reference, of which type it is;
for each reference type, I have get reference table from related table
I have to output in order, as shown in table one.
1:
$data=array();
$sql=mysql_query("SELECT * FROM reftypes
WHERE Article_ID=1 ORDER BY ID ASC");
while($row = mysql_fetch_array($sql)){
$data[]=$row[2]; // i store in an array so that i can use later..
}
2:
foreach ($data as $ref) {
$counter=1;
switch ($ref) {
case "article":
$sqlarticle= mysql_query("SELECT Title
FROM book WHERE Article_ID=1 ORDER BY ID ASC");
echo mysql_result($sqlarticle, $counter); //i want to get only one out of book table
$counter++;
break;
...
...
But $sqlarticle does not seem to work.
I want to display as:
+-----------+----------+
|Article_ID |Reference |
+-----------+----------+
| 1 | article1 |
| 1 | book1 |
| 1 | article2 |
| 1 | article3 |
+-----------+----------+
I know it is a long question and for experts or experienced people it is very trivial, but that is where I'm stuck.
SELECT
*
FROM
reftypes R
WHERE
Article_ID=your_id
LEFT JOIN books B ON (B.Article_ID = R.Article_ID AND R.Ref_Types = 'book')
LEFT JOIN articles A ON (A.Article_ID = R.Article_ID AND R.Ref_Types = 'article')
ORDER BY
R.id ASC;
Even if the database is wrongly modeled, I think.
What about the followin model instead?
""although especially question owners should respect any kind of effort and input, -i am thankful- i can not understand why some people try to think of question's holder as well-informed or experienced as themselves, or worse comment from higher level. ""
anyway, my question was about to get values one by one, here is how i did it;
$data=array();
$sql=mysql_query("SELECT * FROM reftypes
WHERE Article_ID=1 ORDER BY ID ASC");
while($row = mysql_fetch_array($sql)){
$data[]=$row[2]; // i store in an array so that i can use later..
}
$articlecount=0;
$bookcount=0;
foreach ($data as $value) {
switch ($value) {
case "article":
$sqlarticle=mysql_query("SELECT RefArticleTitle
FROM ref_article
WHERE $article_ID=Article_ID
ORDER BY ID ASC");
$articles= mysql_result($sqlarticle, $articlecount);
echo $articles;
echo "\n";
$articlecount++;
break;
case "book":
$sqlbook=mysql_query("SELECT RefBookName
FROM ref_book
WHERE $article_ID=Article_ID
ORDER BY ID ASC");
$books= mysql_result($sqlbook, $bookcount);
echo $books;
echo "\n";
$bookcount++;
break;
...
...
as a result, i got what i required..
+-----------+----------+
|Article_ID |Reference |
+-----------+----------+
| 1 | article1 |
| 1 | book1 |
| 1 | article2 |
| 1 | article3 |
+-----------+----------+
thanks to whoever interested in the topic..
$result=mysqli_query("select ref_types from reference type");
while($row=mysqli_fetch_array($result))
{
$table=$row[0];
$result1=mysqli_query("select * from $table");
while($row1=mysqli_fetch_array($result1))
{
var_dump($row1);
}
}