how to get specific records - php

i'm making a simple site for movies and i wanna display related movies in the page..
the problem that my database contains American and Indian movies in movies table
i'm trying to find a way that when the visitor click on any american movie the related movies would appear only the american movies (there is a column called "movie_lang" in my table that labels the american movies as number 1 and the indian as number 2)
this's as far as i can get
$query=mysql_query("select * from movies order by id desc limit 4");
while($m=mysql_fetch_assoc($query)){
if($m['movie_lang']== '1'){
echo '<img src="uploads/poster/'.$m['thumbnail'].'" title="'.$m['name'].'">' ;}
else{
echo '<div class="hidden"></div>"';
}
}
not sure of my code. sorry...new to this...

If you wanna display only the american movies because the visitor click on it, you can show all the american movies using your query database.
$query = mysql_query("select * from movies where movie_lang = 1 order by id desc limit 4");
If you want the indian movies, just change the parameter in movie_lang to 2. This parameter can be for you a GET request.

Alright, I think I understand the issue, let me know if I missed it though: You want to list all types of movies, but if a user clicks a link for an american movie, you want to show him only american language movies on later pages. Here's my idea:
// When a page loads, it checks if the 'selected_lang' variable is set. If so, it creates a language filter
$previous_lang = isset($_GET['selected_lang'] && is_numeric($_GET['selected_lang'])) ? " where movie_lang = " . $_GET['selected_lang'] . " " : "";
// We assemble queries which will use a language filter if we have one, or all languages if not
$query=mysql_query("select * from movies $previous_lang order by id desc limit 4");
while($m=mysql_fetch_assoc($query)){
if($m['movie_lang']== '1'){
// We include a 'selected_lang' variable in our link, so that page now nows the language of the movie the user picked
echo '<img src="uploads/poster/'.$m['thumbnail'].'" title="'.$m['name'].'">' ;
} else {
echo '<div class="hidden"></div>"';
}
}
This code looks to see if a 'selected_lang' was set, and if so, uses it for subsequent SQL queries. You may have to chop bits here and there for different pages, and possibly re-arrange it if you want to write your own (sensible) where clauses.
Let me know if you need more help with this.

Related

Generating information based on users choice in php

I have any information stored in a database which is picked up and displayed with radio buttons. I like to display information from the database based on what radio buttons the user has chosen. For example I have a list of activities a user may have done and based on what they have chosen I would like to display other activities they could do. I can get the system to display random information from the database using RAND(). Can't find any online tutorials for this.
Please give us more information or a concrete example of your problem, all i can tell you is that your SQL request in your second code snippet will probably not give the expected result :
SELECT * FROM activities ORDER BY RAND() LIMIT 1
You probably don't want to ORDER BY RAND() (may be impossible) nor LIMIT 1, you just want to pickup one random row from your mysql results, am i right ?
If i am right just get the full resultset (with no order by / no limit clause), generate a random with php (between 0 and resultset size) the pick the expected row from resultset.
Ok, so i don't know your database structure, but lets say you have a table for activities and table for the activities the user does. For the sake of this example we will call them activities and activities_by_user
The activities table will have columns
activity_id | activity
The activities_by_user will have columns
activity_id | user_id
So your display code will look something like this
$query = "SELECT activities.*, activities_by_user.activity_id AS has_activity FROM activities LEFT JOIN activities_by_user ON activities_by_user.activity_id = activities.activity_id AND user_id = 1 ORDER BY RAND()";
// The user_id in just for example. There should be the id of the logged user
$result = mysqli_query($con, $query) or die('Error');
while($row = mysqli_fetch_object($result)) {
// If the has_activity field is not null, then the user does that activity
$checked = (isset($row->has_activity) && $row->has_activity != null) ? 'checked' : '';
echo '<label><input type="checkbox" name="activities[]" value="' . $row->activity_id . '" ' . $checked . ' />' . $row->activity . '</label>';
}
This will generate checkboxes for all the activities and will check does who are done by the user.

PHP & SQL to get a certain row

Hello i am just starting out and not too bad with HTML but no hardly anything on PHP, I have created a basic PHP code to get data from my sql database but limit to the first 3 and echo them out.
However i would really like to be able to put these in fancy looking divs later on in a different order, so say row 1 in div 1 row 2 in div 2 etc.
I know how to select and echo line based on a unique id but i want to be able to say query by date order then limit to 3 and echo those in different divs on the website.
Ive looked everywhere so any help would be very good, here is my code:
$sql = mysql_query("SELECT * FROM dbc_posts ORDER BY ID ASC limit 3");
$unique_id = 'unique_id';
while ($rows = mysql_fetch_assoc($sql)){
echo $rows[type] . '<br/>';
}
?>

Arrays display order

So this script works like this. It takes the tags you have chosen as your interests and compares it with the other users tags. This script below gives me the output of how many tags me and the other person have common.
$get_userinfo = mysql_query("SELECT * FROM users") or die(mysql_error());
while($userinfo = mysql_fetch_array($get_userinfo)) {
$usertags = $userinfo['tags'];
$tagsdata = explode(" ", $usertags);
$interestsdata = explode(" ", $interests);
$result = array_intersect($interestsdata, $tagsdata);
echo "Count under this belongs to ".$userinfo['name']."";
echo count($result);
echo "<br />";
}
Now, I want first, this script also displays me in the list so I see how many tags I have common with myself and I want to remove myself. And second, how do I list it so the person with highest number (most tags common) get displayed at the top and descending.
Add a condition to exclude yourself from your own query:
SELECT * FROM users WHERE user_id != [your user id]
To order by the number of tags, you need to issue an aggregate function in your SQL statement to group results by the tag and user. Without seeing your table structure I can only offer a very generalized statement
SELECT username, tag, count(tag) FROM users JOIN tags ON x = y WHERE user_id != [your user id] GROUP BY user_id, tag_id ORDER BY count(tag) DESC
Another option is to collect your data, and sort through it with PHP after you already know how many tags each user has in common. See http://php.net/manual/en/function.sort.php for information on sorting arrays.
You should also start using PDO or mysqli as the mysql functions have been officially deprecated.
I also strongly advise you to not put multiple tags in one database field.

mysql results sort by array

I think I don't understand how 'sort' works, so please don't judge me. I really searched all day long.
I have a movies table with actors column. A column it's named "actors". The actors are links separated by space " ". The order of the links it's very important.
I explode the links into an array which looks like [0]-> link0, [1]->link1, ...
I have the actors table where every actor also has it's movies links. I don't want to make 20 different sql searches so I made a variable with all the links I want, like this ( WHERE actor_link = link1 OR actor_link = link2 OR .. )
The problem is this. The search will probably find first the link7, and so my sorting it's gone. What can I do to keep that order from the movies table. I want to display the actors by popularity in the movie, not the order of my database.
Can you give me another method to search the actors without making 'x' sql searches and still keeping the order?
$actors[] = explode(" ", $row['actors_link']);
$x=0;
$actors2 = '';
while ($actors[0][$x]) {
$actors2 = $actors2 . "`link_imdb_actor` = " . "'".$actors[0][$x]."' OR ";
$x++;
}
$actors2 = substr($actors2, 0, -3);
$sql = "SELECT * FROM `actors` WHERE $actors2";
$sql_result = mysql_query($sql) or die(" ");
while ($row3 = mysql_fetch_array($sql_result)) {
echo $row3['link_imdb_actor'];
}
So, the movie Hotel Transylvania has Adam Sandler, Andy Samberg and Selena Gomez. My search shows Selena Gomez, Andy Samberg, Adam Sandler because this is the order from my database. How can I sort the sql results by the order of the actors array? Thank you!
To expand on Arjan's comment, if you want to be able to actually use the actor data (e.g. search with it) I would recommend at least two more tables. One called actors with the fields actorID, firstName, and lastName. The other table would be castings with the fields castingID, actorID, movieID, and castingOrder.
Each castingID will then link an actor to a movie - this would make for easy searches of every movie a particular actor has been in or every actor in a particular movie.
The castingOrder field can be used to maintain the order you want.
I need your existing code to really get the gist of what's going on.
I will make one suggestion in your query. Instead of saying WHERE actor_link = a OR actor_link = b OR actor_link = c do this instead:
WHERE actor_link IN (link1, link2, link3)

Retrieve and display comments/queries from database

I'm developing in php/sql a web application where users will be able to post items that they'd like to sell ( kinda like ebay ). I want non-members to be able to comment on the items or ask queries about items.
My problem is I want to display each item as well as any comment/query made about that item, in a similar manner as the way Facebook wall works.
I want to "append comments"(if any) to each item. The comments table is linked to the items table via column item_id. And the items table is linked to users table via column user_id. I have left joined users table with items table to display item details, i tried to left join comments table as well so that there are 3 joined tables.
That fails because no comments are displayed and only one item is displayed, despite there being multiple entries in each table. Here is the code i,m using.
$database->query
('
SELECT sale.*, query.*, users.id AS userid, users.username as user
FROM sale
LEFT JOIN users ON sale.user_id = users.id
LEFT JOIN query on sale.id = query.item_id
where category = "$category" ORDER BY sale.id DESC
');
$show = " "; //variable to hold items and comments
if ($database->count() == 0) {
// Show this message if there are no items
$show .= "<li class='noitems'>There are currently no items to display.</li>" ;
} else {
$show .= "<li>";
while ( $items = $database->statement->fetch(PDO::FETCH_ASSOC) )
{
$show .= "
//show item details in html
";
while( $query = $database->statement->fetch(PDO::FETCH_ASSOC) )
{
$show .= "
//show queries below item details
";
}
$show .= "</li>" ;
}
Welcome to Stackoverflow!
I recommend you taking a look at pdo. If you are already using mysql_ functions, then I recommend you switch. More on that can be found here.
Now that your pointed to the direction of to what functions to use when connecting/running queries, you now should create your tables. I use phpmyadmin for managing my database, I find it very good, but it's up to you what you use. Once you've decided on the service you use to manage your database, you should then learn how to use it by doing some google searches.
Now you need to set up your table and structure it correctly. If you say you're having items, then you should make a table called items. Next create the columns to the properties of the items. Also I recommend reading about Database Normalization, which is a key aspect of setting up your SQL tables Etc.
Once you have everything set up, you've connected to your database successfully Etc. You now need to set up the "Dynamic Page". What I mean by this is, there's only one page, say called 'dynamic', then a variable is passed to the url. These are called GET HTTP requests. Here's an example of what one would look like: http://example.com/item?id=345.
If you've noticed, you'll see the ? then the id variable defined to 345. You can GRAB this variable from the url by accessing the built in PHP array called $_GET[]. You can then type in your variable name you want to fetch into the []'s. Here's an example.
<?php
$data = $_GET['varname']; // get varname from the url
if(isnumeric($data)){ // is it totally made out of numbers?
$query = "SELECT fieldname FROM table WHERE id=:paramname";
$statement = $pdo->prepare($query); // prepare's the query
$statement->execute(array(
'paramname'=>$data // binds the parameter 'paramname' to the $data variable.
));
$result = $statement->fetch(PDO::FETCH_ASSOC); // grabs the result of the query
$result = $result['fieldname'];
echo 'varname was found in the database with the id equal to:'.$data.', and the result being: '.$result;
}
?>
So now you can see how you can grab the variable from the url and dynamically change the content with-in the page from that!
Hope this helped :)

Categories