simple php mysql search engine with checkboxes - php

I would like to do a search engine for my webpage.
I have several tables in my mysql database and i would like them
combined when user
Table users
id name age country vip profile_image
1 nick 23 sweden 1 yes
2 michael 20 germany 0 no
3 laura 19 usa 1 yes
4 gary 33 china 1 yes
Table online
id user_id online
1 1 1
2 2 1
3 4 1
user_id is connected to id in users table
Now i have checkboxes
[ ] Those which are online
[ ] Those which are vip
[ ] Those with profile image
Im coding my page in PHP and im trying to figure how to include certain
searches in a sql query if certain checkbox is checked.
I can have tons of options here. Example if no checkbox is checked,
iff on you want to search for those which are online, how do i go in to the second table?
I hope you get my point here. I really hope someone could help me
and give me an working example of the php & sql query.
Cheerz!

First you have to check which checkboxes have been checked. Then you must write MySQL-query with PHP based on that information. You must think in every checkbox, what information it needs to check. If your database is well written, there is seldom a problem that two options affect each other. If information is in users-table, you need just write line to where-clause. If you need to join table to users-table to get information you need to do that too. Here is an example
$query = "";
$query .= "SELECT users.* FROM users";
if ($include_online == 1) {
$query .= " LEFT JOIN online ON online.user_id = users.id";
}
$query .= " WHERE";
if ($include_vip == 1) {
$query .= " users.vip = 1 AND";
}
if ($include_image == 1) {
$query .= " users.profile_image = 'yes' AND";
}
if ($include_online == 1) {
$query .= " online.online = 1 AND";
}
$query .= " users.name LIKE '%".$search_string."%'";

You need to form a query something like the following:
SELECT users.name, users.age, users.country
FROM users
LEFT JOIN online ON user.id = online.user_id
WHERE ((user.vip = 1) && (online.online = 1))

Related

SELECT COUNT with Group BY only return value of 2

I have 6 records 3 of which has identical School and I want to get the result of counting how many school there are inside my database but it only returns the value of 2
$tblnum1 = "SELECT COUNT(*) AS ttldata FROM engoralgrade3 WHERE Years = '$yrr' GROUP BY School";
$tblnum = mysqli_query($conn, $tblnum1);
$tblnm = mysqli_fetch_array($tblnum);
echo $tblnm['ttldata'];//input should be 3
This what my data base looked like
I have checked your table, every school do have 2 rows.
maybe u want to count how many distinct school there are, so change the sql to:
select count(distinct School )from engoralgrade3
or u want to distinct the school name, try :
select distinct School from engoralgrade3
You can try this query it will work
$tblnum1 = "SELECT * FROM engoralgrade3 WHERE Years = '$yrr' GROUP BY School";
$tblnum = mysqli_query($conn, $tblnum1);
$tblnm = mysqli_num_rows($tblnum);
echo $tblnm ;
it may be the var $yrr is not identical for all six records in database which cause make returnred value is 2 not 3 .

Get a list of users following a specific user and check whether I am following them

I have a mysql table consisting of users following other users.
USER_ID FOLLOW_ID
1 2
1 3
2 4
3 4
6 4
2 6
I am user No. 2 and the person in question is user No. 4. You see that three people are following user No.4 including me. I can query the users who are following user No.4. How can I add to the query if I am following these people or not? So what I would like to know is who are following a specific user (No.4 in this case) and which one of them I am following.
Desired result:
USER_ID (No.4 is FOLLOWED BY), DO_I_FOLLOW_HIM
2 No
3 No
6 Yes
As you see from the last record of the table I (No.2) am following User No.6.
Query the list of people following user No.4:
$myid = '6';
$userid = '4';
$i = 0;
try {
$stmt = $conn->prepare("SELECT USER_ID FROM FOLLOW WHERE FOLLOW_ID=?");
$stmt -> execute(array($userid));
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$row2[$i] = $row['USER_ID'];
$i++;
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
$response["success"] = 0;
}
Sample SQL Fiddle for help: http://sqlfiddle.com/#!2/97ac6
SELECT him.user_id, IF(i.follow_id,'yes','no') AS i_follow_him
FROM Follows him
LEFT JOIN Follows i ON (i.follow_id = him.user_id AND i.user_id = 2)
WHERE him.follow_id = 4
To get a list of users that you follow that are following another given user, you need to use a subquery. You can see it when written above you are asking two things
Who is following person A
From that list who am I following.
So You could try using a query like so,
Select User_ID, Follows_ID
From Follows
Where User_ID = ?
And Follow_ID In (Select User_ID From Follows Where Follow_ID = ?)
To see a list and whether you're following
Select f.User_ID,
Case When ? In (Select User_ID From Follows Where Follow_ID = f.User_ID) Then 'Yes' Else 'No' End
From Follows f
Where f.Follow_ID = ?
#Shudder makes a good point, you may see performance increases (especially if this is a large table) by using a join instead of a subquery.
SELECT him.user_id, IF(i.follow_id,'yes','no') AS i_follow_him
FROM Follows him
LEFT JOIN Follows i ON (i.follow_id = him.user_id AND i.user_id = ?)
WHERE him.follow_id = ?
I made it easier by adding your own id and user No 4.
select follow_id
from follows
where user_id=2 and follow_id IN (select user_id from follows where follow_id=4)

PHP contest Logical

In one of my web application in php there is a contest section . It contains a multiple choice 10 questions , Each has 4 options .
After user filling the form I am saving the answer as comma separated values in a db . like follows:
user | answer
-------------------------------------
112 | 1,7,8,9,8,5,2,3,6,7,9,6
I got a answer key same as the use's filled answer key ..
What is the best logical method for evaluate the users input and find out the highest scored user?
As mentioned in the comments, this isn't the best way to store data, but I'd evaluate like this:
$query = mysql_query("select * from `table` where 1",CONNECTION_IDENTIFIER) or die("die message");
$answer_key = array(answer1,answer2,etc);
$high_score = 0;
$high_scorer= "";
while($r=mysql_fetch_array($query)){
$users_answers = explode(',',$r['answer']);
$user_score = 0;
for($i=0;$i<10;$i++){
if ($answer_key[$i]==$users_answers[$i]){
$user_score++;
}
}
if ($user_score > $high_score){
$high_score = $user_score;
$high_scorer = $r['user'];
}
}
echo "High scorer is $high_scorer with $high_score points";
if you have answers with scores like that:
$answersRating = array(1 => 0, 2=> 1, 3 => 3, 4 => 2, ....) when selecting answer 1 he got 0 points, for 2 => one point, for 3 => 3 points and so on. You can do something like that:
$score = array_sum(array_intersect_key($answersRating, array_flip(explode(',', $userAnswersStringFromDB))));
I think you should structure your DB like this:
NOTE: This is bare minimum, you of course would add extra fields to questions like name, description, etc
answers | id, user_id, question_id, answer
questions | id, contest_id, correct_answer
user | id, name
Then you could get everything with a query.
Top Score:
SELECT u.name,count(*) as Score FROM user u, answers a, questions q WHERE u.id=a.user_id and q.id = a.question_id and q.correct_answer=a.answer WHERE q.contest_id=XXX ORDER BY Score

MySql return only one instance of duplicate entries

Hi I have a table with names and numbers entered along with other data . The table called events contains many instances where the name and numbers are the same but the other entries are different. I want to perform a search using names so I can display the number. But in my search I only need to return one instance of a name . The table is like this
Name Number Responisble Position
Paul 8455 Chorley t7
Dave 3821 PR south f5
Paul 8455 PR North p9
Paul 8455 Leyland t6
Dave 3821 Ribbleton r4
and my script is this
$condition = "name LIKE 'Paul' ";
$result = mysql_query("SELECT * FROM events WHERE $condition ") ;
while($row = mysql_fetch_array($result)) {
The script is not complete but I hope you can see that the results would return 3 results but what i want is a result with just one for each name
I hope this makes sense ! thanks for any help
$condition = "name LIKE 'Paul' ";
$result = mysql_query("SELECT * FROM events WHERE $condition GROUP BY name") ;
try using distinct -
SELECT DISTINCT (columns) FROM (table) WHERE (condition)
edit probably disregard this, mis-understood your question i think
MySql return only one instance of duplicate entries
You can either use group by or distinct in the select statement see http://dev.mysql.com/doc/refman/5.1/en/select.html
In your example it would be
$condition = "name LIKE 'Paul' ";
$result = mysql_query("SELECT * FROM events WHERE $condition GROUP BY name") ;
while($row = mysql_fetch_array($result)) {
SELECT name, number FROM events WHERE $condition GROUP BY name, number

mysql select and where over several tables (very tricky)

I have 4 Tables (listed bellow) and need:
get last 10 Chats from Room 3 without banned users
show nickname for fromuserid
HIDE Users $userid dont like to see table "HIDE"
Table 1 "chats"
ID(autoinc) fromuserid roomid text
1 23 3 bla
2 14 1 bla
3 11 3 bal
Table 2 "user" /shorted/
ID(autoinc) nickname banned
1 chris 0
2 paul 1 // 1 = banned
Table 3 "hide"
ID(autoinc) orguser hideuser
1 12 3
2 33 12
Right now i solved it with PHP Routine, but I have to go through EACH result and make always a new query, that needs too long;
$userid = 1; // actual user
// List all chats and show userid as nickname
$sql_com = "SELECT user.id, user.nickname, chats.text, chats.id ".
" FROM chats, user".
" WHERE ".
" chats.fromuserid = user.id ".
" AND chats.roomid = 3 ".
" AND user.banned != 1 ".
" ORDER BY chats.id DESC";
$result = mysql_query ($sql_com);
$count = 0;
while ($row = mysql_fetch_array($result, MYSQL_NUM))
{
$dontshow = false;
// Filter : dont show users $userid dont like to see (table "hide")
$sql_com2 = "SELECT id from hide WHERE ( (orguser = ".$userid.") AND (hideuser = ".$row[0].") ) ";
if ($result2 = mysql_query ($sql_com2))
{
if (mysql_num_rows($result2) > 0) $dontshow = true;
}
// Output
if ($dontshow == false)
{
$count++;
echo "Nickname: ".$row[1]." Text: ".$row[2];
}
if ($count > 10) break;
}
Btw. I made already some improvments, so the actual question may not fit with all answers (thanks for your help till now)
Finaly its now just about to integrate the filter "dont show people listed in table "hide" for my actual user".
I think you need something along these general lines. I've done it slightly different from your question. Instead of getting the top 10 then removing records. It gets the top 10 records which would not be hidden.
SELECT c.ID, c.fromuserid, c.roomid, c.text, u.nickname
FROM chats c
JOIN user u ON c.fromuserid = u.id
where c.roomid = 3 AND user.banned = 0
AND NOT EXISTS(
SELECT * FROM hide h
WHERE h.hideuser = c.fromuserid
AND orguser = $userid)
ORDER BY c.ID DESC
LIMIT 0,10
Not tested but it would be something like:
$sql_com = "SELECT us.id, us.nickname, ch.text, ch.id ".
" FROM chats ch, ".
" user us, ".
" hide hi, ".
" banned ba, ".
" WHERE ".
" us.id != hi.hideuser ".
" us.id != ba.user ".
" us.id = ch.fromuserid ".
" AND ch.roomid = 3 ".
" ORDER BY ch.id DESC LIMIT 0,10";
Although I can't immediately find a simple way to answer your question as-is, I can point you in the right direction:
http://dev.mysql.com/doc/refman/5.0/en/subqueries.html
Using subqueries should enable you to go and select from both blocked and hidden tables, and using those in your original query.

Categories