...

View Full Version : Displaying an ad based on user input?



greens85
02-01-2010, 01:14 PM
Hi All,

I have 2 drop down search boxes with 2 options, Category & Region.

If the user selects a category & a region I want to display an ad that is relevant to the region they choose...

However if they select a category but leave the region blank I want to display an ad for the category they select.

I have the following code, which at the min allows the region to over ride the category ads... however if I select a category & no region I still get a region ad.

I'm sure I'm probably missing something simple here, and I think there may be an easier way to do this as my code is a bit long winded...

Would anyone be kind enough to advise?


<?php

function randomImage ( $array ) {
$total = count($array);
$call = rand(0,$total-1);
return $array[$call];
}

// These are the category image arrays

$business_manager = array (
"images/ads/cat_ad1.gif"
);

$cover_supervisors = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$education_recruitment = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$middle_school = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$nursery_nurse = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$playworker = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$primary_head = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$primary_teacher = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$school_support = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$secondary_head = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$secondary_teacher = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$sen_teacher = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$teaching_assistant = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$tesol = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

// These are the region image arrays

$channel_islands = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$east_midlands = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$eastern = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$isle_of_man = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$london = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$north_east = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$north_west = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$northern_ireland = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$scotland = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$south_east = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$south_west = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$wales = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$west_midlands = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

$yorkshire_humberside = array (
"images/ads/1.gif",
"images/ads/2.gif",
"images/ads/3.gif"
);

if ($country == 'Channel Islands' && $category ==
'Business Manager/Bursar Jobs' or
'Cover Supervisor Jobs' or
'Education Recruitment Consultant' or
'Middle School Jobs' or
'Nursery Nurse Jobs' or
'Playworker Jobs' or
'Primary Head Teacher Jobs' or
'Primary Teacher Jobs' or
'School Support Staff Jobs' or
'Secondary Head Teacher Jobs' or
'Secondary Teacher Jobs' or
'SEN Teacher Jobs' or
'Teaching Assistant & HLTA Jobs' or
'TESOL/TEFL/EAL Jobs') {
echo '<img src="'.randomImage($channel_islands).'"/>';
}

if ($country == 'East Midlands') {
echo '<img src="'.randomImage($east_midlands).'"/>';
}

if ($country == 'Eastern') {
echo '<img src="'.randomImage($eastern).'"/>';
}

if ($country == 'Isle Of Man') {
echo '<img src="'.randomImage($isle_of_man).'"/>';
}

if ($country == 'London') {
echo '<img src="'.randomImage($london).'"/>';
}

if ($country == 'North East') {
echo '<img src="'.randomImage($north_east).'"/>';
}

if ($country == 'North West') {
echo '<img src="'.randomImage($north_west).'"/>';
}

if ($country == 'Northern Ireland') {
echo '<img src="'.randomImage($northern_ireland).'"/>';
}

if ($country == 'Scotland') {
echo '<img src="'.randomImage($scotland).'"/>';
}

if ($country == 'South East') {
echo '<img src="'.randomImage($south_east).'"/>';
}

if ($country == 'South West') {
echo '<img src="'.randomImage($south_west).'"/>';
}

if ($country == 'Wales') {
echo '<img src="'.randomImage($wales).'"/>';
}

if ($country == 'West Midlands') {
echo '<img src="'.randomImage($west_midlands).'"/>';
}

if ($country == 'Yorkshire & Humberside') {
echo '<img src="'.randomImage($yorkshire_humberside).'"/>';
}

?>

Many Thanks,

Greens85

mlseim
02-01-2010, 01:48 PM
It would be best to use MySQL for this, but I think you
could also do it with a simple text file (flat-file database).

Come up with a "scheme" or a grid idea that encompasses your layout ...

Example:

category|region|ad|start date|end date|

Each line is a unique ad that will be displayed for a particular category or region.
You can also specify a start and end date so you can add lines ahead of time and
they won't be "active" until those dates.

Separate each field on each line by pipes | ... that makes it easy to separate them.

So build your simple text database using Notepad, and name it "ads.txt" or something
like that .. here's an example. I'll leave the dates off for now (future option).



middle_school|scotland|ad1.gif|||
middle_school|scotland|ad2.gif|||
middle_school|south_east|ad1.gif|||
nursery_nurse|london|ad33.gif|||
middle_school|london|ad45.gif|||


You could end-up with 2000 lines, but that's OK.
They can be all mixed-up, it doesn't matter.
To add another ad, you simply upload the image and add a line to the file.

Then, a PHP script can open your "ads.txt" file and display them however you
want. The script can search, sort, look for only 1 area, 1 category, or both.
The PHP script will open the file and put each line into an array. You can then
explode the lines and create whatever ad displays you wish.

Like I said before, this should really be done with MySQL, but that's up to you.


.

greens85
02-01-2010, 03:27 PM
Thanks for the reply...

I have no problems doing this with MySQL... I have a database setup and ready to go.

How would I get this working with mysql though?

mlseim
02-01-2010, 05:02 PM
You'll first have to build a table.
Either using PHP, or using your MySQL admin panel

That table will have the variables assigned.

Describing it on this forum is possible, but this isn't a
very good venue for posting ... it will take you 3 days
to go back and forth with these postings.

You might want to search Google for some MySQL
tutorials and examples instead of using this forum ...

But, this is a way to set it up using PHP.
You enter your correct MySQL account info and the
script creates and builds a table with the variables:



<?php
// Make a MySQL Connection
mysql_connect("localhost", "user_name_here", "password_here") or die(mysql_error());
mysql_select_db("name_of_your_database") or die(mysql_error());

// Create a MySQL table in a tabled named "ads" ...
mysql_query("CREATE TABLE ads(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
category VARCHAR(80),
region VARCHAR(80),
ad_image VARCHAR(40),
ad_desc VARCHAR(80),
start_date VARCHAR(40),
stop_date VARCHAR(40),
spare1 VARCHAR(60),
spare2 VARCHAR(60))
")
or die(mysql_error());

echo "Table Created!";

?>



This is a pretty decent tutorial:
http://www.tizag.com/mysqlTutorial/mysqltables.php

greens85
02-02-2010, 12:44 PM
Sorry I don't think I've made myself very clear on this one...

I know how to create a table etc...

I was more wondering how the images will be dragged out and displayed with PHP based on the users choice...

e.g. user selects Category - Cover Supervisors & Region - North East... how then does the PHP know whether to display an image from the Cover Supervisors array or from the North East Array...

Likewise if they select just a Category of Primary Teachers & leave region blank, how does it know to display an image from the Primary Teachers array and to completely ignore any of the Region Arrays?

I hope this makes sense, I seem to be having trouble trying to explain what I need to do so I must apologise!

Many thanks

mlseim
02-02-2010, 01:48 PM
Give us the name of your table, and a list of the MySQL variable names.

You have the ability to do several MySQL search queries and keep track of
the results. Do the queries first, and then determine what to do based on the
results of ALL the queries. If any of the queries result in at least 1 row, you know
you've had a successful query match. But which one (or more) of them resulted
in rows found, might change the order in which you pick an ad. You could even do
some sort of "fuzzy logic" to put a "weight" on the number of results from each
query and determine the path to take.

QUERIES to test:
1) Search for BOTH category AND region.
2) Search for region ONLY (even if a category was, or was not, entered).
3) Search for category ONLY (even if a region was, or was not, entered).
4) Determine the user's region based on IP address, and use that instead of the one they entered.
5) Search for region OR category, by order of region.
6) Search for category OR region, by order of category.

Each one of those may or may not result in rows found.
The query number, and number of rows found could be put into an array, and you
could sort them, or do some sort of math to determine which query to use in your
final ad selection.

Of the rows found (or used in the final selection), you may have a "weight" placed
on the advertiser themselves, that gives the random selection higher odds for picking an advertiser
with a higher weight, or score. Perhaps the ads that pay more, get picked more often?

Your ad picking process could get interesting.

But, let me know if my idea (which may not be what you were thinking) gives you any other thoughts or ideas.
I guess I'm looking deeper into this than what you are planning on doing?

Anyhow, we need to know the name of your table (or tables), and MySQL variables name.



.

greens85
02-02-2010, 02:13 PM
Your ad picking process could get interesting.

But, let me know if my idea (which may not be what you were thinking) gives you any other thoughts or ideas.
I guess I'm looking deeper into this than what you are planning on doing?


I think you are right, this is far deeper than I was planning... however it also seems like it would make the advertising options far more interesting... although the coding would also be far too over my head to do!

Basic ad displaying would be fine for now:

e.g. an array of ads for each region & an array of ads for each category.. with regions getting preference over categories, unless the region is left blank at which point the category ad would be displayed.

Example of Region:

North East

north-east-web-design.gif
north-east-php-developers.gif
etc.

Example of Category:

Cover Supervisors

CS-Training.gif
CS-CRB-Check.gif
etc.

And as mentioned above if they were to select Cover Supervisors & North East then one of the north east ads in the array would take preference.

This would be fine for now then I could look at doing the more complicated stuff once this was in place.



Anyhow, we need to know the name of your table (or tables), and MySQL variables name.


Does a table need to be used for this? I have a table containing all the region name which are displayed in the search box like so:


<label>Location:</label>
&nbsp;&nbsp; <br/>
<span class="small">e.g. North East</span>&nbsp; <br/>
<select name="country" id="country" onchange="runcountrysearch()">
<option value="">-- Search All --</option>
<?
$country_query=mysql_query("SELECT * FROM countries ORDER BY country ASC");
while ($country_result=mysql_fetch_array($country_query))
{
?>
<option value="<?=htmlentities($country_result['country'])?>" <? if($a1[country]==$country_result['country']){echo 'selected';}?>>
<?=htmlentities($country_result ['country'])?>
</option>
<?
}
?>
</select>

The Categories however aren't stored in a database, they are hardcoded into the page:



<label>Category:</label>
<br/>
<span class="small">e.g. Cover Supervisor Jobs</span>&nbsp; <br/>
<select name="category">
<option value="">-- Search All --</option>
<option value="Business Manager/Bursar Jobs">Business Manager/Bursar Jobs</option>
<option value="Cover Supervisor Jobs">Cover Supervisor Jobs</option>
<option value="Education Recruitment Consultant">Education Recruitment Consultant</option>
<option value="Middle School Jobs">Middle School Jobs</option>
<option value="Nursery Nurse Jobs">Nursery Nurse Jobs</option>
<option value="Playworker Jobs">Playworker Jobs</option>
<option value="Primary Head Teacher Jobs">Primary Head Teacher Jobs</option>
<option value="Primary Teacher Jobs">Primary Teacher Jobs</option>
<option value="School Support Staff Jobs">School Support Staff Jobs</option>
<option value="Secondary Head Teacher Jobs">Secondary Head Teacher Jobs</option>
<option value="Secondary Teacher Jobs">Secondary Teacher Jobs</option>
<option value="SEN Teacher Jobs">SEN Teacher Jobs</option>
<option value="Teaching Assistant &amp; HLTA Jobs">Teaching Assistant &amp; HLTA Jobs</option>
<option value="TESOL/TEFL/EAL Jobs">TESOL/TEFL/EAL Jobs</option>
</select>

It would be probably easier to link you to the site:

http://www.educationvacancies.com

If do a 'quick job search'... you will be able to see where I am trying to get the ads to display and sometimes that it returns two... this is when it returns region and category... which is my problem!

Many thanks

greens85
02-02-2010, 05:04 PM
Hey,

Forgot to add I've created the table as per your instructions...

So I now have the following:

Table - ads

Fields -

id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
category VARCHAR(80),
region VARCHAR(80),
ad_image VARCHAR(40),
ad_desc VARCHAR(80),
start_date VARCHAR(40),
stop_date VARCHAR(40),
spare1 VARCHAR(60),
spare2 VARCHAR(60))

However I didn't do it through PHP but rather I did it through PHPmyAdmin... although this shouldn't make a difference as I set all the same values as provided by yourself.

Now I have the table setup, I realize I will need to populate it with some data. I don't however know how to add an image to the database...

I kinda know how to search through records on a basic level are pull out the data into rows, but I'm not sure I have the knowledge to do it on this scale...

Can you advise me from here?

Many thanks

mlseim
02-02-2010, 05:38 PM
Put all of the images into a directory, just for the images.
Not sure if each ad is 1 image? In the database, only
put the filename of the image. It's easier to manage images
if they are in a directory, not actually in the database.

When you get some images in a directory, and some data
populated in the database, let us know. we can then try
a simple query.

greens85
02-02-2010, 05:47 PM
Put all of the images into a directory, just for the images.
Not sure if each ad is 1 image? In the database, only
put the filename of the image. It's easier to manage images
if they are in a directory, not actually in the database.

When you get some images in a directory, and some data
populated in the database, let us know. we can then try
a simple query.

Should the it just be the filename in the DB e.g. image.gif or should it be a path /images/image.gif?

Also say I have 3 ads for the North East... does each ad need to have its own record in the database?

I've now added 6 records into the database...

INSERT INTO `educavac_jobvac`.`ads` (
`id` ,
`category` ,
`region` ,
`ad_image` ,
`ad_desc` ,
`start_date` ,
`stop_date` ,
`spare1` ,
`spare2`
)
VALUES (
'1', 'Playworker Jobs', 'North East', '2.gif', 'This is advert number one', '02/01/2010'. '02/02/2010'
), (
'2', 'Nursery Nurse Jobs', 'London', '3.gif', 'Advert', '', '', '', ''
), (
'3', 'Education Recruitment Consultant', 'East Midlands', '1.gif', 'Advert', '', '', '', ''
), (
'4', 'Secondary Head Teacher Jobs', 'West Midlands', '2.gif', 'Advert', '', '', '', ''
), (
'5', 'Business Manager/Bursar Jobs', 'Eastern', '1.gif', 'Advert', '', '', '', ''
), (
'6', 'SEN Teacher Jobs', 'South West', '3.gif', 'Advert', '', '', '', ''
);

mlseim
02-02-2010, 07:30 PM
No path needed ... you already know the path, and most likely,
they are all in the same directory.

I would say, if an ad fits more than 1 category or region, you put it in again,
so yes, one ad might be inserted 6 times for 6 unique categories or regions.

The key is that an ad gets entered into the database ONLY if there is a
region AND a category to assign with with.

So a basic query might look like this:


<?php

// Open your MySQL Database ... your account info here (and keep it secret from us).
$dbhost = 'the_mysql_host';
$dbuser = 'user1';
$dbpass = 'open_sesame';
$dbname = 'ads';

// make the MySQL connection.
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
mysql_select_db($dbname) or die('Cannot select database');

// some test variables
$category = "Nursery Nurse";
$region = "London";

// to deal with case-sensitivity, you may want to always force the user's input to lower-case.
// it's commented-out for now, but this is how to do it.
// $category = strtolower($category);
// $region = strtolower($region);

// ** VERY IMPORTANT **
// always sanitize variables before you use them in ANY query.
$category = mysql_real_escape_string($category);
$region = mysql_real_escape_string($region);

// there are hundreds of ways (combinations) etc. to set-up the query.
// in this example, we'll do a "like" instead of "=".
$query="SELECT * FROM educavac_jobvac WHERE category LIKE '%$category%' AND region LIKE '%$region%' ";

// perform the query.
$result = mysql_query($query) or die(mysql_error());

// now, we can see if there are any "results".
// if the number of rows > 0, that means there were some results of the query.
$num_rows = mysql_num_rows($result);

// we also need to know how many fields you are using (for building our $object array).
$num_fields = mysql_num_fields($result);

// if($num_rows < 1){
// echo "No ads found";
// }

// it might be polite to close the connection ... since we're done with it.
mysql_close($conn);

// this part will vary also, because you can choose to put the results into
// an array (to be used later), or do some while-loop processing. So, for now,
// we'll put it into an array...
$j=0;
$x=0;
$object=array();
while($row=mysql_fetch_array($result)){
for($j=0;$j<$num_fields;$j++){
$name = mysql_field_name($result, $j);
$object[$x][$name]=stripslashes($row[$name]);
}$x++;
}

// at this point, you may choose to "randomize" the array and pick the first one.
// we won't do that now, but the shuffle command will do it.
// shuffle($object);

// Now, everything in the result is in the array called $object.
// We can view those objects by row number and field name.
// (arrays always begin at zero [0]).

echo "The first ad found is: {$object[0]['ad_image']} <br />";

echo "Here is the ad image: <img src='images/{$object[0]['ad_image']} alt='{$object[0]['ad_desc']} /> <br />";

// now it becomes a "free-for-all". you have so many choices to make on
// how to proceed ... whether to do multiple queries, whatever.
// maybe this is enough to get you started?

?>


In this query example, it should have found "3.gif",
because "Nursery Nurse" is LIKE "Nursery Nurse Jobs" and "London" is LIKE "London".


.

greens85
02-03-2010, 10:29 AM
Hi,

I've tried implementing the code...

I had to append 'ad_' to every variable name, as I believe they were clashing with some existing variables that are producing the actual job results!

So basically the code implemented now looks like this:


$category = mysql_real_escape_string($category);
$region = mysql_real_escape_string($region);

$ad_query = "SELECT * FROM ads WHERE category LIKE '%$category%' AND region LIKE '%$region%'";
$ad_result = mysql_query($ad_query) or die (mysql_error());
$ad_num_rows = mysql_num_rows($ad_result);
$ad_num_fields = mysql_num_fields($ad_result);

$ad_j=0;
$ad_x=0;
$ad_object = array();
while ($ad_row = mysql_fetch_array($ad_result)){
for($ad_j=0;$j<$ad_num_fields;$ad_j++){
$ad_name = mysql_field_name($ad_result, $ad_j);
$ad_object[$ad_x] [$ad_name]=stripslashes($ad_row[$ad_name]);
} $ad_x++;
}

//shuffle($ad_object);

echo "The first ad found is: {$ad_object[0] ['ad_image']} <br/>";

echo "Here is the ad image: <img src='images/ads/{$ad_object[0] ['ad_image']} alt='{$ad_object[0] ['ad_desc']} /> <br/>";

However when I do a search with the drop down boxes and select:

'Nursery Nurse Jobs' & 'London'

I get the following errors:

Warning: mysql_field_name() [function.mysql-field-name]: Field 7 is invalid for MySQL result index 7 in /home/educavac/public_html/jobresults.php on line 84

Warning: mysql_field_name() [function.mysql-field-name]: Field 8 is invalid for MySQL result index 7 in /home/educavac/public_html/jobresults.php on line 84

Warning: mysql_field_name() [function.mysql-field-name]: Field 9 is invalid for MySQL result index 7 in /home/educavac/public_html/jobresults.php on line 84

Warning: mysql_field_name() [function.mysql-field-name]: Field 10 is invalid for MySQL result index 7 in /home/educavac/public_html/jobresults.php on line 84

Warning: mysql_field_name() [function.mysql-field-name]: Field 11 is invalid for MySQL result index 7 in /home/educavac/public_html/jobresults.php on line 84

Warning: mysql_field_name() [function.mysql-field-name]: Field 12 is invalid for MySQL result index 7 in /home/educavac/public_html/jobresults.php on line 84

Warning: mysql_field_name() [function.mysql-field-name]: Field 13 is invalid for MySQL result index 7 in /home/educavac/public_html/jobresults.php on line 84

There are far to many of these to list them all but they all appear to be the same type of error, with on the Field number incrementing each time...

A quick search leads me to believe that this function is now depreciated, if this is the case... is there an alternative?

Many thanks...

mlseim
02-03-2010, 12:29 PM
You can't just add "ad_" to every variable ... because your MySQL variables
aren't like that ... so they cannot be found. You would have to delete and re-build
your MySQL table with the new variable names.

Instead ... explain the "clash" thing you mentioned. There is no such thing.
If there happens to be some (a couple or few) variables that I used that were used
in other places, show me the whole script.

I didn't test my script, so maybe it's some other little typo I made ... but now we don't
know what the original problem was. Now it's totally different.

Did you try my script all by itself? I should have produced a result all by itself,
save it as "test.php" and play with it. You don't need to insert my script into another one.
All by itself will not have any problems with "clashing" variables.



.

greens85
02-03-2010, 01:33 PM
Hi,

Testing your script on its own kinda work in that it displays 'The first ad found is: 3.gif & also says 'here is the ad image' but then displays a broken image icon...

You can see exactly what I mean here:

http://www.educationvacancies.com/ad_display_test.php

As for the clashing... What I meant was that I already have some variables existing in the script with names such as $query & $result, The reason I thought this was an issue was that when I typed your script in and tested... my job results had disappeared when I did a search.

Just for reference I have attached the file where I am trying to get the ads to display (didn't paste as its quite long).. but have removed your script, so you can see what it originally looked like...

When I inspect it with firebug, where the image should appear I get the following:


<img one="" number="" advert="" is="" this="" src="images/ads/2.gif alt=">

mlseim
02-03-2010, 05:09 PM
Those two $query and $result don't matter unless your use of them requires
them to remain unchanged. My use of them is only for about 6 lines of code,
after that, I don't care what the values are ... but then again, I can't see the rest of your script.

This line you have is all messed-up ... missing single-quotes.
<img src='images/ads/{$ad_object[0] ['ad_image']} alt='{$ad_object[0] ['ad_desc']} />

I think you want it like this:

<img src='images/ads/{$ad_object[0]['ad_image']}' alt='{$ad_object[0]['ad_desc']}' />

Here's another alternative if that doesn't work:

<img src=\"images/ads/{$ad_object[0]['ad_image']}\" alt=\"{$ad_object[0]['ad_desc']}\" />



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum