I have 2 table
Table-1 - user
user(ID.Name,Class)
Table-2 - Category
Category(ID,user_id,cat_id)
if user input a data from text field the how to search data from both table
Just query both tables and use the 'OR' operator for the columns you want to search in
SELECT * from user, category WHERE user.id=[text field] or category.user_id=[text field] or category.cat_id=[text field]
PHP Example: (assuming you are using MySQL database - you also need mysqli enabled in your php.ini file)
$mysqli = mysqli_connect(HOSTNAME, USERNAME, PASSWORD, DATABASE);
if (mysqli_connect_errno($mysqli)) {throw new exception("Failed to connect to MySQL: " . mysqli_connect_error());}
$sql = " SELECT * from user, category WHERE user.id='".$text_field."' or category.user_id='".$text_field."' or category.cat_id='".$text_field."'";
$rows = $result->fetch_array(MYSQLI_ASSOC);
foreach($rows as $row){
print_r($row);
}
This should get the records and show you the response from the array.
I hope you have added primary key & foreign key relations to these tables, in-order to grab data from both the tables you have two ways, either do multiplication of both table and bring in all the data else make use of JOIN that does the same in efficient way
Hoping to have your table schema as
USER [table] having id, username, name, password
CATEGORY [table] having id, name, description, user_id
So the query will become
SELECT U.*, C.id as cat_id, C.name as cat_name, C.description as cat_desc
FROM USER U
JOIN CATEGORY C ON C.user_id = U.id
If you have user inputting data from input fields, that becomes a filter query to be added in our above query, assume user is entering Name of category and wants the result set of the same then the above query gets added with WHERE clause as below
WHERE C.name LIKE '%{INPUT FIELD CONTENT HERE}%'
I have used LIKE clause above to allow us doing PARTIAL search
Hope this helps you
Related
I'm making a search engine in which a page visitor can search for music artists based on 4 different attributes which the artists will have a rating of from 0- 100 and by entering the minimum value of a specified attribute, the visitor can view the list of artists with ratings greater than or equal to the desired value. After the query I have the fetch array and foreach statement already set but I am having trouble with the query.
I've tried the following query statement. It's one cohesive statement:
SELECT users.username, databaseimage.profile
// users.username is artists username
// databaseimage is table where profile pic is stored
FROM users
JOIN databaseimage ON users.id = databaseimage.user_id
JOIN attributes ON users.id = attributes.userid
// user.id, database.user_id, and attribute.userid all correspond to the id of a specified artist
// attributes is table where attributes are stored
The above gets me all the data that I need. Below is the part I need help with. I want to narrow the data down such that only the data corresponding to artists with attribute ratings (as attr) greater than $selectnumber (Number specified by the visitor) is in the the result array. This what I have tried.
WHERE attribute.userid
HAVING COUNT() IN (
SELECT userid, ($attribute DIV TotalRatingEntries) as attr
FROM attributes
WHERE attr >= '$selectnumber'
)
A far as I understand data structure I can propose the query below:
SELECT
users.username,
databaseimage.profile
FROM
users
JOIN databaseimage ON users.id = databaseimage.user_id
JOIN attributes ON users.id = attributes.userid
WHERE
attribute.userid IN
(
SELECT
userid
FROM
attributes
group by
userid,TotalRatingEntries
having
sum(attribute)/TotalRatingEntries >= '$selectnumber'
)
Please provide more details about these 3 tables, maybe I misunderstood something.
I have a join and the result of the join is correct, but then I want to display a variable, but it's not in variable format like $variable, it's in the format $row['field'], however, it doesn't display the correct value because the field name is in both tables.
Sometimes it displays the left one, sometimes it displays the right one. i don't know how to force it to display the one i want.
So for example i have this query:
SELECT
user_table.*, user_groups.*
FROM
user_table
LEFT JOIN user_groups ON user_groups.groupid = user_table.usergroup
WHERE
user_table.client = "0"
AND user_table.usergroup != "1"
ORDER BY
user_groups.name ASC
Not going to put in every field, because there are too many, just a few to get the idea.
user_table:
userid, username, usergroup, fname, sname, company
user_groups:
groupid, name, userid
The JOIN will have a result like the following:
userid username usergroup fname sname company groupid name userid1
1129 whatever 2286 first last abc 2286 abc 0
Then i begin to echo all the fields like so:
while ($row=mysql_fetch_assoc($result)) {
echo $row['username']." ".$row['userid']." ".$row['company']." ".$row['fname']." ".$row['sname']." ".$row['username'];
}
All the data will be correct except the userid. it will use the zero(0) instead of the 1129 which is the one i want.
I have tried all of the following for the userid echo:
$row['userid']
$row['userid0']
$row['userid1']
$row['userid[0]']
$row['userid[1]']
$row['userid'][0]
$row['userid'][1]
Nothing works. it either displays the wrong one from the result, or displays nothing.
PHP tries to map the column names into key => value pairs. If there is a column with a duplicate name, then you'll only get one.
Map out second userid columns in MySQL using the AS keyword (http://www.w3schools.com/sql/sql_alias.asp) to give the second userid field a different name.
SELECT
user_table.*, user_groups.groupid, user_groups.name, user_groups.userid AS group_userid
FROM
user_table
LEFT JOIN user_groups ON user_groups.groupid = user_table.usergroup
WHERE
user_table.client = "0"
AND user_table.usergroup != "1"
ORDER BY
user_groups.name ASC
You can then access the two fields like this:
$row['userid']; // client.userid
$row['group_userid']; // user_groups.userid
I have the following as my results.. the problem is I only want 1 field from the balances table and 2 fields from the userinfo table... if I replace the * with say user,avatar I get my error...
$result = mysql_query("SELECT * FROM userinfo INNER JOIN balances ON userinfo.user = balances.user ORDER By balance DESC,avatar");
if (!$result) {
die("Query to show fields from table failed");
I do not know the proper form and cant find it anywhere
TIA
John
as user column exists in both the joined tables userinfo and balances you need to prefix the table name while accessing the column
Try
SELECT userinfo.user, userinfo.avatar, balances.balance
FROM userinfo
INNER JOIN balances
ON userinfo.user = balances.user
ORDER By balance DESC,avatar
I'm having difficulty trying to find the best way to get my results from a table. I want to get the targeted row from a table by one using the primary key from another using a foreign key.
The tables are would be set similar to this(minus a lot of other attributes for space):
user Table:
user_Id(pk)
name
type
venue_Id(unique/indexed)
venue Table:
venue_Id(fk)
rating
Logic flow is: user_Id is provided by a session variable. Query DB table 'user' to find that user. Go to type of user to identify if user is person or venue. Assuming user is venue, go to DB table 'venue' and query table for rating using foreign key from unique/indexed venue_Id from user table.
The query looks like
SELECT rating FROM `venue` WHERE `user_Id` = '$user_Id' AND `type` = 'venue'
Is this possible, and if so, what is the correct way to go about it?
You have a few ways to retrieve this information.
Using JOIN:
SELECT v.rating
FROM venue v INNER JOIN user u
ON v.venue_id= u.venue_id
AND u.`user_Id` = '$user_Id' AND u.`type` = 'venue'
Using an IN sub-query
SELECT rating
FROM venue
WHERE venue_id IN (SELECT venue_id FROM user
WHERE `user_Id` = '$user_Id' AND `type` = 'venue')
BTW, you should consider protect your code from potential SQL Injections
Its a bit unclear you explained that way.
From what I get, there is 2 table User and Venue.
In User table u have: user_id, venue_id, name, type.
While in Venue table u have: venue_id, rating.
You are expecting to get rating (Venue Table) while you use the WHERE clause in user_id and type which both stored on User Table.
Your Query:
SELECT rating FROM venue WHERE user_Id = '$user_Id' AND type = 'venue'
It is impossible to get it done like above because you are selecting from venue table while user_id and type is not from venue table. So it will make it unidentified even you have chaining the FK. Because FK will only to show and make some constraint to parent child table.
The query should be something like this:
SELECT rating FROM venue v JOIN user u on v.venue_id = u.venue_id WHERE u.user_Id = '$user_Id' AND u.type = 'venue'
Correct me if I am wrong..
Combining rows from two tables based on the tables having columns with equal values is called an equi-join operation, it's the pattern we typically use to "follow" foreign key relationships.
As an example:
$sql = "SELECT v.rating
FROM `venue` v
JOIN `user` s
ON s.venue_Id = v.venue_Id
AND s.type` = 'venue'
WHERE s.user_Id` = '" . mysqli_real_escape_string($con, $user_Id) ."'"
This isn't the only pattern, there are several other query forms that will return an equivalent result.
As an example of using an EXISTS predicate:
$sql = "SELECT v.rating
FROM `venue` v
WHERE EXISTS
( SELECT 1
FROM `user` s
WHERE s.venue_Id = v.venue_Id
AND s.type` = 'venue'
AND s.user_Id` = '"
. mysqli_real_escape_string($con, $user_Id)
."'"
)";
The original query appears to be vulnerable to SQL Injection; the example queries demonstrate the use of the mysqli_real_escape_string function to "escape" unsafe values and make them safe to include in SQL text. (That function would only be appropriate if you are using the mysqli interface. Using prepared statements with bind placeholders is another approach.
I have an issue regarding PHP, MySql and foreign keys. I understand foreign keys and have a relationship between two tables in place as described:
Let's say I have 2 tables: 'vehicles' and 'manufacturers'.
Each row in the 'vehicles' table includes a manufacturerId column which is a foreign key relating to the 'manufacturers' table. This is set up nicely, in PhpMyAdmin when I insert a new row into the 'vehicles' table the manufacturerId column has a drop-down menu with the manufacturerId's listed as options. Very nice.
BUT: In my application, of course, I don't want the user to have to know (or have to guess) what the correct number for 'Ford' or 'BMW' is when they add a new vehicle, I want them to be able to choose the manufacturer by name.
But how does the application know the manufacturer names based on the manufacturerId? How does the application know there is a relationship between the 2 tables? Am I supposed to hard-code the relationship in the application? Am I supposed to modify all my queries to have a JOIN between the 2 tables? Or hard-code a query to get a list of manufacturers every time I want to display a drop-down of manufacturers?
Is there a way for the application to know about relationships between tables and be able to display data from a text column instead of the int column used as the ID?
Assuming your 2 table are structured like this:
VEHICLES
id
manufacturerId
vehicleName
MANUFACTURERS
id
manufacturerName
You would create your vehicle manufacturer select menu for users by querying the database like this:
// query the database
$q = 'SELECT id, manufacturerName FROM manufacturers';
$r = mysqli_query($link, $q);
// display a select menu using id and manufacturerName
echo '<select name="manufacturer">';
while($row = mysqli_fetch_assoc($r)) {
echo '<option value="'.$row['id'].'">'.$row['manufacturerName'].'</option>';
}
echo '</select>';
To use the post data from that menu to add a vehicle & manufacturer id to your vehicles table:
$q = "INSERT INTO vehicles (manufacturerId, vehicleName) VALUES ({$_POST['manufacturer']}, '{$_POST['vehicleName']}')";
mysqli_query($link, $q);
Finally, if you wish to select the vehicle name and manufacturer in the same query, you would join the tables like this:
// Select vehicle name and manufacturer for vehicle with id of 1
$q = "SELECT v.vehicleName, m.manufacturerName, v.id AS vehicleId, m.id AS manufacturerId
FROM vehicles AS v, manufacturers AS m
WHERE v.manufacturerID = m.id
AND v.id = 1";
mysqli_query($link, $q);
I think that should answer all your questions in one way or another!