I have an image that is displayed from a table and I want the user to be able to click the image which directs them to a page that returns the rest of the data for that row. Do I need a php loop for this? I can't quite figure it out.
This returns the Last Name, First Name, and an Image:
<?php
if (isset($_GET['LastName'])) {
$ln = $_GET['LastName'];
}
include 'connection.php';
$query = "SELECT * FROM residents WHERE LastName like '$ln%' ";
$result = mysql_query($query);
while($person = mysql_fetch_array($result)) { ?>
<div class="media col-sm-4">
<a class="pull-left" href="redirectionpage.php?<?php echo $person['ID'];?>.php">
<img class="media-object" src="upload/<?php echo $person['Picture'];?>" width="100" height="100"/>
</a>
<div class="media-body">
<h4 class="media-heading"><?php echo $person['LastName'] . ", " . $person['FirstName']; ?></h4>
</div>
</div>
<?php }>?
Is the best way to accomplish this by redirecting the user to a new page and using a mysql statement to display the new data?
This is the code for the other page:
<?php
//Gets data from the database
include ('header.php');
include ('footer.php');
include ('connection.php');
$query = "SELECT * FROM residents WHERE ID = LastName LIMIT 1";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
$outputpicture.='<div><p><img src="upload/' . $row['Picture'].'" width="450" height="550"/></p></div>';
$outputname.= $row['LastName'] . ", " . $row['FirstName']. '<br />';
$outputspouse.= $row['Spouse']. '<br />';
$outputrelatives.= $row['Relatives']. '<br />';
$outputaddress.= $row['Address']. '<br />';
$outputbirthday.= $row['Birthday']. '<br />';
$outputbegan.= $row['BeganResidence']. '<br />';
$outputended.= $row['EndedResidence']. '<br />';
$outputformer.= $row['FormerResidence']. '<br />';
$outputcareer.= $row['Career']. '<br />';
$outputeducation.= $row['Education']. '<br />';
$outputmaritalstatus.= $row['MaritalStatus']. '<br />';
$outputsiblings.= $row['Siblings']. '<br />';
$outputspecialinterests.= $row['SpecialInterests'].'<br />';
}
?>
The link needs to be changed to
<a class="pull-left" href="redirectionpage.php?id=<?php echo $person['ID'];?>">
Adding this id= will allow you to access the id parameter in redirectionpage.php via the $_GET superglobal.
$id = $_GET['id'];
You can use the $id variable to select the specified row from your database. You will see a lot of examples that do it like this:
$query = "SELECT * FROM residents WHERE ID = $id";
This works but you should not do it, because it creates an SQL injection vulnerability. Read about prepared statements and create your SQL so that you can pass the ID as a paramater.
$stmt = $pdo->prepare("SELECT * FROM residents WHERE ID = :id");
$stmt->bindValue(':id', $id, PDO::PARAM_INT);
$stmt->execute();
This should also be applied to the code you use to select the list of images.
Assuming ID is the key for your residents table, this should select only one record, so you will not need the while loop. You can just use one fetch.
Related
everyone. I'm having a bit of a PHP conundrum here and I couldn't find a good answer that already existed. You see, I'm working on a project where I have to take a classmate's discography website and revamp it with PHP, to where, instead of having the album covers and tracklists hard-coded in, it would query the database for them. My problem is that I have to keep the general style of his site intact, and I'm having trouble doing that. Basically his styles depend on having the album cover, name, and tracklists in div tags, and the style he's got in place is achieved through both Bootstrap and his own, custom CSS stylesheet.
Before I start to ramble, my question is: is there any way to wrap looping output in HTML tags? I need to get the album cover, album name, and tracklists in a div tag, but only the tracklists loop. Here is the code I have in place to query the database:
<?php
require ('mysqli_connect.php');
// Connect to database server
mysql_connect("localhost", "admin", "instructor") or die(mysql_error());
// Select database
mysql_select_db("phprediscography") or die(mysql_error());
// SQL query
$q = "SELECT DISTINCT albums.albumname, albums.albumID, albums.coverart
FROM albums
JOIN tracks
ON albums.albumID=tracks.albumID"; //select UNIQUE results from database
$t = "SELECT trackname FROM tracks WHERE albumID = 1";
$b = "SELECT trackname FROM tracks WHERE albumID = 2";
$n = "SELECT trackname FROM tracks WHERE albumID = 3";
$r = "SELECT trackname FROM tracks WHERE albumID = 4";
$result = mysqli_query($dbcon, $q);
$result1 = mysqli_query($dbcon, $t);
$result2 = mysqli_query($dbcon, $b);
$result3 = mysqli_query($dbcon, $n);
$result4 = mysqli_query($dbcon, $r);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) { //loop through database to get each album
echo '<img class="img-responsive" src=' . $row['coverart'] . '>' . '<br />';
echo '<h2>' . $row['albumname'] . "</h2><br />";
if ($row['albumID'] == 1) {
foreach($result1 as $row1) { //loop through tracks and output to page
echo '<p>' . $row1['trackname'] . '</p>';
}
}
if ($row['albumID'] == 2) {
foreach($result2 as $row2) { //loop through tracks and output to page
echo '<p>' . $row2['trackname'] . '</p>';
}
}
if ($row['albumID'] == 3) {
foreach($result3 as $row3) { //loop through tracks and output to page
echo '<p>' . $row3['trackname'] . '</p>';
}
}
if ($row['albumID'] == 4) {
foreach($result4 as $row4) { //loop through tracks and output to page
echo '<p>' . $row4['trackname'] . '</p>';
}
}
}
// Close the database connection
mysql_close();
?>
If I need to post anything else, let me know, this is my first-ever question so I'm just kind of feeling it out.
By doing your $t = "SELECT trackname FROM tracks WHERE albumID = #"; and if($row['albumID']==#) you are essentially still hardcoding similar to your friend. Just do 1 query, where you join all the tracks. Then when looping, group by the albumname -
<?php
require('mysqli_connect.php');
// SQL query
$q = "SELECT albums.albumname, albums.albumID, albums.coverart, tracks.trackname
FROM albums
JOIN tracks
ON albums.albumID=tracks.albumID";
$result = mysqli_query($dbcon, $q);
$current_albumID = ""; //create current albumID var to be used below.
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){//loop through database to get each album
if($row['albumID'] != $current_albumID){
echo '<img class="img-responsive" src='.$row['coverart'] . '>' . '<br />';
echo '<h2>' . $row['albumname'] . "</h2><br />";
$current_albumID = $row['albumID']; // set current albumID to this albumID
}
echo '<p>' . $row['trackname'] . '</p>';
}
?>
Try something like this instead: Get all the data you're after in your first query, then use php to process that into your output:
$q = "SELECT albums.albumname, albums.albumID, albums.coverart, tracks.trackname
FROM albums
JOIN tracks ON albums.albumID=tracks.albumID";
$result = mysqli_query($dbcon, $q);
$lastAlbumId = null;
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
if ($lastAlbumId != $row['albumID']) {
echo '<img class="img-responsive" src="'.htmlentities($row['coverart']).'"><br />';
echo '<h2>'.htmlentities($row['albumname']).'</h2><br />';
}
echo '<p>'.htmlentities($trackname).'</p>';
$lastAlbumId = $row['albumID'];
}
A few things to note:
I added use of htmlentities to escape the user data so malicious people can't type in HTML somewhere and have it appear on your site. This is something you should do almost everywhere you're displaying data from a database in a html site, except for very rare cases where you know what you're doing.
You probably don't need those <br /> tags - <h2> is a block level element so it'll force itself onto it's own line anyway (unless there's some silly CSS rules somewhere).
Also note - the above code is untested - typed straight into browser. There may be some syntax errors - let me know if you see any problem and I'll happily edit the answer. (or you can suggest an edit).
I have constructed an SQL query to lay out some info on a web page. The query works well. The problem is with each iteration of while loop a CSS class needs to be auto-incremented by 1.
<div class="related-item item1">
'item1' should become 'item2' in the next iteration and so on. Can you give me something ideas how to do it?
<?php
//Construct the SQL query code
$rel = "SELECT entries.*, images.name
FROM entries, images
WHERE entries.id = blog_id
ORDER BY dateposted DESC
LIMIT 0, 3;";
//Send the query to the MySQL server
$result = mysql_query($rel);
//Pull the row as an associative array
while ($row = mysql_fetch_assoc($result)) {
echo '<div class="related-item item1">
<div class="thumbnail-wrapper">';
echo '<img src="./images/' . $row['name'] . '" alt="How SHAPE Reader Caitlin Flora Lost 182 Pounds"/></div>
<h4 class="related-article-title">
' . $row['subject'] . '
</h4>
</div>';
} //End of while loop
?>
Just keep a counter variable going
$cnt = 1;
while(fetch from db) {
echo "<a class='foo{$cnt}'>click me</a>";
$cnt++;
}
which produces
<a class='foo1'>click me</a>
<a class='foo2'>click me</a>
<a class='foo3'>click me</a>
etc...
but generally this sort of thing is NOT necessary for CSS. You'd have to create a css rule for EVERY one of those <a> elements being created, which gets incredibly ugly and repetitive. There is nth-child support in CSS, so you can write rules which "modify" themselves based on which child an element is (1st, 2nd, ... Nth).
Add an integer and increment it...
<?php
//Construct the SQL query code
$rel = "SELECT entries.*, images.name
FROM entries, images
WHERE entries.id = blog_id
ORDER BY dateposted DESC
LIMIT 0, 3;";
//Send the query to the MySQL server
$result = mysql_query($rel);
$i = 1;
//Pull the row as an associative array
while ($row = mysql_fetch_assoc($result)) {
echo '<div class="related-item item{$i}">
<div class="thumbnail-wrapper">';
echo '<img src="./images/' . $row['name'] . '" alt="How SHAPE Reader Caitlin Flora Lost 182 Pounds"/></div>
<h4 class="related-article-title">
' . $row['subject'] . '
</h4>
</div>';
$i++;
} //End of while loop
?>
I have to output a series of random images previously saved inside a DB.
At the moment of the output, instead print a picture, the code print a strange string (meaby dumpfile?):
(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢Š(¢¢’ú~ü±®æIüa¤Äû[SÓÕºàܦ'$·›ØÒ¢°o>)xvÀŸ7ZÓדþULünð®ì.±„ðFíŸÉj=¬íìæöLꨮ6ã㦇êW8b³|Ä⪟ÚL-…Óu¦ÇRmÕ#ÿǪ^"’ûH¯cQô;Ê+ÏeøýC£Ý:ó÷çHÏåTnh[¿»ÐãRz/Ïýò¦£ë”—_ÌW©Øõ +Écý µIæùltuà¯Údfúgg_´ÿh1ÿMÓ?O&à¹ü™ùÒXÊ/¯æSÂÔ]H¢¼õi £mœÝ[°ë¹Pãòlþ•¥iñïÂwmµudVÎèd~;qúÖ‘ÄR{IèT_e…‹iñ#Ã÷»|½kKfnŠnQXþæµî£»ŒFßµ¦´ÖëöÏôpND;W?ÝL…V9à'5ÏSK–GE<,çhŸNîWϺoÇu·\ëW–¹É˜Í ¯ÕÖRºgß½^“Äñ_D¬ºÕ×™ÈÿM‘”þ$°üy¬þ¹…}R]Ot¨n5;{?õ×Åþû…þuóî¦öîònû»,ñ³Ãþ†¨ËtÖŸô €ò“üÿLGþ5/ýÒヿSè¼s¢Û¶×Ö4µoF»ŒZ‚‰:°ùµK^ÿp—þUàªI(eä{z ³œÁyú`U9V5>c¤…T‚7ØÉz®EGץصƒ]Yï|n𼃪+Ù ‘赿41þ«í·î#WÿBÅxŒªmÿH½ó±)_ å³O·˜Jî±ÚÝ6:eb…‰õû£ô¨xéô±_S‡™ì§ãréÚ§# 7’3ÿ‘*´¿óˆ´é™²Ïqÿ"kËžÂiUzÛ«rƒóÀþ•Nh$óTIçÎPmn§Àú€ê?J—Œ¨RÂÀõi~:ÜÿË=Y¼oT5Vããn´Ì='O…›§uŸýšòñ£GqüVJü|Óϳ1Ç¥8h&7GjÁ;maíÇ9ÅfñU{”°Ô»_yè—µhŸC·œ€ÿÌ·ôª³üsÔ¤ÿW¨i¬Ýˆ+üëˆ&ÞÏ8¸’>p°R3þî)ñ[óñ%ño{–eÿЇYªú—õzk¡ÖIñ{W½UªH¥€ÿWj}ú*§7Å#îó5«ÍÃÑZ1ü¿•ssè6¨Û¦U™¾ñÖ }2ÇóÅ8-¸m¶²dÿN¨ÓŒÔ:•V5NšÙÒüGšBÊ××ó?ç´Ÿ úV|þ&þЙn$QÔõÇJlSB]•¡‡o\;·õëS‰]¢†=¸àˆœ¨={ŸåëÞ£ß{²’ŠÙ÷¬Ï»ì3Éè¼ûöÜjIDiá¤Ä«Û|hÌ?J-æ˜Ûå)çæ…rãüõ©Ròt’Bœÿ¬‰8úýj,Ê¿b8šêÕwCco©þ€h¼Ôµgý\kï'ò;³ú~U$º
My code:
<?php
include_once('conn.php');
$n="SELECT COUNT('id_product')
FROM 'products'";
$value=mysql_query($n);
do
{
$selectionASC='SELECT id_product
FROM products
ORDER BY id_product ASC
LIMIT 1';
$selectionDESC='SELECT id_product
FROM products
ORDER BY id_product DESC
LIMIT 1';
$ASC=mysql_query($selectionASC)
or die ('Impossible execute the query <br />').mysql_error();
$DESC=mysql_query($selectionDESC)
or die ('Impossible execute the query <br />').mysql_error();
//____________________________________________________________________
$ASC = mysql_num_rows($ASC);
$DESC = mysql_num_rows($DESC);
$rand_n=rand(($ASC-1),($DESC+1));
//____________________________________________________________________
$selected='SELECT id_product,name, price, img
FROM products
WHERE id_product='.$rand_n;
$selected = mysql_query($selected);
//____________________________________________________________________
while($row=mysql_fetch_row($selected))
{
echo "Product'id:  "; echo $row[0];
echo '<br />';
echo "Name:  "; echo $row[1];
echo '<br />';
echo "Price::  "; echo $row[2];
echo '<br />';
echo "Immage: <img src='images/".$row['3']."'alt='Image'>";
echo '<hr> <br />';
$value--;
}
}
while ($value==0)
?>
The rest of the output is coherent with the code. Anyone know why it happen? And how to fix it? Thanks!
You cannot output image like what you did , first of things
when you fetch image from db .
for example if my image filed stored in img field i will call it like this
$id=$_GET['id'];
$query = mysql_query("select * from img where img id=$id ");
$row = mysql_fetch_array($query);
$img = $row['img'];
header("Content-type: image/jpeg");
print $img;
so this page only for displaying the pictures and when you want to use it you can do
<img src="display_img.php?id=2" />
it's not possible to keep every things in one page but also you can divide your page like this
if($$_GET['action']=="display_img"){
// show img code
}
So on my blog page I am using substr to display only a bit of the articles. The idea is once someone clicks one of the headings they will be sent to a page displaying the full article.
When i click the link i get the right heading in the url for example i click the 4th blog entry i will be redirected to index.php?id=4.The problem is that on this page the content remains the same, nothing changes. How do I get it so when i click the article I will be directed to a page containing only that article in full and no others. Thanks in advance guys this has been wrecking my head all day.
<?php
$dbinfo = "SELECT blog_id, title, date, body FROM content ORDER BY blog_id DESC LIMIT 0, 3";
$result = mysql_query($dbinfo) or die(mysql_error());
$return = '<p> Go Back To Content Page</p>';
if(mysql_num_rows($result) !=0):
while($row = mysql_fetch_assoc($result)){
echo '<div id="roundedbox"><h2>' . $row['title'] . ' </h2>';
echo '<div id="date"><h5><p>' . $row['date'] . '</p></h5></div>';
echo substr('<p>' . $row['body'] . '</p>',0, 90)." .... "." read more</div>";
}
else:
echo '<p> UH OOH! THERE IS NO SUCH PAGE IT DOES\'T EXIST </p>';
echo $return;
endif;
?>
The query you have in your code will return all the records for the table, what you want is the query to return the record based on the id parameter from the $_GET['id']. It's a good idea to make sure you're only using integers to prevent sql injection.
From your code you need to have a separate query to fetch the appropriate record using the $_GET['id'] parameter as follows...
//the parameter is set and it is an integer
if(isset($_GET['id']) && is_int($_GET['id'])) {
$blogId = (int)$_GET['id'];
$query = "SELECT blog_id, title, date, body FROM content WHERE blog_id='$blogId'";
// run query and get record data and output it
} else {
//code to return all records as list
$dbinfo = "SELECT blog_id, title, date, body FROM content ORDER BY blog_id DESC LIMIT 0, 3";
$result = mysql_query($dbinfo) or die(mysql_error());
$return = '<p> Go Back To Content Page</p>';
if(mysql_num_rows($result) !=0):
while($row = mysql_fetch_assoc($result)){
echo '<div id="roundedbox"><h2><a href="index.php?id=' . $row['blog_id'].$row['title'] . ' </a></h2>';
echo '<div id="date"><h5><p>' . $row['date'] . '</p></h5></div>';
echo substr('<p>' . $row['body'] . '</p>',0, 90)." .... "." read more</div>";
}
else:
echo '<p> UH OOH! THERE IS NO SUCH PAGE IT DOES\'T EXIST </p>';
echo $return;
endif;
}
Didn't know how to word the title sorry. Basically I have a comments system, it works really simply, selects the uid of the post from a DB, then just outputs the comments tied to that UID from another DB.
The nature of the comments system is that every poster is anonymous, because of that, it's hard to track whether you're communicating with the same person or not, for that reason, I want to make the div wrapped around the comment be a specific colour, and for each comment by that person on that post to be that colour. The only thing that ties a users comments together is the IP address.
My code thus far:
$sql = "SELECT * FROM anonpost_com WHERE uid = '$uid' ORDER BY date DESC";
$result = mysql_query($sql) or print ("Can't select entry from table anonpost.<br />" . $sql . "<br />" . mysql_error());
while($row = mysql_fetch_array($result)) {
$date = date("l F d Y", strtotime($row['date']));
$comment = stripslashes($row['comment']);
$uid = ($row['uid']);
$cid = ($row['cid']);
$ip = ($row['ip']);
?>
<div id="comments" style="border:1px solid <?php echo $colour; ?>;">
<p><?php echo $comment; ?></p>
<h4>by <i>Anonymous</i> on <?php echo $date; ?></h4>
</div>
<?php
}
?>
$colour comes from:
$colour = dechex(rand(0,10000000);
But I'm unsure how to make $colour the same for every instance of the same IP on a comment...
Any help would be appreciated!
I would agree that IP address might not be the best solution, but to do that:
$sql = "SELECT * FROM anonpost_com WHERE uid = '$uid' ORDER BY date DESC";
$colours = array();
$result = mysql_query($sql) or print ("Can't select entry from table anonpost.<br />" . $sql . "<br />" . mysql_error());
while($row = mysql_fetch_array($result)) {
$date = date("l F d Y", strtotime($row['date']));
$comment = stripslashes($row['comment']);
$uid = ($row['uid']);
$cid = ($row['cid']);
$ip = ($row['ip']);
if (!isset($colours[$ip])) {
$colours[$ip] = dechex(rand(0,10000000);
}
$colour = $colours[$ip];
?>
<div id="comments" style="border:1px solid <?php echo $colour; ?>;">
<p><?php echo $comment; ?></p>
<h4>by <i>Anonymous</i> on <?php echo $date; ?></h4>
</div>
<?php
}
?>
Note that the colour will change each time the page loads.