Display image on php mysql blog based on username of post - php

Thanks in advance!
I have a simple mysql and php blog that I built based on a tutorial I found online. What I would like to be able to do, but have no idea how to go about it, is this:
I would like a picture (avatar) to be displayed with each comment on each post. The picture that is chosen would be based off of the name in the Posted By: area of the comment. So for instance: Let's say me, the admin, leaves a comment on the thread. My name is automatically pulled in via a '$_SESSION' variable so I don't have to worry about entering that each time. When the comment is displayed on the blog thread page, it shows Commented on By: Admin. This name is stored in the db and pulled in with the a php echo statement.
So what I want this avatar code to be able to do is
1) look at the area where the Commented on By: text is
2) read the text
3) see that it says Admin and display the admin.png image next to it. If it sees anything other than Admin in the Commented on By: area, then it will display something like guest.png
Here is a snippet of code I found in my stackoverflow and google searches. It works but it pulls in the guest image 6 times, then the actual admin.png image, and then the guest image 3 more times. And it displays this way on EACH comment on EACH thread! And when I add a new thread and a new comment to that thread, it adds the guest image again at the end of the multiple images being displayed on each comment. Did I set it up wrong?
<?
$sql = "SELECT comment_user FROM comments";
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) != 0) {
$counter = $starting + 1;
$pathImg = "images/";
while ($row = mysql_fetch_array($result)) {
//calculate url image
$pathFile = $pathImg . $row['comment_user'] . ".png";
if (!file_exists($pathFile)) {
$pathFile = $pathImg . "guest.png";
}
?>
<img src="<?=$pathFile?>" alt="<?=$row['comment_user']?>">
</p>
<?
$counter++;
}
}
?>
This displays out as (Guest Image)(Guest Image)(Guest Image)(Guest Image)(Guest Image)(Guest Image)(Admin Image)(Guest Image)(Guest Image)(Guest Image).
Any help on throwing something together would be great! Trying to keep it simple to!
EDIT:
This is how the comments are displayed, along with the code from FlyingGuy's answer.
<?php
foreach ($post['comments'] as $comment){
$commentCount = 0 ;
$sql = "SELECT comment_user FROM comments";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
$commentCount++ ;
$pathImg = "images/";
$pathFile = $pathImg . $row['comment_user'] . ".png";
if (!file_exists($pathFile)) {
$pathFile = $pathImg . "guest.png";
}
echo "<img src=\"". $pathFile ."\" alt=\"". $row['comment_user'] ."\"\><br>";
}
?>
<h4>By <?php echo $comment['user']; ?> on <?php echo $comment['date']; ?></h4>
<p><?php echo $comment['body']; ?></p>
<hr />
<?php
}
?>
This is how the functions look for displaying and adding comments:
function get_comments($pid){
$pid = (int)$pid;
$sql = "SELECT `comment_body` AS `body`, `comment_user` AS `user`, DATE_FORMAT(`comment_date`, '%m/%d/%Y') AS`date` FROM `comments` WHERE `post_id` = {$pid}";
$comments = mysql_query($sql);
$return = array();
while (($row = mysql_fetch_assoc($comments)) !== false){
$return[] = $row;
}
return $return;
}
// adds a comment
function add_comment($pid, $user, $body){
if (valid_pid($pid) === false){
return false;
}
$pid = (int)$pid;
$user = mysql_real_escape_string(htmlentities($user));
$body = mysql_real_escape_string(nl2br(htmlentities($body)));
mysql_query("INSERT INTO `comments` (`post_id`, `comment_user`, `comment_body`, `comment_date`) VALUES ({$pid}, '{$user}', '{$body}', NOW())");
return true;
}
?>

Look what you are trying to do is select the image that matches the name of the user in the current row of your result set. So you will set your image file variable as appropriate for each row and you are sending that to the browser.
For starters and can see the probability of case issues here. Are all user names forced to lower case and all image names forced to lower case? If this is on a linux box that is a land mine on windows not so much, but this should be taken into account.
It will set an image name for each row of your queries result set so it will look like:
[image] [comments]
[image] [comments]
[image] [comments]
if you have three rows in your result set.'
Personally I avoid all of the turning php on and off all over the place. Concat a single string and then simply echo it out for each row. So I would code it like so:
<?
$commentCount = 0 ;
$sql = "SELECT comment_user FROM comments";
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$commentCount++ ;
$pathFile = $pathImg . $row['comment_user'] . ".png";
if (!file_exists($pathFile)) {
$pathFile = $pathImg . "guest.png";
}
echo "<img src=\"". $pathFile ."\" alt=\"". $row['comment_user'] ."\"\><br>";
}
So I have eliminated a lot of things from your code example like counters etc. You don't really need to check and see if there are rows since the while loop simply will not execute of there are no rows so you will simply have a question of comment with no subordinate comments and it will only send the image link if there are comments.
No if it were me doing this I would create an avatar file name is the user table and store the path to those as part of the system configuration which would be part of the global set of variables that are always present. Your query would then join in the users table and the image name or guest image would be in your result set. A bit more complex but much cleaner and it simplifies your code.
One of the reasons I don;t like dynamic typing. $row was being mutated to an array of ALL the rows..

Related

How do I display a table using an explode or is there something else to suggest?

First I want to explain my application:
I have created an application for my QA work. The application generates a document gets saved as a pdf and added to the server. I have a dynamic table in it that gets save to the database using the implode function separating it as with a comma in the same row as the test case on the database.
It all works fine, but when I want to view the test case I am having trouble to figuring out how to get it to display. I have read plenty of scenarios to use the explode but no luck...
<?php include 'app_database/database.php'; ?>
<?php
if(isset($_POST)){
$step = $_REQUEST['step'];
$url = $_REQUEST['url'];
$pass_fail = $_REQUEST['pass_fail'];
$comment = $_REQUEST['comment'];
$sql1 ="UPDATE qa_testing_application SET step='".implode(',',$step)."',url='" . implode(',',$url) . "',pass_fail='" . implode(',',$pass_fail) . "',comment='" . implode(',',$comment) . "' WHERE test_case_name='$test_case_name'";
$result= mysqli_query($database, $sql1) or die(mysqli_error($database));
}
?>
I am inserting it this way. And i would like to retrieve it from the DB.
I would love to display it as follows:
Please see the link http://i.stack.imgur.com/6aglk.jpg
At the moment i am trying to test and figure out how to display it:
Not sure how to implement a for or foreach function in here as well if thats needed.
$countsteps = 0;
$counturls = 0;
$countpass_fails = 0;
$countcomments = 0;
$test_case_number = '21';
$select_tbl=mysqli_query($database,"select * from qa_testing_application WHERE test_case_number='$test_case_number'");
$result = mysqli_query($database, $sql1) or die(mysqli_error($database));
while($fetch=mysqli_fetch_object($result))
{
$step=$fetch->step;
$url=$fetch->url;
$pass_fail=$fetch->pass_fail;
$comment=$fetch->comment;
$steps=explode(",",$step);
$urls=explode(",",$url);
$pass_fails=explode(",",$pass_fail);
$comments=explode(",",$comment);
echo '<td>'.$steps[$countsteps++].'</td>';
echo '<td>'.$urls[$counturls++]."</td>";
echo '<td>'.$pass_fails[$countpass_fails++]."</td>";
echo '<td>'.$comments[$countcomments++]."</td>";
}
So how would I get this to display in a table?
edit:
Oh and this is the error that I get:
Undefined Offset
This error simply says there is no such key exists into given array or you're trying to fetch a value from non-array variable.
To show data into tabular format, you don't need to explode data coming from db. They are already concatenated.
So to show data from db, modify your code as show below:
$test_case_number = '21';
$select_tbl=mysqli_query($database,"select * from qa_testing_application WHERE test_case_number='$test_case_number'");
$result = mysqli_query($database, $sql1) or die(mysqli_error($database));
echo '<table>';
echo '<th>Step</th><th>Url</th><th>Pass/Fail</th><th>Comment</th>';
while($fetch=mysqli_fetch_object($result))
{
echo '<tr>';
echo '<td>'.$fetch->step.'</td>';
echo '<td>'.$fetch->url.'</td>';
echo '<td>'.$fetch->pass_fail.'</td>';
echo '<td>'.$fetch->comment.'</td>';
echo '</tr>';
}
echo '</table>';

Calling from a MySQL/PHP array multiple times in a page

I'm probably asking a very simple question here - I know the basics of calling an array but I think I'm probably not doing it in the most efficient way... I'm calling some data into an array at the start of my page and then I want to be able to use this data-set multiple times throughout the page without wrapping everything in PHP if possible.
At present I'm doing it like this -
A variable ('video') is passed to my page through the URL which I get like so:
<?php
$video = $_GET['video'];
?>
My <title> tag is pulled from the selected database (also titled 'video')
<?php
$title = mysql_query("SELECT * FROM video WHERE ID = '{$video}'") or die(mysql_error());
mysql_real_escape_string($video);
while($head = mysql_fetch_array( $title )) {
echo "{$head['title']} - BY XXXXX</title>";
echo "<meta property=\"og:title\" content=\"{$head['title']} - BY XXXX\"/>";
}
?>
I then want to use the {$video} data later on the same page, but defining a slightly different variable like so:
<?php
$data = mysql_query("SELECT * FROM video WHERE ID = '{$video}' ORDER BY added DESC") or die(mysql_error());
mysql_real_escape_string($video);
while($info = mysql_fetch_array( $data )) if ($info['ytembed'] == 'yes') {
echo "{$info['embedcode']}";
echo "<div class=\"videobox1\">";
echo "<div class='video-title'>{$info['title']}</div>";
echo "<div class='video-subtitle'>{$info['subtitle']}</div>";
echo "<div class='video-credits'>{$info['cast']}</div>";
echo "<div class='back'>«back</div></div>";
} else {
echo "no embed code";
}
?>
So at the moment every time I want to pull from that data I'm calling the whole array again - it would be amazing if instead of doing this I could just print/echo selected items
Is there a way to make my code more efficient and do this?
I'm also looking to Validate the ID and if it doesn't exist within the video DB send the user to a 404 page - but perhaps that's a separate question.
Hello this is refined code
Replace first 1 with this.
$video = $_GET['video'];
$video = mysql_real_escape_string($video);
$videodata = mysql_query("SELECT * FROM video WHERE ID = '{$video}' LIMIT 1") or die(mysql_error());
// execute the query and check if video id exist or not
if(mysql_num_rows($videodata) == 0){
// 404 redirect code.
}
Replace Second with
$videodataArray = array(); // created array for storing video data
while ($head = mysql_fetch_array($videodata))
{
$videodataArray = $head ; // store the value in video data array for to use in fulll page
echo "{$videodataArray['title']} - BY XXXXX</title>";
echo "<meta property=\"og:title\" content=\"{$videodataArray['title']} - BY XXXX\"/>";
}
Replace last one with
echo "{$videodataArray['embedcode']}";
echo "<div class=\"videobox1\">";
echo "<div class='video-title'>{$videodataArray['title']}</div>";
echo "<div class='video-subtitle'>{$videodataArray['subtitle']}</div>";
echo "<div class='video-credits'>{$videodataArray['cast']}</div>";
echo "<div class='back'>«back</div></div>";

Only the last image displays from database

I asked this question before but no one could help me unfort. I have images and headings coming from database now the problem is that only one image is displaying(the last image) i need both to display.
here is my revised code
$query = "SELECT page_title, page_image FROM pages WHERE id='$page'";
$result = mysqli_query($connection, $query);
confirm_query($result);
while ($page_fetch = mysqli_fetch_assoc($result)) {
$page_title = $page_fetch['page_title'];
$images = $page_fetch['page_image'];
echo "<div class=\"content \">";
echo "<h3 class=\"words\"> $page_title </h3>";
echo "<img src='pics/" . $images . "' width=\"340\" height=\"252\" alt=\"\" />";
echo "</div>"; //end box
} // close while loop
here is my database for pages
page_id id page_image page_title
1 1 ocean.jpg have a look at the ocean
2 1 house.jpg The house
just some extra info the images must display dynamically , as they coming in from a form to db to this page
Your are returning your images from your query.
Check the view source page, You will find your error their.
Your returing image name will not match with the image which you got in the folder. (For the second one)

insert value from drop down box to the database

I am missing something from my code and I don't know how to make it work. I may have programed it wrong and that could be giving me my troubles. I am new at php and things have been going slowly. please understand that the code my not be organized as it should be. After creating about 12 pages of code I found out that I should be using mysqli or pod. Once I get everything working that will be the next project. Enough said here is my issue. I was able to populate my drop down box and there shows no errors on the page. Also all the data does get inserted into the database except for the section made on the drop down box. Here is my code. I will leave out all of the input fields except the drop down.
<?php
{$userid = $getuser[0]['username'];}
// this is processed when the form is submitted
// back on to this page (POST METHOD)
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
# escape data and set variables
$tank = addslashes($_POST["tank"]);
$date = addslashes($_POST["date"]);
$temperature = addslashes($_POST["temperature"]);
$ph = addslashes($_POST["ph"]);
$ammonia = addslashes($_POST["ammonia"]);
$nitrite = addslashes($_POST["nitrite"]);
$nitrate = addslashes($_POST["nitrate"]);
$phosphate = addslashes($_POST["phosphate"]);
$gh = addslashes($_POST["gh"]);
$kh = addslashes($_POST["kh"]);
$iron = addslashes($_POST["iron"]);
$potassium = addslashes($_POST["potassium"]);
$notes = addslashes($_POST["notes"]);
// build query
// # setup SQL statement
$sql = " INSERT INTO water_parameters ";
$sql .= " (id, userid, tank, date, temperature, ph, ammonia, nitrite, nitrate, phosphate, gh, kh, iron, potassium, notes) VALUES ";
$sql .= " ('', '$userid', '$tank', '$date', '$temperature', '$ph', '$ammonia', '$nitrite', '$nitrate', '$phosphate', '$gh', '$kh', '$iron', '$potassium', '$notes') ";
// #execute SQL statement
$result = mysql_query($sql);
// # check for error
if (mysql_error()) { print "Database ERROR: " . mysql_error(); }
print "<h3><font color=red>New Water Parameters Were Added</font></h3>";
}
?>'
Here is the drop down
<tr><td><div align="left"><b>Tank Name: </b> </div></td><td><div align="left">
<?php
echo "<select>";
$result = mysql_query("SELECT tank FROM tank WHERE userid = '$userid'");
while($row = mysql_fetch_array($result))
{
echo "". $row["tank"] . "";
}
echo "";
?>
</div></td></tr>
You missed some code in while loop.
while($row = mysql_fetch_array($result))
{
echo "<option>".$row['tank']."</option>";
}
echo "</select>";
are you able to build drop down menu or box. if not try this query
$sql="SELECT `tank` FROM `tank` WHERE user_name='$user'";
$result=mysqli_query($dbc,$sql)
//here $dbc is a variable which you use to connect with the database.
Otherwise leave that only read from here why you need to change your code. in the while loop
one one more thing you have to give your select attribute a name, because it will return the value through name so give a name to your select attributes as you are using tank while building your drop down menu so i will give a same name tank. Than you dont have to change anything.
and you have to give value to your option as well, thanks
echo "<select name='age'>";
while($row = mysql_fetch_array($result))
{
echo "<option value='" . $row['tank'] . "' >" . $row['tank'] . "</option>";
}
echo "</select>";

PHP output as link from database

I have the following code that works by outputting as a link ( the link comes from a field in my database) I wish to do the same for the code below, however i cannot get it work, here is the example of what I have that works, and the code that i wish to make output as a link:
Working Code what I want it to look like
if (!empty($_REQUEST['term'])) {
$term = mysql_real_escape_string($_REQUEST['term']);
$sql = "SELECT * FROM adrenaline WHERE title LIKE '%".$term."%'";
$r_query = mysql_query($sql);
while ($row = mysql_fetch_array($r_query)){
echo '<br> '. $row['title'] .'';
}
}
?>
And the code that i have at the moment, it works by be manually typing in the hyper link, however I wish to make it take the link from the database like the example above
//query the database
$query = mysql_query("SELECT * FROM hobby WHERE id = '1' ");
//ferch the results / convert results into an array
WHILE($rows = mysql_fetch_array($query)):
$title = $rows['title'];
echo "<a href='shard.php'>$title</a>";
endwhile;
?>
Many thanks!
I am not 100% certain if this is what you meant to ask... let me know in comments:
<?PHP
$query = mysql_query("SELECT * FROM hobby WHERE id = '1' ");
if(mysql_num_rows($query) >= 1) {
while($rows = mysql_fetch_array($query)) {
echo sprintf("%s", $rows["description"], $rows["title"]);
}
} else { echo "No hobbies found."; }
?>
I believe you might have faced some syntax issues while dealing with quotes parsing a variable in <a html tag. Consider using sprintf something like in my example.
I have also added a mysql_num_rows() just in case and you can see its a good fail-safe method incase there are no rews found on any select query.
IMPORTANT: STOP using mysql_ functions because its deprecated from new PHP versions. Use PDO or mysqli instead.

Categories