View page based on a record - php

I'm new to PHP and pardon me for asking this very basic question. What I want to do is to display or view a page based on a specific record. For example, I have a home.php page which lists records of lessons. And when I click on a specific record, it will go a page named lesson.php . I have to view the relevant information/data from my dB of that specific lesson. I tried to use GET but I think it's not going to meet the requirement of my system.
This is what I've tried so far:
$qry1stQuarter = $conn->prepare("SELECT l.lesson_title FROM tbllessons as l
JOIN tblstudents as s
ON l.grade_level = s.grade_level
WHERE quarter_code = '1st'
AND s.grade_level=:grade_level");
$qry1stQuarter->execute(array(':grade_level' => $grade_level));
<div id="tabs-2">
<div id="accordion">
<h3><strong>Yunit 1</strong></h3>
<div>
<?php
for($i=0; $row = $qry1stQuarter->fetch(); $i++){
$lesson_title = $row['lesson_title'];
?>
<div id = "lessons">
<?php
echo "<a href = 'lesson_view.php'>$lesson_title </a>";?>
</div>
<?php
} // end of for loop
?>
</div> <!-- end of Yunit 1 -->
What is the best way to do this? Your help is pretty much appreciated. Thanks.

In your database, I assume you have an ID column. A typical way to do what you are asking is to use that ID as a GET parameter on a link, and then include that in your WHERE clause in your SQL statement.
Eg:
echo "<a href='lesson_view.php?id=$lesson_id'>$lesson_title</a>";?>
And then on your lesson_view.php page, your SQL has something like this:
SELECT * FROM tbllessons WHERE id = mysql_real_escape_string($_GET['id'])

Related

MySQL only returning one value

Been trying to figure out what's wrong for nearly two hours now.
I have made a wall post feature for my website, posts should be displayed on the profile wall, however instead of all of the posts being displayed, only 1 is. I have no idea what is wrong with my code, I can't find any issues.
The $profile_username variable has been defined in previous code and works. Even if I just type the name of the profile in it still only returns one post.
//----------submit wall post----------//
$getwallposts = mysql_query("SELECT * FROM `wallposts` WHERE `postedto`='$profile_username' ORDER BY `postid`");
//check if any rows are returned
while($wallposts = mysql_fetch_assoc($getwallposts)) {
$postid = $wallposts['postid'];
$postedby_username = $wallposts['postedby'];
$wallpostdate = $wallposts['dateposted'];
$wallpost = $wallposts['post'];
$querypostedby_info = mysql_query("SELECT * FROM `users` WHERE `username`='$postedby_username'");
//get the info above
if (mysql_num_rows($querypostedby_info) > 0) {
$getpostedby_info = mysql_fetch_assoc($querypostedby_info);
$postedby_id = $getpostedby_info['id'];
$postedby_profilepicture = $getpostedby_info['profilepicture'];
}
//lets keep the line breaks
$wallpost=nl2br($wallpost);
//display the posts
$wallpoststicker =
"
<div id='wallpost-container'>
<div id='wallpost-header'>
<img src='$postedby_profilepicture'><div id='wallpost-header-by'><a href='/profile.php?id=$postedby_id'>$postedby_username</a> said:</div>
<div id='wallpost-date'>• $wallpostdate</div>
</div>
<div id='wallpost-content'>
$wallpost
</div>
</div>
";
}
Also, I know that mysql is deprecated; my version of PHP can handle mysql queries fine though.
Where to do you echo you're output?
If it is after the While you will only get the last result that is stored in the variable.
Output within the while loop.
I can see a couple of issues with that code. First, what it seems to be your problem:
$wallpoststicker =
"
<div id='wallpost-container'>
<div id='wallpost-header'>
<img src='$postedby_profilepicture'><div id='wallpost-header-by'><a href='/profile.php?id=$postedby_id'>$postedby_username</a> said:</div>
<div id='wallpost-date'>• $wallpostdate</div>
</div>
<div id='wallpost-content'>
$wallpost
</div>
</div>
";
This code overrides the $wallpoststicker variable on every loop. That's why you only print one result at the very end.
But secondly, you're doing a query within a loop, which is potentially very inefficient. Have you thought on doing a LEFT JOIN between "wallposts" and "users" so you have all the data you need before you start your loop?

MYSQL retrieve data from two tables

I am trying to make a small discussion system where people can login and post a discussion. On the homepage I want to show the discussions.
First I retrieve the data for the discussions (topic, category, username, etc) from the table 'discussions'and order them by 'date_time'.
I put these values in div's that are working just how I want it. The problem I am having now is to show the avatar of the user. The avatars are stored in a table 'users' under the column 'avatar'.
So I need to retrieve the value from the column 'avatar' in the table 'users' where 'username' matches the username of the discussion.
This is the code that I have now but it's not working. I have tried different things but I am not very familiar yet with PHP so I don't really know how to go from here.
Thanks in advance!
$result = mysql_query("SELECT
topic,
category,
date_time,
username,
SUBSTRING(discussion, 1, 80) AS discussion
FROM discussions
ORDER BY date_time DESC");
while($record = mysql_fetch_array($result))
{
?>
<div class="discusscolumn">
<div>
<p><? echo $record['category'] . ": <b>" . $record['topic'] . "</b>"?></p>
</div>
<div>
<?php
$discussion_username=$record['username'];
$getavatar = mysql_query("SELECT avatar, username FROM users WHERE username='$discussion_username' ");
$avatarrecord = mysql_fetch_array($getavatar);
echo'<span class="smallpic"><img src="user/'.$record['username'].'/'.$getavatar['avatar'].'"></span>';
?>
</div>
<div>
<p>Posted by <? echo "<a href='user.php?u=".$record['username']."'>".$record['username'] ?> </a></p>
</div>
<div>
<p><br><? echo $record['discussion'] ?>&nbsp...</p>
</div>
<div>
<p><? echo $record['date_time'] ?></p>
</div>
<div>Discuss</div>
</div>
<?php } ?>
PS: I know I am working with mysql instead of mysqli and that I'm mixing HTML and PHP code but I just want the basics to work now.
Please check your img source(src), that you have passed as user/username/avatar instead of passing like this please put url like http://www.w3schools.com/images/w3schools_green.jpg so that you will be getting out. But in your case you need to have all your user image in some other global storage area for eg.Amazon s3 bucket, and you need to get string from database construct like above url and append that in img src inside input tag

How to Link PHP Sub Categories(Pages) Dynamically

I have There PHP File getting Data From MySQL Database called:
clubs.php
club.php
player.php
the clubs.php list all clubs from tbleclubs table and it looks like:
clubs.php
$database = new Database();
$res = $Db->query("SELECT * FROM tblclubs");
foreach ($res as $dataRow): ?>
<span><?php echo $dataRow['id']; ?></span>
<span><a hrer=""><?php echo $dataRow['name']; ?> </a></span>
<?php endforeach; ?>
and club.php listing all players in a club from tblclub table
club.php
$database = new Database();
$res = $Db->query("SELECT * FROM tblpclub");
foreach ($res as $dataRow): ?>
<span><?php echo $dataRow['id']; ?></span>
<span><a hrer=""><?php echo $dataRow['name']; ?> </a></span>
<?php endforeach; ?>
and finally the player.php is from tbleplayer:
player.php
$database = new Database();
$res = $Db->query("SELECT * FROM tblplayers");
foreach ($res as $dataRow): ?>
<span><?php echo $dataRow['id']; ?></span>
<span><a hrer=""><?php echo $dataRow['name']; ?> </a></span>
<?php endforeach; ?>
I have set up a Foreign Key(FK) for tblclub as clubs_id and for tblplayers as club_id.
Now, my question is, how can I dynamically navigate to each selected item in next page like:
clubs->club->player
Thanks
First of all you have some errors in your HTML (it should href and not hrer for links)
Secondly, using a select * type of query is bad form; you should generally be choosing specific keys from your table, and not just all of them. You will also need to be link your tables if you want this to work properly; it's difficult to tell what specific rows you have in your tables; some structure would be helpful.
That said you would need to structure your queries something like this. For example to get a list of players a specific club:
SELECT p.playerid, p.name,
FROM tblplayers p, tblclub c
WHERE p.club_id = c.club_id
this query will get a list of all players on a specific club.
As for linking you would could modify your links to be something like this. To link to a specific player in a specific club, this would be the link on club.php to player.php:
<?php echo $dataRow['name']; ?>
Then to get the info you could just get the playerid from the URL by using a GET variable, like this: $playerid = $_GET['playerid']
and then get your information from the query, to do what you like. You can use the data in any way you like from there.
This is just a start, but you should be able to extrapolate from this for the rest of your questions. Hope this helps.
Ok, you are now rendering static lists.
To make the navigation dynamic you would basically need 3 things:
create links with ids
fetch this id from the URL
and query the db using the WHERE statement to select that specific id
You have already started with links: <a hrer="">, but it's href.
clubs.php - would render the overview of all clubs with links to each club
Place this in your foreach to construct the links by attaching the ids.
foreach ($res as $dataRow) {
$id = $dataRow['id'];
$name = $dataRow['name'];
$link = 'club.php?id=' . $id;
echo '<span>' . $id . '</span>';
echo '<span>' . $name. '</span>';
}
Now you can click for instance club.php?id=2.
But club.php would need to handle the incoming id, right?
club.php - renders the list of players with links to each player
You basically repeat the pattern from above, but with a different anchor base, this time it's player.php. You should get a list with player.php?id=x links.
How to handle the id in each of the scripts?
The id is incoming via $_GET.
You can use var_dump($_GET['id']) to see the value. Use a variable, like so $id = $_GET['id'].
(Later, when everything works: do not forget to secure and escape the incoming data properly.)
Then use $id in your database query:
SELECT * FROM tblplayers WHERE player_id = ' . $id;

Database not receiving correct data [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to fill 3 different tables in my database.
Sale table which has the following rows:
sale_id
fk_sale_user
fk_payment_id
sale_date
Print_for_sale which has:
print_for_sale_id
fk_sale_id
price_print_for_sale
Print_has_size_has_print_for_sale
print_has_size_has_print_for_sale_id
fk_print_has_size_id
fk_print_for_sale_id
Here is a screenshot of my database in mysql workbench so you can situate.
I'm trying to make the "buying" action.
This is my markup and php code:
printdetail.php
<?php
$id= $_GET['print_id'];
$printdetails = getprintdetailsById($con, $id);
$line = mysql_fetch_assoc($printdetails);
$selectsize =" select * from size";
$result=mysql_query($selectsize);
?>
<div>
<img width="800px;"src="<?php echo $line['print_img']?>"/>
</div>
<div>
<span> <?php echo $line['print_title']?> </span>
<form action="addprints.php" method="post">
<ul>
<?php while ($line = mysql_fetch_assoc($result)) { ?>
<li> <input type="checkbox" name="sizes[]" value="<?php echo $line['size_id']?>">
<?php echo $line['size_name']." Price: ".$line['size_price']."€ "?>
</li>
<?php } ?>
<input type="submit" value="Add to Cart" >
</ul>
<input type="hidden" name="print_id" value="<?php echo $id; ?>" />
</form>
</div>
addprints.php
<?php
session_start();
$user_id = $_SESSION['user_id'];
print_r($_POST);
$id_print= $_POST['print_id'];
include('database.php');
$bought_sizes=$_POST['sizes'];
$number_of_bought_sizes= count($bought_sizes);
//header('location:index.php?area=printstore');
$sqlinsertsale = "insert into sale
(fk_sale_user,
fk_payment_id)
values(".$user_id.", 2)";
mysql_query($sqlinsertsale);
for($i=0; $i< $number_of_bought_sizes; $i++){
$selectsize = "select *
from size";
$resultsize = mysql_query($selectsize);
while($linesize = mysql_fetch_assoc($resultsize))
{ $size_price = $linesize["size_price"]; }
$selectsale = "select *
from sale";
$resultsale = mysql_query($selectsale);
while($linesale = mysql_fetch_assoc($resultsale))
{ $sale_id = $linesale["sale_id"]; }
$sqlinsertprintforsale = "insert into print_for_sale
(fk_sale_id,
price_print_for_sale)
values(".$sale_id.", ".$size_price.")";
mysql_query($sqlinsertprintforsale);
$selectprinthassize = "select *
from print_has_size";
$resultprinthassize = mysql_query($selectprinthassize);
while($lineprinthassize = mysql_fetch_assoc($resultprinthassize))
{ $print_has_size_id = $lineprinthassize["print_has_size_id"]; }
$selectprintforsale = "select *
from print_for_sale";
$resultprintforsale = mysql_query($selectprintforsale);
while($lineprintforsale = mysql_fetch_assoc($resultprintforsale))
{ $print_for_sale_id = $lineprintforsale["print_for_sale_id"]; }
$sqlinserthashas = "insert into print_has_size_has_print_for_sale
(fk_print_has_size_id,
fk_print_for_sale_id)
values(".$print_has_size_id.", ".$print_for_sale_id.")";
mysql_query($sqlinserthashas);
}
?>
I am very new to php and mysql so I'm sorry if this is a dumb or bad question. I can't figure out what I'm doing wrong...
The table Sale is being updated correctly in phpmyadmin. Everything is working. User ID is OK and payment ID is OK too. (I haven't done the payments part yet so I just used a number to test.)
The table Print_for_sale is updating the correct sale ID (fk_sale_id), however the price_print_for_sale is always the same, no matter what print I choose. It's always 150 when sometimes it should be 65 ou 25.
(The print price is defined in the size table. So far I have 3 different sizes, so different prices.)
The table Print_has_size_has_print_for_sale is updating the correct print_for_sale ID, but the fk_print_has_size_id is always number 12 (which is the last from that list) and it has nothing to do with my choices on the form. I believe this is what is making the price come out wrong. If it's always the same combination of prints and size (print_has_size), then it's always going to have the same price... Why is this happening?
Can someone please help me?
Here are some screenshots of phpmyadmin:
Edit: This is the function I used:
<?php
function getprintdetailsById($con, $print_id){
$question = "select * from print where print_id=".$print_id;
$result = mysql_query($question, $con);
return $result;
}
?>
This is a lot of info.. I guess we can start debugging. Let's begin with your while loops. Inside your for loop, the first line select * from size, this should return an array, then you are iterating this array with your while loop, but you are assigning them to just one variable. This will overwrite the data result of the last iteration. Is this what you want?... to be continued.
You don't want that to be overwritten.. so what you need to do for that while loop is assign it to an array, like this:
while ($linesize = mysql_fetch_assoc($resultsize)) {
$size_price[] = $linesize["size_price"];
}
so, once you have the $size_price[] with all the desired sizes, we move on.. your code now runs select * from sale where you want all the sale_ids from. So just like above, assign it to an array, we'll say $sale_ids[]
Now you are trying to run a query that inserts data to the print_for_sale table, but the data comes from the two different arrays you created above.. this is will not work, and if so, you would need to come up with crazy loops and iteration like you already have tried.
To fix it, you first need to look at your tables, assign them unique ids, and link them through indexes, once you do that, you need to use the JOIN SQL command on your queries to get the matched data together.
I would look into separating your code as well. this will help you reuse it. You should look into an MVC framework. Ever heard of Codeigniter? its very easy to learn and powerful for applications.
Hope this helps.
Your code could use work, but I think that your problem is a misplaced bracket at the end. It should be:
while($lineprinthassize = mysql_fetch_assoc($resultprinthassize))
{
$print_has_size_id = $lineprinthassize["print_has_size_id"];
$selectprintforsale = "select *
from print_for_sale";
$resultprintforsale = mysql_query($selectprintforsale);
while($lineprintforsale = mysql_fetch_assoc($resultprintforsale))
{
$print_for_sale_id = $lineprintforsale["print_for_sale_id"];
$sqlinserthashas = "insert into print_has_size_has_print_for_sale
(fk_print_has_size_id,
fk_print_for_sale_id)
values(".$print_has_size_id.", ".$print_for_sale_id.")";
mysql_query($sqlinserthashas);
}
}
The replace code should be in the loop. In your original code, you looped through all the values, ending with the last one, and then used it.

PHP catalog, click on item image to display product details

I am trying to build a simple catalog displaying items from a mysql database.
So far I can get the items to display in a list format including the images stored as a path in the items table in a field called "path".
I would like the ability to be able to click on the item image and it takes you to a dedicated page showing you the details of that product. The link would correspond to which ever item you click on based on the data in the item table.
So far I have the following code;
<?php
session_start();
require "connect.php";
$date = date("d-M-Y");
$query = "select * from item order by date && time asc limit 0,3";
$query2 = "select * from users where userid = ".$_SESSION['userid'];
$result = #mysql_query($query, $connection)
or die ("Unable to perform query<br>$query");
?>
<?php
while($row= mysql_fetch_array($result))
{
?>
<?php echo $row['item'] ?>
<?php echo $row['description'] ?>
//Code for Image Link
<a href='<a href='<?php echo $row['path']?>'><img src="<?php echo $row['path']?>
<?php
}
?>
The above code allows you to click on the image and it takes me to http://127.0.0.1/steal/%3Ca%20href=
However I don't know what I would need to enter in order for it to take me to a page that shows the product?
Please Help
Many Thanks
I don't know your database schema, so I'm taking some liberties here about your columns for the product. But, try this:
<img src="<?php echo $row['path']?"/>
I also am not sure what your product page URL is either, so change product_page.php to whatever template you are using to display your products.
You need to create another page called for example showProductsOrder.php that accepts the orderID and then does output the content.
showProductsOrder.php?orderID=1
<?php
SELECT * FROM order WHERE orderID = $_GET['orderID']
while(fetch()) {
//> Show product here
}
?>
Also please don't use mysql_query. Use php.net/pdo
Addendum
Show all products
As yes123 said you would need to create another page, but i if you have a problem creating the link here is my suggested solution:
Replace your link with:
<?php echo ("<a href='".$row['pagePath']."'><img src='".$row['imagePath']."' /></a>";?>
$row['pagePath'] is the page that it will load when the image is clicked on, and
$row['imagePath'] is where the image is stored on your pc / server.

Categories