How to dynamically select a table from mysql using PHP - php

I created an html that has a formulary that let you choose between four different options:
<select name="especie">
<option value = "1"> Hyundai </option>
<option value = "2"> Renault </option>
<option value = "3"> Ford </option>
<option value = "4"> Fiat </option>
</select>
Each of these options correspond to one table in a mySQL database (let´s say it´s called companies), and have the same variables. The html then lets you perform the query, and I want it to display the information according to the table you have previously chosen.
$query = "SELECT * FROM $table WHERE brand LIKE ´%$brand%´;";
So what I want is to create a PHP that chooses dynamically the table ($table) depending on the chosen option by the user (in the first chuck of code).
Any help would be really appreciated it.

Without re designing your DB structure - which could be the best course of action, there are two easy ways to do this. You could do it basically the way you said. If choosing this method you need to make sure that the table is being selected by a key from an array of tables so it is a safe input like so:
$tables = ["table1" => "table1","table2" =>"table2"];
$query = "SELECT * FROM ".$tables[$table_key_from_input]." WHERE brand LIKE ´%$brand%´;";
But this is not ideal as, when tables are added removed all code like this needs to be updated.
Another way of getting the desired outcome would be to make a database view which is a union of all the tables (plus the table name in an extra column) then you can just select from the view every time using the table as a variable supplied by the user input.
You can learn about views here: https://www.w3schools.com/sql/sql_view.asp
And see how to make a union here: https://www.w3schools.com/sql/sql_union.asp
The view code would look a little like this:
CREATE VIEW view_name AS
SELECT *, 'table1' AS 'table' FROM table1
UNION
SELECT *, 'table2' AS 'table' FROM table2
Then your query would be like this:
$query = "SELECT * FROM view_name WHERE brand LIKE ´%$brand%´ AND table = $table;";
(But ideally using PDO!)
Also if you do it this way if you ever re think your db structure and perhaps do what was suggested by El_Vanja in the comments you can, and by deleting the view and giving the table the same name the code wouldn't even have to change!

Related

get list from table used to create "filter button"

This must be something trivial but long to explain. I cannot form good question for google. I dont know if I should get this result in SQL query or I need to change PHP part which includes sql query. (My knowledge is small, I am making my own very simple planner website but im stuck on creating button for filtering options.)
Imagine I have table named “Records” with 3 columns “ID, Item, Category”.
In categories I write all data in CAPITAL LETTERS and categories can be repeating.
So example table Records looks like this(in columns layout like this: id-item-CATEGORY):
1-sleep-HEALTH 2-ate breakfast-FOOD&DRINK 3-drank
coffee-FOOD&DRINK 4-took eyedrops-HEALTH 5-tram to
work-TRAVEL
I know how to list all data from column Category, but I want to avoid repeating categories. I need to get list of categories like this (Health and Food&drink does not duplicate):
HEALTH FOOD&DRINK TRAVEL
So with this list I can than via php generate html select tag options.
In php part I would use something like this:
$query1=mysqli_query($db,"select * from Records asc”);
while($query2=mysqli_fetch_array($query1)){
echo “<option value=“.$query2[‘category_option’].”>”.$query2[‘category_option’].”</option>”
};
So the result HTML will look something like this.
<select>
  <option value="HEALTH">HEALTH</option>
  <option value="FOOD&DRINK">FOOD&DRINK</option>
  <option value="TRAVEL">TRAVEL</option>
</select>
Can you please point me right direction? Or mention some best practice to reach this kind of functionality. Thanks to all which try to help.
Use DISTINCT in your SQL:
SELECT DISTINCT Category FROM Records
No duplicates will be returned.
Have a play with it on this link https://www.w3schools.com/Sql/sql_distinct.asp
Note that now we are only fetching one column here instead of *.
You can also use GROUP BY:
SELECT * FROM Records GROUP BY Category
https://www.w3schools.com/Sql/sql_groupby.asp

Selecting multiple fields from <option> and adding them to database

Background:
I am creating a three tier e commerce website which sells books. Within my website I have created a form (only accessible to staff members) which allows the staff member to add a new book to the system (the database).
At the moment I have a table within my database which records the following data:
book_isdn // unique identifier of each book.
book_cat
book_title
book_author
etc..
Along with this, I have created a table for book categories which stores the following:
cat_id
cat_title
I have defined the following rows in the categories table:
cat_id 1 = Business books
cat_id 2 = Computing books
cat_id 3 = Science books
cat_id 4 = History books
etc
The problem:
In the form which allows a staff member to add a new book, I have a list:
<select multiple name="b_category" style = "width:150px" required>
<?php
$get_cats = "select * from categories";
$run_cats = mysqli_query($connect, $get_cats);
while ($row_cats = mysqli_fetch_array($run_cats)) {
$cat_id = $row_cats['cat_id'];
$cat_title = $row_cats['cat_title'];
echo "<option value='$cat_id'> $cat_title </option>";
}
?>
</select>
I want to add a new book to the 'books' table with the corresponding cat_id for the category to which the book belongs to (i.e. business, computing etc.).
However, a book can also be in two categories, i.e. a book can be both in the field of business and computing.
The question:
How can I alter the form so that it selects multiple options from and adds them to the database, along with the cat_id?
For example:
if using the form I complete all other fields and select computing and business from the list, I want it so that upon clicking "Add new book", the form data is sent to the 'books' table where I will be able to see the new book and under the field of book_cat, I will see 1,2.
I am completely stumped. Is there any way to approach this issue? I hope I have explained this well.
Thanks.
Ok, let's start with something you have not asked for.
a) DB design
Please do not store a concatenated id value like 1,2 in book_cat.
That makes lookups and search hard, because you need to fetch & split every single time. That might only work for really small systems.
What you are looking for is a relation table from books to categories.
Name it like this books_to_categories, with book_id and cat_id.
Query: SELECT cat_id FROM books_to_categories WHERE book_id = 2;
Result: array one or more ids, then resolve the cat_id to it's name (cat_title) via the category table.
The keyword here is database normalization.
b) Formular
Ok, you have a drop down list box, where you can do multiple selections.
Now, the values of these selections need to be transfered to the server side.
One trick is to use array syntax, instead of
<select name="b_category" size=4 multiple>
just use
<select name="b_category[]" size=4 multiple>
and on the server-side var_dump($_POST['b_category']); to see the values received. Then simply iterate over the values of the array and make your database entries.

Multiple selection if some form option are selected

I want to make a dynamic filter system based on a html form with multiple options, some like that:
<form>
<select>
<option></option>
-//-
</select>
<select>
<option></option>
--//--
</select>
</form>
and make a sql query but with condition from form, and every option have an "All" option which means no condition.
So i was thinking to make something like that, with multiple for and N^2 if condition, but is to much code and it's not faster... to make 16 if-uri and 16 SELECT for a 4 option form ...
So, know someone a faster solution ?
Thanks.
Edit
So let say i have a database users with ID, Name, Age, City.
I make a form with 3 option (1 for Name, 1 for Age, 1 for City) so i can see only some users, let say i want all users which have name Nick and it's from Miami.
I need to my SELECT condition to exclude the condition for AGE, like now select will be :Select * from Users where Name = 'Nick' and City='Miami', but if i want to see users with Age= 18 and City NY my select will need to exclude the condition for Name, and be like: Select * from Users where Age= 18 and City='NY'.

How to seperate results from a mysql select

I apologize for this beginner question but unfortunately it is my level.
I have a fairly simple web page for my work, it is a index.php page that when opened goes out to a DB and retrieves the contents of a certain column. It then places the results in a drop down pick list.
Here is my problem, this column is a list of materials for customers. Some customers have more than 1 different type of material, while others have one.
Therefore my pick list can look like:
Apple /n
Orange; Apple; banana/n
banana;peach /n
orange/n
I am trying to come up with something that when I pull the data from the mysql DB that my php seperates the materials and only provides unique items.
Here is my code for creating picklist:
<p><select size="1" name="material" ID="material" onChange="showfield(value);">
<option value=''><None></option>;
<?php
while ($row = mysql_fetch_array($query))
{
$rowmod = strtr($row['material']," ","_");
echo "<option value='$rowmod'>$row[material]</option>";
}
?>
Here is my mysql select:
$query="select distinct material from TABLE-A order by material";
Update:
I think my Mysql is right, I think I played around with the php strtr and I was able to remove the ; and add lines in, but now I do not know how to make it cycle through and create my
here is the new code:
$row[product]";
}
?>
some output from my $row will have only one product, some will have 2 or more, I wonder if I have to put another while loop after the $rowmod?
I have a feeling I am close, but hoping for some guidance.
First of all, you should make a material table, indexed with an auto_increment id, and use that ID in what you call TABLE-A in a column material_id. Like that you'll have a list of unique material in one table dedicated to it, where you can even add some columns for the details of the material, etc..
Then I am unsure of your needs/use-case, but it looks like you'll need a customer_material table to link a customer with its material(s) so that you know which customer uses which material. It would have an id auto-incremented, as it should always be for any table for better practices, a customer_id and a material_id, with an unique index on the both last columns (customer_id+material_id) to be sure you link one material to one customer only once and not many time each material for the same customer.
Then when you'll need to list the materials for a given customer, just use this query:
select m.id, m.name
from customer_material cm
join material m on cm.material_id = m.id
where cm.customer_id = YOUR_CUSTOMER_ID
If you need to list all materials uniquely, you;ll then need this query:
select m.id, m.name
from material m
order by m.name /* optional, to order by the material name */
And voila. As I am unsure of your use-case the schema of the DB might be a bit different, but I think anyway the main problem in your issue is that the DB is not well architected. Lemme know if I something is unclear here.
You mentioned that different customers have different materials, but that is not reflected in your SQL query because there is no WHERE clause, meaning that you are selecting all unique values from the materials table regardless of any condition. But with that aside, I think that if you change your code slightly you will get some data.
$query="select distinct `material` from `TABLE-A` order by material"
<p><select size="1" name="material" ID="material" onChange="showfield(value);">
<option value=''><None></option>;
<?php
while ($row = mysql_fetch_assoc($query))
{
$rowmod = strtr($row['material']," ","_");
echo "<option value='$rowmod'>$row['material']</option>";
}
?>

how to populate a drop down list and save it to your database?

I would like to populate a drop down list of moods and save it to my database with a time stamp. And at the same time connect the moods with the current user. How should I approach this?
In my database, I have a table called "checkin" which includes: ID, Time, FKMoods (foreign key to list of moods) and FKUsers(foreign key to users).
Right now I have a form called checkin in "page.php":
<form id="checkin" action="checkin/checkin.php" method="POST">
<label for="checkinMood">Select your current mood :</label>
<select id="checkinMood" class="SelectMood"></select><br />
<input type="submit" id="checkin-button" value="Update!" />
Steps to accomplish this
Select the moods from a moods table
Loop through the results and put them into a select input
Upon submitting, update the given mood into the user table
Don't save the html option list to the database. It's too hard to edit when you want to change the options. Store a list of moods like this:
CREATE table moods
mood_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
mood VARCHAR(45);
To make the option list, query the mood table and loop through the results creating options as you go:
<option value='{$mood["mood_id"}'>{$mood["mood"]}</option>
To store the user's mood, update the users table with the mood_id.
Do a joined sql query to pull the foreign keyed values/rows from other tables first - assuming you are using mysql - using very basic functions everyone knows (without going into whether you are using mysqli or any pdo or lib) :
SELECT * FROM checkin c LEFT JOIN listofmoods lm ON c.FKMoods = lm.FKMoods LEFT JOIN listofusers lu ON c.FKUsers = lu.FKUsers ORDER BY c.ID ASC
(or however you want to sort)
Now you got all the fields you need. then run a mysql fetch to create the list, something like :
$query=mysql_query(-thequery listed above-);
while($fetch=mysql_fetch_assoc($query))
{
$moodselect.='<option value="'.$fetch['FKMoods'].'">'.$fetch['whateverfieldlabelthemoodnameyouhaveonmoodstable'].'</option>';
}
this will pop you a $moodselect with the necessary options being there. you can then shove this in to the select you have in your example.
you would probably have to put in the user id in some hidden field in your form. or if your user system recognizes the user automatically from session you can just use it when the form is posted to checkin.php.

Categories