Select row from DB based on 3 different values - php

Currently my DB looks similar too...
ID Username Interest
04 Tommy Soccer
04 Tommy Internet
32 Jack Soccer
32 Jack Swimming
32 Jack Boxing
I have a page on my website where the user can specify his/her interests and depending on what they enter, those with the same interests will be displayed.
So If Tommy was to visit my page and add "Boxing" as an Interest Jack would show up as he has "Boxing" listed within the table.
I need to write a query to do this but i'm unsure of the best way to do it as i'm still very new to PHP, would something along the lines of...
mysql_query(SELECT * FROM interests_table WHERE Interest = $interest1 || $interest2 || Interest3);

mysql_query("SELECT * FROM interests_table WHERE (Interest = $interest1 OR Interest = $interest2 OR Interest = $Interest3)");

Even shorter:
mysql_query("SELECT * FROM interests_table WHERE Interest IN ($interest1, $interest2, $interest3)");
Of course you will need to add necessary parameters escaping for more secure code.
If you have all possible values you want to search for in array, the code may look like this:
$interests = array('boxing', 'swimming', 'speedway');
// ... query preparation
$result = mysql_query("SELECT * FROM interests_table WHERE Interest IN (" . implode('", "', mysql_real_escape_string($interests)) . ")");
// rest of the code ...
But this code is only effective for small sets of data (few to hundreds). If you'd have more interests on list, you should find more effective way.

Related

Failing to search for full names while querying mysql with php

First time asking on SO. I currently am trying to search a database where the first and last names are seperate. Example:
player_id | first_name | last_name
191 John Smith
192 Larry Citizen
193 Benjamin Example
I am trying to allow users to search this list using a full name only. I currently have the following code once the user hits submit, it calls usersearch.php.
session_start();
include '../con.php';
$player = $_POST['name'];
$sql = "SELECT * FROM characters WHERE (concat(first_name,' ',last_name)) = ($player)";
$result = mysqli_query($conn, $sql);
if (!$row = mysqli_fetch_assoc($result)) {
echo "Found no-one with the name $player. <a href='../search.php'>Try Again?</a>";
} else {
$_SESSION['selplate'] = $row['plate'];
$_SESSION['selname'] = $row['first_name, last_name'];
header("Location: ../profile.php?player=$player");
}
No matter the query it will not find users and always returns "Found no-one with the name $player. Try again?"
This was supposed to be the easy part of this project and I am pulling my hair out.
I have spent over an hour searching SO and Google to no avail so it must be my code? afaik it should work.
you need qoutes ' ' around player because its a text and also concatinated.
if you search Johnsmith it will return nothing
if you search John Smith it will give you result, because in your concat you are adding a space between words
"SELECT * FROM characters WHERE concat(first_name,' ',last_name) =('".$player."')"
I would change it to a fulltext index on both first and last name, change the word min on full text indexes. then I would search using ( some guy as the name )
MATCH( first, last )AGAINST('+"some" +"guy"' IN BOOLEAN MODE )
delete the white-space from concat function in query and other thing is use $player = str_replace(' ','',trim($_POST['name'])) instead of $player = $_POST['name'].
$SQL = "SELECT * FROM TABLE_NAME WHERE concat(first_name,last_name) = '".$player."'"
i suggest PDO with prepared statements...
assume you are searching 'benjamin example' and query will check for 'benjamin example' so str_replace will output as benjaminexample.and the concated first_name and last_name will match it.
hope it help.
ignore if it sound silly.

mysql results sort by array

I think I don't understand how 'sort' works, so please don't judge me. I really searched all day long.
I have a movies table with actors column. A column it's named "actors". The actors are links separated by space " ". The order of the links it's very important.
I explode the links into an array which looks like [0]-> link0, [1]->link1, ...
I have the actors table where every actor also has it's movies links. I don't want to make 20 different sql searches so I made a variable with all the links I want, like this ( WHERE actor_link = link1 OR actor_link = link2 OR .. )
The problem is this. The search will probably find first the link7, and so my sorting it's gone. What can I do to keep that order from the movies table. I want to display the actors by popularity in the movie, not the order of my database.
Can you give me another method to search the actors without making 'x' sql searches and still keeping the order?
$actors[] = explode(" ", $row['actors_link']);
$x=0;
$actors2 = '';
while ($actors[0][$x]) {
$actors2 = $actors2 . "`link_imdb_actor` = " . "'".$actors[0][$x]."' OR ";
$x++;
}
$actors2 = substr($actors2, 0, -3);
$sql = "SELECT * FROM `actors` WHERE $actors2";
$sql_result = mysql_query($sql) or die(" ");
while ($row3 = mysql_fetch_array($sql_result)) {
echo $row3['link_imdb_actor'];
}
So, the movie Hotel Transylvania has Adam Sandler, Andy Samberg and Selena Gomez. My search shows Selena Gomez, Andy Samberg, Adam Sandler because this is the order from my database. How can I sort the sql results by the order of the actors array? Thank you!
To expand on Arjan's comment, if you want to be able to actually use the actor data (e.g. search with it) I would recommend at least two more tables. One called actors with the fields actorID, firstName, and lastName. The other table would be castings with the fields castingID, actorID, movieID, and castingOrder.
Each castingID will then link an actor to a movie - this would make for easy searches of every movie a particular actor has been in or every actor in a particular movie.
The castingOrder field can be used to maintain the order you want.
I need your existing code to really get the gist of what's going on.
I will make one suggestion in your query. Instead of saying WHERE actor_link = a OR actor_link = b OR actor_link = c do this instead:
WHERE actor_link IN (link1, link2, link3)

Getting mysql row that doesn't conflict with another row

I have two tables that link together through an id one is "submit_moderate" and one is "submit_post"
The "submit_moderate" table looks like this
id moderated_by post
1 James 60
2 Alice 32
3 Tim 18
4 Michael 60
Im using a simple query to get data from the "submit_post" table according to the "submit_moderate" table.
$get_posts = mysql_query("SELECT * FROM submit_moderate WHERE moderated_by!='$user'");
$user is the person who is signed in.
Now my problem is when I run this query, with the user 'Michael' it will retrieve this
1 James 60
2 Alice 32
3 Tim 18
Now technically this is correct however I don't want to retrieve the first row because 60 is associated with Michael as well as James. Basically I don't want to retrieve that value '60'.
I know why this is happening however I can't figure out how to do this. I appreciate any hints or advice I can get.
SELECT DISTINCT post
FROM submit_moderate
WHERE post NOT IN (SELECT post
FROM submit_moderate
WHERE moderated_by = 'Michael')
PS: not sure, but in some cases it probably would worth changing select-part of the nested query to SELECT DISTINCT post
Suppose $user = 'Michael';
If u really don't want the 1st row of user as you said that james matches with the michael in posts
then go for
$post = mysql_query_first("SELECT post FROM submit_moderate WHERE moderated_by='$user'");
$get_posts = mysql_query("SELECT * FROM submit_moderate WHERE moderated_by!='$user' and post!='$post');
or
$get_posts = mysql_query("SELECT * FROM submit_moderate WHERE post NOT IN (SELECT post FROM submit_moderate WHERE moderated_by = 'Michael') and moderated_by != 'Michael' ");

A mySQL count query to return a numeric value?

I have a database set up with a few hundred customers in, all of them are unique. However, some customers are linked together, if they are part of a family. E.g.
I have a family ID that links these customers, e.g. Mrs A. Jones is customer number 005 and Mr B.Jones is customer number 017 and as they are related, I have assigned them family ID 001.
I've searched online, but no where seems to be that useful at providing me with any assistance into how I could do some sort of mySQL count to echo the number of people WHERE familyID = 001.
Also, is there any way, I could return both seperate customer records, given the mySQL search criteria of familyID = 001.
Many thanks,
Tom.
EDIT: Realised I'd put passenger instead of customers, my bad! Also, the names are made up for obvious DPA reasons :)
You want the COUNT() function
SELECT count(*) AS count FROM customers WHERE familyID="001"
You can replace the * with a column name, makes it a little faster.
$sql='SELECT count(familyID) AS count FROM customers WHERE familyID="001"';
Here you can get number of customers of familyID= 001
But where is this passenger came from? what is the relation with customer?
If it is about customer not passenger then
$sql='SELECT * FROM customers WHERE familyID="001"';
$query=mysql_query($sql);
$count=mysql_num_rows($query);
while($fetch_arr=mysql_fetch_array($query)){
$familyName=$fetch_arr['name'];
echo $familyName;
}
You can get all records from * and from $count u can get number of customers
You can use the count Function in such cases .it can be used as.
Select count(*) form TABLE NAME where familyID = "001"
If you want the unique records as well as the count use this, with the OVER function:
SELECT customers.id,
customers.additional_columns,
count(1) OVER (PARTITION BY familyID) AS count
FROM customers
You can do something like
$result = mysql_query("SELECT * FROM families where familyID='001'", $link);
$num_rows = mysql_num_rows($result);
source
For your first question, this will do
$result = #mysql_query("SELECT * FROM tbl_name WHERE familyID = '001'");
echo mysql_num_rows($result); //This line should display the count

how do I loop inside a loop with PHP in MySQL?

table persons
name | details
------------------
mathew| tax,home,car,insurance
john | job,tax,employ
neil | tax,home,car,job
yancy | consultant,rent,family
lucy | home,car,insurance
I want loop through this table and search with details then saved result to another table called persons1
name | names
------------------
mathew| neil,lucy,john
neil | mathew,lucy,john
john | mathew,lucy,neil
so far I coded something like below but not working
mysql_connect("localhost", "root", "pass");
mysql_select_db("database");
$query = "SELECT * FROM persons";
$result = mysql_query($query);
while($r = mysql_fetch_array($result))
{
$exp = explode(",",$r["details"]);
$sql = mysql_query('SELECT * FROM persons WHERE MATCH (tags) AGAINST ("+$exp[0]" "+$exp[1]" "+$exp[2]" IN BOOLEAN MODE)');
$result = array();
while($row = mysql_fetch_assoc($sql))
{
array_push($result,$row['name']);
$name = implode(",",$result);
mysql_query("INSERT INTO person_new (name,names) VALUES (\"".$r["name"]."\", \"".$name."\")");
}
}
IT is very sad that nobody can give an answer to my question about my code. instead of looking into my design I request you to look into my code and tell me where I made a mistake..i am doing something different than what it sees and this is why I request you to check my code...
Your problem would be better solved via database normalization.
Storing data like tax,home,car,insurance in a single column, then parsing it to search is a Very Bad Idea.
First of all, it'd be nice if you'd tell us what doesn't work.
Having said that, I suspect (at least one of) your error(s) is here:
'SELECT * FROM persons WHERE MATCH (tags) AGAINST ("+$exp[0]" "+$exp[1]" "+$exp[2]" IN BOOLEAN MODE)'
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
This will literally give you the query AGAINST ("+$exp[0]" "+$exp[1]" "+$exp[2]" IN BOOLEAN MODE), which is likely not what you want. You need to concatenate the string, or use a double quoted string:
'SELECT ... AGAINST ("+' . $exp[0] . '" "+' . $exp[1] . '" "+' . $exp[2] . '" IN BOOLEAN MODE)'
or
"SELECT ... AGAINST (\"+$exp[0]\" \"+$exp[1]\" \"+$exp[2]\" IN BOOLEAN MODE)"
I'm with #Dolph though, this is not a good database structure, and if you're going to redesign it later anyway (careful with saying "later", that usually never happens), you should just do it now.

Categories