Multiple categories selection system for Article
Earlier M using two tables
articles & categories and save category ID in articles table
But in this system I can save only one category ID per article
I want to save Article in Multiple categories
While searching I found same question on StackOverflow
I understand the whole concept of adding one more table of relationship & saving Article ID & Category ID in this table.
But not aware how to implement multiple selection system using arrays in New Article Form & Edit Article Form.
earlier I am showing Select in my form to display categories list in Add Article & Edit Article Page.
pls someone explain me How to show categories list in multiple checkbox style in my form so user can select multiple categories and then after POST how to get checkbox data and run query to insert data in both Article Table & New Relationship table with selected categories ID
want to display category List like this screenshot
Many Many Thanks...
EDIT:
I use echo '<input type="checkbox" name="selcats[]" value="$catid"> ' .$catname;
to display Categories check box
Its showing in a row side by side.
how to change display like screenshot i.e. list with scrollbar
& need to process this array and insert in new table while inserting article in databse.
EDIT 2
got the checkbox display correct in a scroll list by using a div :D
<div style="height: 150px; width: 200px; overflow: auto;">
In my case, I use a "tag system", for instance: You have an article with one category, nothing will change that... In adition, you can create another field in the article table with the relevant words (or whatever you want) and separete them with spaces or commas.
// Get the data from your database
$tags = 'world, travel, turism, cities';
// Separate the values
$tags = explode(", ", $tags);
// Create a link for each one
foreach($tags as $t)
{
echo ' ' . ucfirst($t) . ' ' . "\r\n";
}
It should output:
World
Travel
Turism
Cities
And it means that you can SELECT articles that have the title LIKE the tag, or whatever you want to search.
Is that what you was looking for?
You basically require two tables, with this structure
table_categories
_____________________________
| id | title |
-----------+---------------+
table_category_detail
______________________________________________
| id | categoryId | articleId |
-----------+---------------+------------------
To extract all categories, select all from the table_categories and put up into the select menu with mutiple selection enabled.
Next, when posted get the selected box values and insert into table_category_detail one by one
This is how you create a select box
$query = "SELECT * FROM table_categories";
$result = mysql_query($query);
echo '<select multiple="multiple">';
while($row = mysql_fetch_assoc($result)) {
echo '<option value="'.$row['id'].'">'.$row['title'].'</option>';
}
echo "</select>";
Or a Multiple Check Box
while($row = mysql_fetch_assoc($result)) {
echo '<input type="checkbox" name="selcats[]" value="'.$row['id'].'"> ' .$row['title'];
}
After the post:
// Here write codes to insert the article first
$articleId = mysql_insert_id(); //get the id
$values = $_POST['selcats'];
foreach($values as $value) {
$query = "INSERT into `table_category_detail` VALUES(NULL, $value, $articleId)";
$result = mysql_query($result);
}
Related
I have a query which returns posts from a database, the query groups the posts by category and the titles are links to the original post. The returned posts are displayed on a categories page.
The trouble is that whilst the post titles are displayed and grouped by category I find that only the first post_id for each post per category is found and only the first post or post with lowest ID in each category is returned by my link. The link brings you to the original post.
Original posts are displayed on a page called “entries.php”
Example:
Post1 id = 1
Post2 id = 2
Post3 id = 3
All the posts above are grouped by category but if I hover over them they all pickup Post1 id=1 for some reason. Is there something I can do to ensure that each id is found when I hover over them?
Thanks for your time!
Query:
$query = "SELECT category, GROUP_CONCAT(DISTINCT title SEPARATOR '<br />') titles, post_id
FROM categories, posts
WHERE categories.category_id = posts.category_id
GROUP BY category";
$result = mysqli_query($dbc, $query)
or die('Error querying database.');
while ($row = mysqli_fetch_array($result)){
echo "<h2>".$row['category']."</h2>";
echo ''.$row['titles'].'';
echo "<hr />";
}
You should GROUP BY post_id, also use ORDER BY yo sort as you whish.
You're missunderstanding SQL's concept of GROUPing. If you GROUP rows on category_id, what you actually are telling MySQL: I want exactly one row for each category_id, regardless of how many rows there exist. In standard SQL you are only allowed to "SELECT category_id" (and aggregate functions like COUNT, MAX, MIN and so on) when using "GROUP BY category_id". MySQL allows you a little more and arbitrarily selects one hit (the first it finds).
What you probably want is ORDER BY category_id, and then do the grouping in your php script like
$prev_cat_id = null;
while ($row = mysqli_fetch_array($result)) {
if ($prev_cat_id != $row['category_id']) {
do stuff for next category
} else {
do stuff for next post in same category
}
}
remember to do cleanup for last category
I need a little kickstart here.
We're just learning php in school and we have this project where we're making a website for movie browsing. So we wanna be able to select genre, and show all movies from that genre using a MySQL database. We're all clear on the SQL queries and such, my question is rather how I make the browser show movies depending on SQL query?
Let me explain. Say we're movies.com
So on movies.com/genre is where you select the genre right, and on movies.com/display is where you're supposed to see the movies from the genre selected. So, clicking on "Comedy" should take you to movies.com/display and show you only the comedy movies. Selecting "Drama" should take you to the same site (movies.com/display) and show you only the drama movies.
Problem here is that we just don't know where to begin, it became a problem when switching page to show certain sql queries depending on what you selected in a previous page. I am not sure how to Google it, but just a link or a suggestion will help. I'm sure it can't really be too hard.
Thanks in advance.
Start with the html to choose a genre:
<form action="display.php" method="POST">
<select name="genre">
<option value="drama">Drama</option>
<option value="comedy">Comedy</option>
<option value="thriller">Thriller</option>
<option value="horror">Horror</option>
</select>
<input type="submit" value="Submit"/>
</form>
Here we have a form with a dropdown menu to select the genre. The forms action goes to display.php
Create display.php where we can get the submitted value and put that into our query:
// get the submitted value
$genre = $_POST['genre'];
// set a default genre if the POST genre is empty
if(empty($genre)) {
$genre = 'comedy';
}
// connect to database
$link = mysqli_connect("localhost", "my_user", "my_password", "db_name");
// check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: (" . mysqli_connect_errno() . ") ";
}
// build the query
$query = "SELECT * FROM movie WHERE genre = '".$genre."'"; // unsafe !!
$query = "SELECT * FROM movie WHERE genre = '".mysqli_real_escape_string($link, $genre)."'"; // safer
// execute query
$result = mysqli_query($link, $query);
// check result
if (!$result) {
echo 'Query unsuccessfull!';
}
// show values
while($row = mysqli_fetch_assoc($result)) {
echo $row['title'];
echo $row['description'];
echo "<br/>";
}
// close connection
mysqli_close($link);
I would suggest having a table of genres. That way you can display the list of genres easily for a user to select from (ie, you could populate an HTML forms select list from that table). The list of genres would have a unique id (an integer) and a text description, so when the list of produced you display the description but have a value that is the id.
Then have a table of movies (I presume you already have this). Each movie would be identified by a unique integer id field/
Lastly a table of movies to genres. This would just link the id of the movie to the id of the genre(s) for the movie. This way you can have a movie linked to several genres if required.
Doing it this way also means that the values you return from the HTML forms can just be integers, which are easily made safe (just use the php intval() function).
In use you would provide a list of genres as a SELECT list. When the user selects an item and submits the form the id of the selected genre is returned to the script. The script can then do a query that joins the tables together, checking the genre is the selected genre that has been returned to the script.
For example.
tbl_genres
id
genre_name
tbl_movies
id
movie_name
tbl_genre_movie
genre_id
movie_id
Then to get the details for a returned genre id:-
$sql = "SELECT *
FROM tbl_genres
INNER JOIN tbl_genre_movie
ON tbl_genres.id = tbl_genre_movie.genre_id
INNER JOIN tbl_movies
ON tbl_genre_movie.movie_id = tbl_movies.id
WHERE tbl_genres.id = ".intval($_POST['genre_id']);
I am trying to create an accordion menu where each accordion menu pulls the rutines of workouts where it differs by the category column in the db example below;
I got my PDO::db design like this;
id
title
describtion
category
hashtags
video
seen
date_published
how can i pull the info from the database by the category to use it in foreach in my view file. I hope i could make my problem clear enough.
thanks in advance.
You could order by category and then name (make sure you have an index on category, name)
Your Query would be:
SELECT * FROM `workouts` ORDER BY category, name
Then when you iterate you check if the category changed and if, close the sublist and open a new one showing the category first.
Another, slightly cleaner Solution would be to iterate twice, using the first loop to sort in an associative array by category:
$sth = $dbh->prepare("SELECT * FROM workouts");
$sth->execute();
$workouts = array();
/* First Loop */
while(($result = $sth->fetch(PDO::FETCH_ASSOC)) !== FALSE) {
$workouts[$result['category']][] = $result;
}
Now you can loop over $workouts, using the key as the Category.
foreach($workouts as $category => $workoutsByCategory) {
//display category and start subset
foreach($workoutsByCategory as $workout) {
//display workout
}
}
It would be a lot cleaner thou to use a second table which holds the category names and use the id of that table in your workouts table to connect. You can then get the results using join. You might want to look into Relational Database Design and Normalization
Example (not tested) Table Layouts:
table "workouts"
id | category_id | title | description | hashtags | video | seen | date_published
table "categories"
id | title
Then you can get the results using:
SELECT workouts.*, categories.title as category_title FROM workouts LEFT JOIN categories ON (category.id = workouts.category_id)
This will make it easier to change the name of a category amongst other advances ... but you'll read up on that i guess.
There are several other posts like this but none which match my specific parameters/needs.
How do i find the parent_id associated with one of 50 different outputted query results a user could click on?
Like, if the user clicks on "Transportation" I need code that can find the parent_id corresponding to the transportation node.
Problem is, my data is structure over multiple tables, so if they click on a link I don't necessarily know which table to search.
Essentially what I want is SELECT parent_id FROM * WHERE * = communication
But I can't * for parameters such as table name.
So how do I create code to automatically find the parent_id of a specific query once the user selects it?
There must be a better option than listing all my 20 tables in the query parameters?
Should I restructure my data into 1 table?
You have to search each table for the parent_id. If you want shorter codes, you can try this:
<?php
$tables = mysql_query('SHOW TABLES');
while($table = mysql_fetch_row($tables)){
$queries[] = 'SELECT parent_id FROM `' . $table[0] . '` WHERE method=\'Transportation\'';
}
$result = mysql_query(implode(' UNION ', $queries));
?>
I have a table named records with the columns: recordid, artist, album, description and coverimg. Some of the albums in the table have the same artist.
On my site I would like to display it like this:
-artist1
album1
album2
- artist2
album3
-artist3
album4
album5
If I use GROUP BY it just shows one row per artist. Is there any other way to group them without resorting to relational tables?
Because now I have a form to insert and update the table through my site, and I have no idea how I would have to code the forms to make this work with relational tables.
try this
select artist,group_concat(album) from albums group by artist
gives you
artist1 | album1,album2,album3
artist2 | albumx,albumy
You can split the second column in PHP e.g. using explode(row[1])
That should help you a bit
You can do it without a group by:
<?php
$query = 'Select artist, album
FROM records
ORDER BY artist'
$result = mysql_query($query);
$artist = '';
while ($line = mysql_fetch_assoc($result)){
// only show artist when it's an other artist then the previous one
if ($line['artist'] != $artist){
echo $line['artist'].'<br/>';
$artist = $line['artist'];
}
echo $line['album'].'<br/>';
}
?>
I know I should not be using mysql_* functions anymore, please choose mysqli_* or PDO....