I have the image URL saved in my mySQL database.($imageid).
How can I display images using their respective id? I want to display different images attached to different blog posts,as we see in regular blogs.
Thank you.
Unsure what stage you are, bit you need to query your 'table' for a single result, perhaps the ID? If the column was Imageid then you could display it like below in an array of results.
$con=mysqli_connect("localhost","user","pass","my_db");
$result = mysqli_query($con,"SELECT * FROM table");
while($row = mysqli_fetch_array($result))
{
echo '<img src="' . $row['Imageid'] . '">';
}
mysqli_close($con);
I've a html form box where i can post subject, image and message. if i post a article without image it's show a image box. I don't want the image box. If i post a article without image then it's should be show only subject and message not image box. But It's show a image box with blank box.
So that i use following sql query but nothing happened...
$no_img = mysql_query("SELECT img_name FROM user_post WHERE post_id = '$id'");
$no_img_check = mysql_num_rows($no_img);
if($no_img_check != 0)
{
echo '<a href="blogpost.php?post_id= ' . $id . '&title=' . $sub. ' "><img src="' .
$upload_path . '/' . $imgname . '" width="140" height="105" alt="NO iamge"
/></a>';
}
else
{
echo "NO image";
}
Any Idea...
I think the problem is that the only case when you would get 0 rows is when the userid doesn't match in the database. If the userid is in the database, but there is no image, you would get a non-zero number of results where each result was either a NULL or an empty string (depending on your DB default value for that column).
You are not setting $imgname anywhere. You've only performed a query (SELECT img_name FROM...) but haven't actually retrieved that value from the database (i.e. you have a result $no_img but nothing in your code suggests that you've set $imgname). Use mysql_fetch_array() or similar to actually get that value.
We have a small php script, that displays random adverts on our site . The banners are served from any location we designate.
What I really would like to know, or be pointed in the right direction is, can we somehow collate the number of impressions each banner gets and possibly the click count on that banner.
I am sure this can be done in php, and stored in a db. Just havent got a clue. I searched on Google, and seemingly everything I could find harks back to 2002 and 2003 lol.
Here is our script:
<?php
$Img1 = "path to image folder/banner.png";
$Alt1 = "alt text for banner";
$Url1 = "http://www.externaldomain.com";
$Img2 ="path to image folder/banner.png";
$Alt2 = "alt text for banner";
$Url2 = "http://www.externaldomain.com";
$Img3 ="path to image folder/banner.png";
$Alt3 = "alt text for banner";
$Url3 = "http://www.externaldomain.com";
$Img4 ="path to image folder/banner.png";
$Alt4 = "alt text for banner";
$Url4 = "http://www.externaldomain.com";
$Img5 ="path to image folder/banner.png";
$Alt5 = "alt text for banner";
$Url5 = "http://www.externaldomain.com";
$num = rand (1,5);
$Image = ${'Img'.$num};
$Alt = ${'Alt' .$num};
$URL = ${'Url'.$num};
Print "<img src=\"".$Image."\" alt=\"".$Alt."\" /"; ?>
To initiate the above code ( we fire an include request )
<?php include ("../adserver/thescriptabove.php"); ?>
I see that you already selected an answer, so I'm not sure if you figured it all out, but I was writing out a little tutorial for you. Finally got it done, hope it still helps you out.
Your method seems to be working fine for serving banners, but if you're going to get into databases and tracking clicks/impressions, I would suggest that you go all in. So store your banner properties in the database as well. I'm going to get ahead and assume that your server/web host allows for a few free MySql databases.
What you need to do is create a database, as well as a User/Admin for the database. Then you're going to access the database with a MySql manager, most web hosts provide phpMyAdmin. Once you're inside the database, you need to set up a table to record your data.
Here's how I want you to set it up:
|Table Name: Banners |
|-------------------------|
|Field: | Type: |
|-------------------------|
|ID | int(5) | The Primary Key and Autoincrement attributes should be set on the ID field as well
|Image | varchar(100) |
|Url | varchar(100) |
|Caption | varchar(100) |
|Views | int(10) |
|Clicks | int(10) |
Now that you've got the database done, here comes the hard part, the PHP. I've pretty much done it for you, but it's untested, so I'm sure there will be bugs, that you will have to work out. But it should point you in the right direction, and help you learn.
<?PHP
// First of all, we need to connect to the MySql server
// For more info, check out: http://php.net/manual/en/function.mysql-select-db.php
$conn = mysql_connect("localhost", "username", "password");
if(!$conn){
die('Could not connect to the MySql Server ' . mysql_error());
}
// Now that we've connected to the MySql sever, we need to select the database
// More info can be found on the same link as above
$db_selected = mysql_select_db('my_database', $conn);
if(!$db_selected) {
die ('Could not select the MySql Database: ' . mysql_error());
}
// Now we need to check the URL parameters to see, if we came to this page normally or because a banner was clicked
// If normally, we serve a random banner and increment the Views field in the database
// Otherwise, we increment the Clicks field and direct the user to the banner's URL
if(!isset($_GET['Clicked'])){
// if the Clicked parameter is not set, we came to the page normally
// Let's select a random banner from the database
$result = mysql_query("SELECT * FROM banners ORDER BY RAND() LIMIT 1") or die(mysql_error());
$row = mysql_fetch_array(result);
// Now let's increment the Views field for the banner we selected
mysql_query("UPDATE banners SET Views = Views + 1 WHERE ID = '" . $row['ID'] . "'") or die(mysql_error());
// let's set the URL to this same page but with the Clicked parameter set
$url = "banner_server.php?Clicked=" . $row['ID'];
// Last but not least, we have to output the banner HTML
// Notice, I set the caption on both the 'alt' and 'title' attributes of the 'img' tag,
// that's because IE shows the value of the 'alt' tag when an image is hovered,
// whereas Firefox shows the value of the 'title' tag, just thought you might want that!
echo "<img src=\"" . $row['Image'] . "\" alt=\"" . $row['Caption'] . "\" title=\"" . $row['Caption'] . "\" />";
}else{
// Otherwise, increment the Clicks field and redirect
// First, let's get the ID of the banner that was clicked from the Clicked parameter
$id = (int)$_GET['Clicked'];
// now let's increment the Clicks field for the banner
mysql_query("UPDATE banners SET Clicks = Clicks + 1 WHERE ID = '" . $id . "'") or die(mysql_error());
// now let's select the banner from the database so we can redirect to the URL that's associated with it
$result = mysql_query("SELECT * FROM banners WHERE ID = '" . $id . "'") or die(mysql_error());
$row = mysql_fetch_array(result);
// redirect to the URL
header("location: " . $row['Url']);
}
// Close the MySql connection
mysql_close($conn);
?>
Good luck
why dont you just let google analytics do it for you? Fire off an event when the link is clicked and let google capture it?
onclick="_gaq.push(['_trackEvent', 'Event Name', 'click', 'Button title/name']);"
You can store the $num in the database pretty easy to get your impression count. Clicks require client side action. The easiest way is to call a javascript function that counts when the banner is clicked via AJAX:
print "<img src=\"".$Image."\" alt=\"".$Alt."\" /";
Then have your javascript function (countClick()) execute the AJAX that will tell the server the banner has been clicked.
Another way is to have a passthru page: mysite.com/linkout.php?q=www.google.com and then have linkout.php count that link and update the database, and then redirect them to the variable passed in the URL.
Here are my 2 cents, assuming you have analytics on our site:
Use the following code when outputting a link:
<a class="ad" href="http://thecatisginger.com/" target="_blank" onclick="ga('send', 'event', 'Block-3-Ads', 'Click', 'The-Cat-Is-Ginger-Ad');"><img src="http://citybymouth.com/wp-content/uploads/2015/02/TCIG-Advert.jpg" onload="ga('send', 'event', 'Block-3-Ads', 'Impression', 'The-Cat-Is-Ginger-Ad', {'nonInteraction': 1});" /></a>
To explain:
<a class="ad" href="http://thecatisginger.com/" target="_blank"
Classic link a href link with class 'ad', links to a site, target opens in new tab. Easy.
onclick="ga('send', 'event', 'Block-3-Ads', 'Click', 'The-Cat-Is-Ginger-Ad');">
This is the newer 'analytics.js' google event tracking, onclick event code, that bascially says, hey, you've clicked this link, so 'send' this 'event' to my analytics 'Events' (which can be checked under "Realtime > Events" or "Behaviour > Events"). "Block-3-Ads" is the area on my website I personally know as the area I put ads, specifically its a right hand sidebar area, but it can be anything you want, so make yours a broad category type thing, like a box, inside which you will have different links you want to track. "Click" is simply the type of event you want to track, can be anything. "The-Cat-Is-Ginger-Ad" is this specific ad I want to track and have the information about.
<img src="http://citybymouth.com/wp-content/uploads/2015/02/TCIG-Advert.jpg"
Then you have an img with a src. Easy.
onload="ga('send', 'event', 'Block-3-Ads', 'Impression', 'The-Cat-Is-Ginger-Ad', {'nonInteraction': 1});" />
Then you have an onload event that fires when the image is loaded, it says, 'send' this 'event', categorise it as a 'Block-3-Ads' event, basically the image loading is counted as an 'Impression', before it was click, but not since this little 'onload' is called when it loads, its not a click, but a load / impression, and again, specifically, the ad loaded is 'The-Cat-Is-Ginger-Ad', and finally, there is passing the 'nonInteraction' parameter as 1, which is just telling google you are tracking a non interaction event.
Its pretty self explanatory, tho I may have typed too much.
WARNING: This is not perfect in that the page may load, and the ad may be below the viewport, out of sight of the user, and still get an impression, which is not accurate, so next I'll be working on firing the impression code just once when the user actually scrolls to the ad itself, and views it, instead of firing it every time a page loads that image.
Thanks to #Saad Imran for the code and also big thanks to the question poster
Bellow the update of the code in php 7 if someone else need it for later use
Note : The same Database table and then store this code in banner.php file
<?php
// to only count views
// select a random banner from the database to show
$rows = $db->QueryFetchArrayAll("SELECT * FROM banners ORDER BY RAND() LIMIT 1");
foreach ($rows as $row) {
// Now let's increment the Views field for the banner we selected
$url = "/banner.php?clicked=" . $row['ID'];
echo "<img src=\"" . $row['Image'] . "\" alt=\"" . $row['Caption'] . "\" title=\"" . $row['Caption'] . "\" />";
}
$db->Query("UPDATE banners SET Views = '".round($row['Views'] + 1)."' WHERE id = '" . $row['ID'] . "'");
// to count clicks need an if statement
if(isset($_GET['clicked'])){
$db->Query("UPDATE banners SET Clicks = '".round($row['Clicks'] + 1)."' WHERE id = '" . $row['ID'] . "'");
header("location: " . $row['Url']);
}
?>
Good luck everyone :)
How can i use php to get an image url from database (based on user id) and display it out as an image.
http://mysite.com/img.php?id=338576
The code below shows a php script goes to a database , check whether the specific user(using the id in the link above) exist then get the image url out of that user's row.
<?php
//connect to database
include ("connect.php");
//Get the values
$id = mysql_real_escape_string($_GET['id']);
//get the image url
$result = mysql_query("SELECT * FROM users WHERE id='$id'")
or die(mysql_error());
$row = mysql_fetch_array($result);
if($row)
{
$img_url = row['imgurl'];
mysql_close($connect);
}
else{
}
?>
The $Img_url is an actual image link www.asite.com/image.jpg
The problem is how can i use php to make an image from the image link($img_url)? By which http://mysite.com/img.php?id=338576 will turn into an image.
I hope someone could guide me
Thanks!
The easiest way:
header('Location: url/to/image');
You could also proxy the request, which uses your bandwidth:
echo(file_get_contents('url/to/image'));
This is pretty basic stuff. Am I understanding you correctly? I would just do this:
<?php
$img_html = '<img src="' . $img_url . '" />';
echo $img_html;
?>
Or check this answer:
How do I script a php file to display an image like <img src="/img.php?imageID=32" />?
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..