I want to make dynamic menu based on laravel. here's the important information :
table_menu :
contains field name etc. and level_id with varchar type
table_level :
contains id with int type and name of the menu
I use codeigniter and sql
so the idea is, instead of inserting data to table_menu one by one (for example if I've 5 menu and 2 level, that would be 10 menu data in total on table menu).
so I think, the best idea for this is that I just need to insert csv on field level_id in table_menu (level_id => 1(admin),4(user),5(etc). and that will give me 5 menu no matter how much level. right?
But the question HOW? is that even POSSIBLE?
I've tried like this :
$this->db->where('parent', true)->where_in('level_id', $this->session->userdata('level_id'))->get('table_menu')->result();
but It didn't work. can anyone help me?
finally i figured it out!
I read a lot about find_in_set sql query, and finally succeed. here's the final code :
$this->db->query("SELECT * FROM table_menu where FIND_IN_SET( ".$this->session->userdata('level_id').", level_id) > 0")->result();
Related
I was wondering if mysql has a way to look at a column and only retrieve the results when it finds a unique column once. For example
if the table looks like this:
id name category
1 test Health
2 carl Health
3 bob Oscar
4 joe Technology
As you can see their are two rows that could have the same category. Is their a way to retrieve the result where the array will one only return the category once?
What I am trying to do is get all the categories in the database so I can loop through them later in the code and use them. For example if I wanted to created a menu, I would want the menu to list all the categories in the menu.
I know I can run
SELECT categories FROM dbname
but this returns duplicate rows where I only need the cateogry to return once. Is there a way to do this on the mysql side?
I assume I can just use php's array_unique();
but I feel like this adds more overhead, is this not something MYSQL can do on the backend?
group by worked perfectly #Fred-ii- please submit this as answer so I can get that approved for you. – DEVPROCB
As requested by the OP:
You can use GROUP BY col_of_choice in order to avoid duplicates be shown in the queried results.
Reference:
https://dev.mysql.com/doc/refman/5.5/en/group-by-handling.html
By using database normalization, you would create another table with an unique id and the category name and by that link those two together, like
select * from mytable1
on mytable1.cat = mytable2.id
group by mytable1.cat
You can ofcourse also use group by without multiple tables, but for the structure, I recommend doing it.
You can use select distinct:
SELECT DISTINCT categories
FROM dbname ;
For various reasons, it is a good idea to have a separate reference table with one row per category. This helps in many ways:
Ensures that the category names are consistent ("Technology" versus "tech" for instance).
Gives a nice list of categories that are available.
Ensures that a category sticks around, even if no names currently reference it.
Allows for additional information about categories, such as the first time it appears, or a longer description.
This is recommended. However, if you still want to leave the category in place as it is, I would recommend an index on dbname(categories). The query should take advantage of the index.
SELECT id, name from dbname GROUP BY categoryname
Hope this will help.
You can even use distinct category.
Firstly, I'm quite new to PHP having only dived in some three weeks ago but loving it as a new thing to learn! I have a specific problem that I cannot seem to find a solution for via Google. I'm running a test page that will form the basis of a final product for a local recreational club that runs competitions and wants to display the results online on their website.
I've created a MySQL database and called it 'results' and imported as a CSV a sample of competition results. My code to connect to the database works as the page displays the "Database Connection Established" message.
The database contains a table called 'z_any_year_results' and the table structure looks like this:-
Record_Number Field Value
1 Field_1 Value_1
2 Field_2 Value_2
3 Field_3 Value_3
4 Field_4 Value_4
5 Field_5 Value_5
I understand how to select the specific table using
mysql_select_db("results") or die(mysql_error());
$data = mysql_query("SELECT z_any_year_results FROM results")
but I need to echo a specific field from the table in a specific section of the web page. So for example, in one section of the page I need to output the field containing the value Field_1 and nearby on the page the field containing the value Value_1. But in another section of the page I need to output the field with the value Field_4 and nearby on the page, the field containing the value Value_4. So I guess my problem is how to extract a specific piece of data from a table to the exclusion of all other records in the table and outout it as an echo on the web page. I cannot find anything on the web that is written in a simple step-by-stepway to help novices like myself understand.
Can anyone point me in the right direction on how to achieve this?
Many thanks in advance.
You are using a type of data design known as key/value design. In other words, each row has the name of a data item and its value. That's not an ideal sort of design for a beginner to use, because it makes for fairly intricate queries.
To answer your question, if you want a certain named field's value you use this query.
SELECT Value FROM z_any_year_results WHERE Name = 'Field4'
But, maybe you want a design that resembles your application's entities a little more closely.
You might have an entity, a table, called, contestant, another called contest, and another called prize.
contestant is a table with columns like contestant_id, surname, givenname, email etc
e.g. 1 , Ellison, Larry, larry#oracle.com
Then you can use queries like SELECT * FROM contest WHERE YEAR(datestart) = 2016 which will make your queries more closely reflect the logic of your application.
I'm trying to insert diferent numebers (like "10 11 12") into a MySQL field (the numbers come from PHP), but when I do the query, the field only gets the first number.
For example, I do:
UPDATE profile SET subcategory = '10 11 12' WHERE userId = 1 LIMIT 1
And the DB just registers '10'.
Any way to do it?
This happen because you're updating a number, probably an integer, so mysql do the job just for the first number.
If you do this:
UPDATE profile SET subcategory = 10 WHERE userId = 1 LIMIT 1
UPDATE profile SET subcategory = 11 WHERE userId = 1 LIMIT 1
UPDATE profile SET subcategory = 12 WHERE userId = 1 LIMIT 1
You'll just update the category with the third value (12).
I suggest you a user belonging to multiple subcategories so you'll have to create another table. Eg: a table called subcategories with at least two fields: userId and subcategoryId. And then you could do something like this:
DELETE FROM subcategories WHERE userId=1
INSERT INTO subcategories (userId, subcategory) VALUES (1,10)
INSERT INTO subcategories (userId, subcategory) VALUES (1,11)
INSERT INTO subcategories (userId, subcategory) VALUES (1,12)
The first line (delete) is used just to update the user's subcategories, first you delete all older subcategories for the user and then you insert the new ones. In PHP you could use a foreach() to automatize the insertion of multiple values.
You could also have a non unique userId in the table profiles with an entry per user subcategory but it will complicate things.
I hope it could help you
From your problem I guess that the type of your subcategory is integer. What happens when you put string? It is converted. The converter convert it to first proper integer which is 10 space after 10 is considered as string.
What can solve your problem?
Chance db structure and depend on relations.
(bad idea) change the type to varchar for example and then insert will be done(DONT DO IT)
Do multiple updates(it really depends on db structure)
This very much depends on the problem you are trying to solve.
If you are just trying to store a small number of numbers then using the php join and split functions to take a list of numbers and convert to and from a string and store that in a VARCHAR.
A better way to solve the problem would be to understand the layout of your data. Try having a table that links profiles to subcategories. Two columns, one for the profile ID and one for the Subcategory ID. You might find having a search for database normalisation informative.
This presentation looks relatively informative: http://www.sqa.org.uk/e-learning/MDBS01CD/page_26.htm
I am trying to create a small script in PHP to get data from a MySQL Database.
In my database 'companies' is a column called category where i store my the companies' categories in. For example "1|2" or just "2".
Now i want to search for "2" and my database shall return those two entries with the "1|2" and "2" - but that is my problem.
I tried it with LIKE % etc. but nothing worked as i hoped.
Does anyone may help me out with my small PHP script?
I believe it's a bad idea to store categories in the way you do.
If you use LIKE "%2" or LIKE "%2%" or LIKE "2" statements to get compnaies wich belong to category "2", you will receive companies with categories e.g. 21|12.
It'd be better to take categories away from company table. And add 2 new tables: category(id, name) and company_category(id, compnay_id, category_id). This is how it has to be in RDMS.
But if you have weighty arguments why you do so - it is you deal.
In this I'd suggest wrapping categories in additional |-symbol to get |1|2| or |1|3|23| and using LIKE "%|2|%" statement.
I hope this helps you.
SELECT * FROM cat_baza WHERE subsection = ".$row['id']." or subsection LIKE('%|".$row['id']."|%') or subsection LIKE('".$row['id']."|%') or subsection LIKE('%|".$row['id']."');
Try
SELECT * FROM table
WHERE category LIKE %2% AND NOT LIKE '%|%'
Try this
SELECT * FROM table
WHERE category='2' OR category LIKE '%|2' OR category LIKE '2|%'
SELECT * FROM table
WHERE category REGEXP '.*2.*'
Regex should work
So I am picking up a project that was quit halfway through by the last guy so that I could get some more practice with PHP and databases. I have run into a problem, and I am sure it is common enough that there is a standard solution, but I am unable to find one.
The db I am working with has 4,600, so reorganizing is out of the question. It is a db of liquers for a wholesaler. Here is what the results page looks like currently:
What I am trying to set it up so the results are returned in list form, with only one title and dropdown menus for the different sizes/prices of products that looks like this:
The problem is that there are multiple entries in the db for each product. In this example there are 3, while some have 1, and some have 2.
I am really not sure how to go about this, and any help would be greatly appreciated. Thank you.
I'm not sure about the PHP syntax, but pseudocode here's what you could do:
allProductsReturnedFromMySQL = QueryYourDatabaseForAllProducts()
Hashtable[productId, List[productSizes]] dropDownsByProduct;
Hashtable[productId, commonProductInformation] uniqueProducts;
foreach (product in allProductsReturnedFromMySQL) {
if product.productId not in uniqueProducts
then add it with the product information that does not vary
if product.productId not in dropDownsByProduct
then add it with an empty list
append the size of this product to the corresponding list in dropDownsByProduct
}
After that little bit of logic you'll have all your unique products with the common properties for each one, and a way to fetch the corresponding sizes drop down. If you wanted to do this purely in SQL to minimize the data that's transferred, you could do something like this:
-- this would get you your products
select distinct id, property1, property2 from product
-- this would get you your drop downs by product
select id, size from product order by id
You can then build the same drop down hashtable by iterating through the second result set.
I'm not sure if this is the best way, but I've always approached this by altering the query so that it is sorted by product name. Then as you iterate through the rows, check to see if the product name matches the one you just processed. If it's the same, then this row is a different size of the same project.