How to count banner impressions and Clicks - php

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 :)

Related

How to efficiently have 1 html layout page for many products that'll call mysql database for product info and insert where I designate it?

Ok so eventually I will have let's say 100 products in mysql database. The product page pulls all info from database (such as partnumber, material, color, etc...) and inputs it into the areas of the page that I designate it, all this using php. The previous page will show all 100 products and when user click's on one product it'll go to that product page. Just like all websites right...
I don't believe I need to make 100 individual html pages for each product right? Can I make just 1 main html page that is the templet for the 100 different products? Basically when user clicks the image tag of the product(1st example of code) it'll open the main html templet but somehow call to the database on open and load that specific info? Then other products will have the same process but for they're specific data from database. The 1st sample code is one product on the page that'll display all 100 products with the href containing the image that'll get clicked to show user actual product page retrieved dynamically without page reload, into a predestined section. I'm sure there is a name for what I'm looking to do but all the research I've done I haven't found what I'm looking for. Is there a better way then what I'm explaining? Also I hope this makes sense, Thank you for any input.
<td><img class="td-Image" src="image.jpg">
</td>
<td class="td-manufacturer">
<h6>MANUFACTURER</h6>
<p>Lowes</p>
</td>
<td class="td-addComponent">
<p>$104.99</p>
<button class="add-button">ADD</button>
</td>
<td class="td-material">
<h6>MATERIAL</h6>
<p>Aluminum 7075-t6 Forged</p>
</td>
<td class="td-platform">
<h6>PLATFORM</h6>
<p>Large</p>
</td>
<td class="td-america">
<h6>AMERICAN MADE</h6>
<p>YES</p>
</td>
Actual product page where php gets info from database example
<?php
$sql = "SELECT * FROM Parts;";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if($resultCheck > 0) {
while ($row = mysqli_fetch_assoc($result)) {
?>
<div class="description">
<h3>Descrption</h3>
<p>
<?php
echo $row['Description'];
?>
</p>
</div>
<?php
}
}
?>
Editor Note: I edited the question to reflect what he want based on thread on my answer below.
In this scenario you would need to pass in a unique identifier i.e product-id and create a query to fetch from the database product info by product-id
$product-id= $_GET['id'];
$strSQL = "SELECT * FROM AR15Parts WHERE id='$product-id'";
$rs = mysql_query($strSQL);
if (!$rs) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_assoc($rs);
//display your data
if($row){
echo $row['field'];
}
Add an unique Id to your products in your mysql database, using the Auto Increment option (A_I checkbox in phpmyadmin). Then you can pass that id into a link to the product page ```href=“individualProduct.php?id=” while rendering all the products on the all products page.
Then in individualProduct.php you can get that id and retrieve the data
$sql = SELECT * FROM Parts WHERE id =?”;
$stmt = mysqli_prepare($sql);
$stmt->bind_param($_GET[“id”]);
$stmt->execute();
$result = $stmt->get_result();
// Do stuff with $result as it is the individual product corresponding to that id
Optimally, you'll need 2 files:
index/list of products
detail information of the selected product
index files (maybe call it index.php)
Here, you need to select products and make it a list:
$stmt = $pdo->query("SELECT * FROM Parts");
while ($row = $stmt->fetch()) {
echo '' . $row['name']."<br />\n";
}
Since you want the detail to be shown to the index/list page, let's add a container area:
<div id="container-detail">
</div>
Add a little javascript code to handle AJAX request:
<script type="text/javascript">
function loadDetail(itemId){
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://website.address/path/to/detail.php?id=" + itemId, true);
xhr.onreadystatechange = function ()
{
if (xhr.readyState==4 && xhr.status==200)
{
document.getElementById("container-detail").innerHTML=xhr.responseText;
}
}
xhr.send();
}
</script>
detail page (let's call it detail.php)
In this screen, we fetch details for only one part, specified by HTTP GET id parameter. The one that's being supplied from index.php (the ?id= part).
$stmt = $pdo->query("SELECT * FROM Parts WHERE id = '" . $_GET['id'] . "'");
$part = $stmt->fetch();
echo "Name: " . $part['name'] . "<br />\n";
echo "Manufacturer: " . $part['manufacturer'] . "<br />\n";
echo "Price: " . $part['price'] . "<br />\n";
That's it, you should get it working with a few adjustments based on the table and template you have.
A little note is that I used PDO mechanism to do the query. This is because mysql_* function has been deprecated for so long that it is now removed from PHP 7.0. Also, the current PHP version has been PHP 8. So, be prepared, a lot of web hosting might gonna remove older PHP versions, moving forward.

Tag cloud using php and mysql - how to link a new page using the mysql column name

I am going to word this to the best of my ability. I have added links to the pages I need help with and their are instructions on there as well. I am new to php and need help please, thank you.
P.S.
I would like to keep the code I have unless you have a better one.
MY QUESTION --- I have created buttons with words from my database table. What I need to know is how to add a link button to the word you click on and this link will open up my articlestagresults.php page and show the word that was selected as well as list the articles according to the word they selected from the tag cloud. Please look at my two web pages and see what I am trying to do.
Here are my two pages with notes in them to better show what I mean.
https://livinghisword.org/articlestagresults.php ----
https://livinghisword.org/articlestagcloud.php
enter code here
THIS IS THE CODE FOR articlestagcloud.php --- below
$sql = mysqli_query($db_conx, "SELECT word FROM articles GROUP BY word ORDER BY word ASC");
while ($row = mysqli_fetch_array($sql)) {
$word = $row['word'];
ksort($word);
echo "<div class='cloudbox tag'>$word</div>";
}
Thank you very much for all the help coming!
You just need to wrap the word in anchor tag like this
echo "<div class='cloudbox tag'><a href = 'articlestagresults.php?word=" . $word . "'> " . $word . "</a></div>";
In articlestagresults.php, You can simply get the word by print_r($_GET['word']); This will give you the selected word from the previous page.
articlestagresults.php
$word = $_GET['word'];
$sql = mysqli_query($db_conx, "SELECT * FROM articles WHERE word = '$word'");
while ($row = mysqli_fetch_array($sql)) {
print_r($row);// It will contain the row data
//SHOW the HTML
}
I would suggest a simple javascript function for that, such as:
<script type='text/javascript'>
function bindEvents(){
var col=document.querySelectorAll('div.cloudbox');
if( col ){
for( var n in col ){
if( col[ n ].nodeType==1 ){
col[n].addEventListener('click',function(e){
location.href='/articlestagresults.php?word='+this.innerHTML;
}.bind( col[ n ] ), false );
}
}
}
}
document.addEventListener('DOMContentLoaded', bindEvents, false );
</script>
That should append the word=value string to the querystring - so your sql would use the value of $_GET['word'] to process the request.
There are several ways you could do this - rather than using GET you could submit a form using POST which would keep the url in the browser as https://livinghisword.org/articlestagresults.php

How can I display image in PHP using image link stored in MySQL database?

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);

Open dynamic Link from AJAX return using javascript

I am trying to convert my queries from PHP to Ajax.
I am currently using this to return song id results from PHP.
<?php echo $currentSong->title; ?>
using this i get something like this
http://chennaichristianradio.com/PHP/web/songinfo.php?songID=5506
How do I get the same results from Ajax, and get a returned address that is the same as above? the song id at the end is the info that is pulled from my database. This will be used for someone to click on this link to open a new page showing the contents of song id 5506.
You can see what i am attempting to do using using my current PHP here. Just clike on one of the "song info" buttons.
http://chennaichristianradio.com/PHP/web/history.php
I attempted the following using AJAX without success. Don't laugh to loudly over my code as I am just learning AJAX and PHP.
Script
document.getElementById('ID').innerHTML = aj_ID "<a href="songinfo.php?songID=+ aj_results[7] + >"
and in HTML
</div>)" title="Lyrics and song info"><img src="../../images/info.png" alt="Track information" width="70" height="22" border="none" title="Song Info and Lyrics" />
Thank you for your help
Edited:
Here is my ajax Script
<?php
//Sam Broadcaster - AJAX Module - Send Artist/Title/Duration and Seconds remaining to getXMLHTTPRequest
//Written, cobbled together by wilksy101. This code contain code sourced from the support forums and stuff written myself
// Change to your database user name
$username="************";
//Change to your database password
$password="************";
// Change to your database name
$database="************";
// Connect to the database
mysql_connect('ccronline.dyndns.info',$username,$password);
// Handle an error
#mysql_select_db($database) or die( "Unable to select database");
// Build Sql that returns the data needed - change this as required.
$sql = "SELECT songlist.*, historylist.listeners as listeners, historylist.requestID as requestID, historylist.date_played as starttime FROM historylist,songlist WHERE (historylist.songID = songlist.ID) AND (songlist.songtype='S' OR songlist.songtype='C' OR songlist.songtype='N') ORDER BY historylist.date_played DESC LIMIT 1";
// Store results in result object
$result = mysql_query($sql);
//store values in vars for calculation for array creation
$curPlay = mysql_query("SELECT * FROM historylist ORDER BY date_played DESC LIMIT 1");
$curPlayRow = mysql_fetch_assoc($curPlay);
if (!$curPlay) { echo( mysql_error()); }
$dt_duration = mysql_result($result,$i,'duration');
$title= mysql_result($result,$i,'title');
$artist= mysql_result($result,$i,'artist');
$album= mysql_result($result,$i,'album');
$picture= rawurlencode(mysql_result($result,$i,'picture'));
$lyrics= mysql_result($result,$i,'lyrics');
$ID= mysql_result($result,$i,'ID');
$curtime = time();
$timeleft = $starttime+round($dt_duration/1000)-$curtime;
$secsRemain = (round($dt_duration / 1000)-($curtime-$starttime));
//build array to return via getXMLHTTPRequest object - you can include more vars but remeber to handle them
//correcty in the useHttpResponse function
$Aj_array = $dt_duration . '|' . $secsRemain . '|' . $title . '|' . $artist .'|' . $album .'|' . $picture .'|' . $lyrics .'|' . $ID;
//we are using the text response object - which i think is easier for small data return
//just echo the array - not so much AJAX rather AJA ??
echo $Aj_array
?>
so you are basically trying to get the content that you are currently displaying in the popup window at http://chennaichristianradio.com/PHP/web/history.php to appear within the same page using AJAX?
I think the main problem you have here is that you haven't established a relationship between the song and its listing html elements.
Try changing all of your "fill" divs to have an id that includes the song number EG: "fill5669" you can then use this to determine where in the page to load the content from your ajax call like in this example:
function songInfo(songID){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{// support OLD crusty versions of IE.
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.getElementById('fill'+songID).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://chennaichristianradio.com/PHP/web/songinfo.php?songID="+songID,true);
xmlhttp.send();
return false;
}

php image show issu

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.

Categories