I have an mp3 downloading site and I want to create a search page, but I am in simple confusion. I have two tables, one that stores movie details like movie name and movie cast, and another one where all the songs of movies are stored. The structure of two tables is shown below:
Table 1: name categories
column :5
id,cat,cast,year,type
here id is primary key
cat is album/movie name
cast is all actores details of movie
year is releasing year and type is movie type
Table 2: files
column :4
id,cat,preview,file
Here my user can search with any keywords, and I can extract rows by sql query but here are two tables so I am confused what to do?
The user can input previews from table and can enter cat, type, cast, type and year from table 1.
Your table structure is not clear, But using join in query is not that complicated as you think, try and learn. Good luck
SELECT Category.cat, Category.cast, Category.year, Category.Type, File.preview, File.file
FROM category As Category
LEFT JOIN files As File On Category.cat = File.cat
WHERE Category.cat LIKE '%search%' OR Category.cast LIKE '%search%'
OR File.preview LIKE '%search%'
etc
Related
I am trying to SELECT id, description, title FROM table1, table2, table100
Say I get this working, is it better for me to just combine all my tables in phpmyadmin?
The problem is I have around 100 tables all of different categories of books so I want to keep them seperated in their individual tables.
I am trying to make a search engine that searches all the books in the entire database. All tables have the same column names.
So really all I really am trying to do is search the entire database's tables for an id, description, title. My search works, just I can only search 1 table and every solution online I have found only really works efficiantly with 2 or 3 tables.
Thanks in advance.
The best is to redesign your database, everything into a single table with an additional "category" column.
in the meantime, you can create a view which union the tables with an additional column for the category.
I recommend redesign the model and unifique this 100 tables to 1, and add a new column with category but integer value, not string value. In this way, you can index the category column with the other fields (id, description, title) for speed up the query.
This resolution is more easy for avoid pain later.
I recommend keeping one table A with id, description, title, category and create another table B with categories. Table A has to have a foreign key with table categories. Then create a query to retrieve the books with a specific category.
Example:
SELECT id, description, title, category FROM books WHERE category = "drama"
I think it speaks to the database design itself as mentioned by most here. You've a few options depending on how much time you have on your hands:
(Short Term / Quick Fix) Central table with all your current fields plus category as a flag to differentiate between the current tables you have. So your insert will be something like "INSERT INTO newtable (ID,AssetID,ServiceID,Category) SELECT id, description, title, 'Fiction' FROM table1 ;"
If you tables are incrementally named like table1, table2 upto table100, you could then maybe write a quick php script that will iterate through the insert loop while incrementing on table on each iteration until the last table.
In the long run, you could invest in a json field that will house all your other data excluding keys that pertaining to a single entry
I have two tables: movies and directors. The directors attribute in the movie entity is multi-valued, which is why I created the directors table with movieId as a foreign key that references the id column of the movies table.
Now, if I want to insert movies into my movies table, how do I add all the information for the movies into the movies table, as well as the name of the directors into the directors table at the same time, possibly using transactions? Also, how do I display the information from the movies table with their corresponding directors from the directors table in a HTML5 table using a while loop? I am using PHP with prepared statements.
This is what I have so far, but it's not complete:
mysqli_autocommit($connect, FALSE);
$stmtMov = $connect->prepare("SELECT id, title, plot, rating, releaseDate, language, duration, country, posterUrl, trailerUrl, imdbUrl FROM movies");
$stmtMov->execute();
$resultMov = $stmtMov->get_result();
$rowMov = $resultMov->fetch_assoc();
$movieId = $rowMov['id'];
$stmtDir = $connect->prepare("SELECT movieId, name FROM directors WHERE movieId = ?")
$stmtDir->bind_param("?", $movieId);
$stmtDir->execute();
$resultDir = $stmtDir->get_result();
$rowDir = $resultDir->fetch_assoc();
Any help would be very much appreciated.
Since you haven't added anything about insert, I'll consider only your select part.
The $rowMov will likely result in a rowset, which is nothing more than an array, which each row will have an ID value. What you should do is iterate with your rowset and generate, for every value, a query for directors entity and get the data you want. Something like:
foreach ($rowMov as $movie) {
$stmt = $connection->prepare("SELECT .... FROM directors WHERE id_movie = ?");
$stmt->bindParam("?", $movie["ID"]);
// $execution, binding results, etc.
}
With that done, you'll have an array with directors and an array with movies. If you want to simplify things on your view (considering you're using a MVC pattern), I would associate both arrays, looking for relations of directors["ID_MOVIE"] and movies["ID"], finally creating an array with both informations like and object.
You've asked two questions,
How do I insert into two tables at the same time, and
How do I display from two tables
But before I go into that, a bit of database review is in order. I would think that each movie would have one director, while each director might have many movies. I suppose the possibility for co-directors exists, too.
So for the first case, each movie must have a director:
movies
------
movie_id
director_id
title
plot, etc...
In this case, you could simply put the director's name in the movie database, but in order to list movies by director you would have to search by the actual name (and mis-spelling would make things complicated). And directors and movies are two different things, so it's better to have separate tables.
In the second case, you need a join table to have a many-to-many relationship.
movies director_movie directors
------- -------------- --------
movie_id movie_id director_id
title director_id name
So to answer your questions,
How do you insert into two tables at the same time?
You don't. First insert into whichever table stands on its own-- in the first case, directors. Then you get the last_insert_id from that table (or if the director already exists, search for the director_id). If last_insert_id is squirrely, you may have to search for what you just inserted to get the id.
Then, you take that id value and insert it into the dependent table movies along with the rest of that table's fields.
For the many-to-many case, you would do it in similar steps: 1) insert into movies 2) get the movie_id 3) insert into direcotors 4) get the director_id 5) insert ids into director_movie
How do I display the results
If there is only one director per movie, it's a simple sql query:
SELECT movies.*, directors.name FROM movies, directors where movies.director_id=directors.director_id AND movies.movie_id=?"
If you have multiple directors per movie, you'll have to loop through results:
SELECT * FROM movies WHERE movie_id=?
then make another query to list the directors
SELECT d.* from directors AS d,director_movie AS dm WHERE dm.director_id=d.director_id AND dm.movie_id=?
I am creating a search box in PHP and using MySQL as the database but when searching there are 3 tables, Colours, Products and Categories, these all have an ID number and can be linked. I have tried to use INNER JOIN, LEFT, RIGHT, everywhere but no luck, the query will sometimes work, spit out multiple items. So I am looking at creating a one-table-fits-all scenario where all the table field names will be in one and I can easily query that table. I have manually created the table but is there anyway of coping the data from the 3 tables into that main one? I do not mind doing it separately if it is a query that only handles one table but I would love not to have to manually type all the data as there is 600+ rows.
Here is the code I am currently trying to use:
SELECT
categories.Product_Type, items_colors.ColourImageurl,
items_list.description, items_list.Description2,
items_list.title, items_list.id, categories.title AS title2,
items_colors.itemID, Colour Name
FROM items_list
LEFT JOIN categories ON categories.Product_Type = items_list.CatID
LEFT JOIN items_colors ON items_list.id = items_colors.itemID
WHERE items_list.visible = 1 AND
Colour Name LIKE '%".$search."%'
Categories defines what type of product you are selecting, items_list has a list of all the sub category names and item_colors has a list of all the colour names that link to the items_list products. When I use this query it outputs 4 copies of one item and I'm not sure why.
If you are getting data from a query, you can use "create table as select" statement to create the new table, with data from old tables.
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,...)]
[table_options]
[partition_options]
select_statement
check here for more info : http://dev.mysql.com/doc/refman/5.1/en/create-table.html
I have a publications database and I need to fetch some information regarding the author. The author field is such that the authors have been lumped together in one field e.g if a book has two authors called Robert Ludlum and John Grisham, in the database it is saved as Ludlum, R.;Grisham,J.;
My application needs to spool information and retrieve data on books authored by a particular author if they click on their name. I am using this statement to retrieve the data
$select = "SELECT tblPublications.Title, tblPublications.Year FROM tblPublications WHERE tblPublications.Authors LIKE '%$sname%'";
$sname is a variable referring to the surname of the author. The problem arises if two authors share the same surname. however a workaround I am trying to implement is to get the applicationtake the surname, insert a comma, take the first name of a user and get the first letter then combine the result to a stringe and match them to each comma delimited value in the author field e.g if it is Grisham's books I am looking for I use *Grisham, J.* in my query.
Any Idea how to do this in PHP,MYSQL?
If it is possible to redesign the database, you should probably have an authors table and a book_authors table that relates books to authors, so that multiple authors can be associated with each book. Where is the Last Name coming from that the user clicks? Is it possible to have the link generated be LastName, First letter of first name? If so then you can probably change the link so it will include the first letter. But it is still possible to have two authors with the same last name and first letter of first name. So I think the best solution is to have an authors table and a Book_authors table and just store the author id as a hidden field and use that to retrieve the books by the selected author.
Your database design is incorrect, you have not normalized the data.
If you use like to search with leading wildcards, you will kill any chance of using an index.
Your only option to fix (if you want to keep the mistaken CSV data) is to convert the table to MyISAM format and put a FULLTEXT index on the authors field.
You can then search for an author using
SELECT fielda, b,c FROM table1 WHERE MATCH(authors) against ('$lastname')
See: http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
Of course a better option would be to normalize the database and create a separate table for authors with a link table.
TABLE books
------------
id primary key
other book data
TABLE authors
--------------
id primary key
lastname varchar (indexed)
other author data
TABLE author_book_link
----------------------
author_id
book_id
PRIMARY KEY ab (author_id, book_id)
Now you can query using very fast indexes using something like:
SELECT b.name, b.ISBN, a.name
FROM books b
INNER JOIN author_book_link ab ON (ab.book_id = b.id)
INNER JOIN author a ON (a.id = ab.author_id)
WHERE a.lastname = '$lastname'
It would entirely depend on what input you are getting from the user.
If the user just types a name, then there isn't much you can do (as there is no guarantee that they will enter it in a correct format for you to parse).
If you are getting them to type in a firstname and lastname however, something like this could be done:
<?php
$firstname = trim(mysql_real_escape_string($_GET['fname']));
$surname = trim(mysql_real_escape_string($_GET['sname']));
$firstletter = substr($_GET['fname'],0,1);
$sname = $surname.', '.$firstletter;
$select = "SELECT tblPublications.Title,
tblPublications.Year
FROM tblPublications
WHERE tblPublications.Authors LIKE '%$sname%'";
I work with PHP. I have a table named books. In table books I have the book_name with the name of the book, book_publisher with the publisher's ID and book_author with the author's ID. Besides the books table I have the books_author table with the authors names and IDs and books_publisher with the books publishers names and IDs.
I give my users 3 input fields that represents author name, book name and publisher name and a search button. They can input an author name, a book name and publisher name in the same search and I have to query my database and return the books names that have author name LIKE (%..%) inputted author name, book name LIKE the inputted book name and publisher name LIKE the inputted publisher name.
The problem is that I have stored only the author's id and publisher's id in my books table and I need to search by all three fields and exclude duplicates (books that were match by name and also by publisher).
Can anybody help me building this query ?
Just join the query:
SELECT *
FROM books b
JOIN book_authors ba ON b.author_id = ba.id
JOIN book_publishers bp ON b.publisher_id = bp.id
WHERE b.book_name LIKE '...'
AND ba.author_name LIKE '...'
AND bp.publisher_name LIKE '...'
Usually in these situations the search boxes are optional so you'll need to dynamically construct the query, meaning the WHERE clause to only filter on, say, publisher name if the user actually entered a publisher name.
Also, searching on LIKE '%blah%' is not scalable beyond thousands or possibly tens of thousands of records. No indexing can cater for that. You may want to look into using something like the MySQL full-text searching instead.
Lastly, make sure you sanitize your input, meaning pass all your input fields through mysql_real_escape_string().