how to link a database item to a link - php

I am designing a system for a recruitment agency and have a search page where the "applicants" can search for a job and apply, the search results is structured:
-Job_Title
-Job_description
-Apply link
This is the same for every result. Code for the above mentioned:
$num_rows = mysql_num_rows($query) or die(mysql_error());
if ($num_rows > 0) {
while ($row = mysql_fetch_assoc($query)) {
$title = $row['Adv_title'];
$description = $row['Adv_desc'];
echo "<h2><a href='#'> $title</a> </h2>";
echo "$description <br /> <br />";
echo"<a href='../View/applicationForm.php' class='link-button right'><span>Apply</span></a>";
Now my problem is that I don't know how to make the Apply link go to each Jobs respective Application form. How can I make the link different for each advert or link the application form to Adv_title in the database?

In order to identify each job in applicationForm.php, you need to pass a parameter that identifies each job via $_GET. This parameter should be unique for each job, so it could be the id field in database that you mention, or it could be the title, assuming that you are checking title uniqueness whenever you create a new job.
So, if you want to use id, your code would look like this (assuming that your field is named id):
while ($row = mysql_fetch_assoc($query)) {
$title = $row['Adv_title'];
$description = $row['Adv_desc'];
$id = $row['id'];
echo "<h2><a href='#'> $title</a> </h2>";
echo "$description <br /> <br />";
echo"<a href='../View/applicationForm.php?id=$id' class='link-button right'><span>Apply</span></a>";
If, for any reason, you don't want end users to view your ids, you can always encrypt them before showing, and decrypt them in applicationForm.php.

In hyperlink tag give the value of the link to redirect to instead of #.
Like you have Adv_Title and Adv_desc field you will need to keep the link too and then you can fetch it and use it.
while ($row = mysql_fetch_assoc($query)) {
$title = $row['Adv_title'];
$description = $row['Adv_desc'];
$link=$row['Adv_link'];
echo "<h2> $title </h2>";

$num_rows = mysql_num_rows($query) or die(mysql_error());
if ($num_rows > 0) {
while ($row = mysql_fetch_assoc($query)) {
$title = $row['Adv_title'];
$description = $row['Adv_desc'];
$id = $row['Adw_id'];
$link = "/$id/View/applicationForm.php";
echo "<h2> $title </h2>";
echo "$description <br /> <br />";
echo"<a href='../View/applicationForm.php' class='link-button right'><span>Apply</span></a>";

if application from is different according to the job adv, you better should have a field in the database table to consider about different application form according to each Adv_title.
while ($row = mysql_fetch_assoc($query)) {
$title = $row['Adv_title'];
$description = $row['Adv_desc'];
$id = $row['Adw_id'];
//if $row['url_link'] is full url
$link = $row['url_link']; // full link
//if $row['url_link'] is just and identifier
// some conditions goes here
......
echo "<h2> $title </h2>";
echo "$description <br /> <br />";
echo "link";

If you really want to hide the id, you can set a server side session variable holding the current job id. And the pick it up on the page that generates the application form. ALternatively, just include it as part of the URL as manuelpedrera shows.

Related

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

session variable between 2 divs on same page?

im trying to pass a session between 2 div on the same page.
i have links, when i click on one i want the id to pass to the other div to populate it with the info from the link, but it doesnt pass!!
this is the code from my links div
$q =mysqli_query($link, "SELECT * FROM products WHERE status = 1 ORDER BY id DESC");
while($row = mysqli_fetch_array($q)){
$data = $row['image'];
$file = substr($data, strpos($data, "/") + 1);
$_SESSION['id']=$row['id'];
echo"<div class='homedogs'>",
"<a href='merchandise.php' class='productchoice'>",
"<img class='nailthumb-container3' src='$file' alt='{$row['name']}. Image' />",
"</a>",
"<br />",
'NAME: ',$row['name'],"<br />",'PRICE: ',$row['price'],
"</div>";
}
}
and this is other div that i want to use the session in
include 'inc/connect.php';
$q = mysqli_query($link, "SELECT * FROM products WHERE id = '".$_SESSION['id']."'") or
die (mysql_error());
while($row = mysqli_fetch_array($q)){
$data = $row['image'];
$file = substr($data, strpos($data, "/") + 1);
echo"<div class='rehomediv'>",
"<img class='nailthumb-container2' src='$file' alt='{$row['name']}. Image' />","<br
/>",
"<div class='nameagesex'>",
"<div class='item_name'>{$row['name']}</div>",
"<br />",
"<span class='item_price'>{$row['price']}</span>",
"</div>",
"<div class='description'>",
nl2br($row['description']),
"</div>",
</div>;
im sure its simple enought but i cant get it! can anyone help?
thanks
EDIT!!!!!
on page load, pid is not set so i get an error, is there anyway to have it that if pid is not set then it just display the last record?
for anyone confused by this edit, check the accepted answer..
You are assigning $_SESSION['id'] multiple times inside a while loop. This will end up keeping only the last value, provided that you do session_start(), as you claim you do.
If you want this to work, don't use $_SESSION, but a GET query instead. Change your link-producing code to:
"<a href='merchandise.php?pid={$row['id']}' class='productchoice'>"
...and, in merchandise.php check $_GET['pid'] to determine the product id being requested:
if(isset($_GET['pid']))
// show corresponding product (your second listing)
else
// show something else, i.e. the product catalog (your first listing)

Refresh page php

how would i go about refreshing a page after i have submitted a form and done some php stuff with it. Heres my form and the php so far.
<form class="removeform"action='peteadd.php'method='post' enctype='multipart/form-
data' name='image_remove_form' >
<?php
include '../inc/connect.php';
$q = "SELECT * FROM gallerythumbs WHERE gallery = 1";
if($r = mysql_query($q)){
while($row=mysql_fetch_array($r)){
echo "<div class='thumb'>",
"<input type='checkbox' name='remove[{$row['id']}]'>",
"<label for='Remove'><span class='text'>Remove</span></label>",
"<br />",
"<img class='thumbnail' src='{$row['filename']}'
alt='{$row['description']}' />",
"</div>";
}
}
else{
echo mysql_error();
}
?>
<input type='submit' name='submit' value='Remove' />
</form>
</div>
<?php
include '../inc/connect.php';
//if delete was checked, delete entries from both tables
if(isset($_POST['remove'])){
$chk = (array) $_POST['remove'];
$p = implode(',',array_keys($chk));
$t = mysql_query("SELECT * FROM galleryimages WHERE id IN ($p)");
$r = mysql_query("SELECT * FROM gallerythumbs WHERE id IN ($p)");
$url=mysql_fetch_array($t);
$image=$url['filename'];
$url2=mysql_fetch_array($r);
$image2=$url2['filename'];
if ($t){
unlink($image);
unlink($image2);
$q = mysql_query("DELETE FROM galleryimages WHERE id IN ($p)");
$s = mysql_query("DELETE FROM gallerythumbs WHERE id IN ($p)");
}
else{
echo "<span class='text'>
There has been a problem, go back and try again.
<br />
<a href='peteadd.php'>Back</a>
</span>";
}
}
else{
echo "<span class='title'>
There are no images in the gallery
<br />
<a href='peteadd.php'>Add Images</a>
</span>";
}
?>
This for display some thumbnails that are saved in mysql with a remove checkbox above them. When I check them then submit the form the are deleted from the direcotries and the mysql tables ok, but how can I refresh the page so the deletion is obvious?
Thanks for looking
what you are describing sounds like you are displaying your page and within it you run some additional code - like deletion - so when you post your form you end up with images being pull from database and then removed
you should run your logic first and only then display page - that way you will be first deleting your records and then when it came to get data from database it will get right data (without records already deleted)
any other soultion will be nothing but hacky way to bypass problem that souldn't exist in the first place :)
You cannot directly refresh a page with PHP, but you can echo out a refresh tag like this
echo '<meta http-equiv="refresh" content="0">'
, or you can do it with javascript, like
location.reload(true);

PHP - Rendering dynamic web page through web browser

I am new to php and programming,, I have been following a tutorial but I've ran into a problem when trying to display the products onto a web page, This is the code am testing
<?php
if (isset($_GET['id'])) {
include "storescripts/connect_to_mysql.php";
$id = preg_replace('#[^0-9]#i', '', $_GET['id']);
$sql = mysql_query("SELECT * FROM products WHERE id='$id' LIMIT 1");
$productCount = mysql_num_rows($sql);
if ($productCount > 0) {
while($row = mysql_fetch_array($sql)){
$product_name = $row["product_name"];
$price = $row["price"];
$details = $row["details"];
$category = $row["category"];
$subcategory = $row["subcategory"];
$date_added = strftime("%b %d, %Y", strtotime($row["date_added"]));
}
} else {
echo "That item does not exist.";
exit();
}
} else {
echo "Data to render this page is missing.";
exit();
}
mysql_close();
?>
When I try to view the page through my browser I get the message "Data to render this page is missing"
I understand that it''s something to do with
if (isset($_GET['id'])) {
And am assuming maybe it's something to do with the 'id' But I cant work out how to fix it. Any pointers and help would be appreciated, sorry if this seems basic but like I said I am new and cant work this problem out. I've been trying all day
Thanks
Obviously, $_GET['id'] isn't set. If your link was something like http://www.example.com/index.php?id=32, it would be set.
Second, do not use GET/POST variables in queries without sanitising them!
And third, don't use mysql_query in the first place, but PDO or mysqli instead
When you see $_GET it's looking for a parameter in the URL. So:
http://localhost/yourphpscript.php?id=123
...is what it's expecting. Some ID must be defined in the URL.
You could try this code:
<?php
if (isset($_GET['id'])){ //Someone submitted a form or just prepended parameter to link
include "storescripts/connect_to_mysql.php"; //Include script with mysql connection
$id = preg_replace('#[^0-9]#i', '', $_GET['id']); //Sanitize input - remove everything besides numbers
$result = mysql_query("SELECT * FROM products WHERE id='$id' LIMIT 1"); //Execute query. Only 1 product because of LIMIT 1
if (mysql_num_rows($result)==1){ //If the product is found
$product = mysql_fetch_assoc($result) ; //Take the product
foreach ($product as $property => $value){ //Go through each property of product
echo "<div> {$property} : {$value} </div>" ;
}
}
} else {?>
<form method="get" action="<?php $_SERVER['PHP_SELF'] ; ?>">
<input type="text" name="id" />
<input type="submit" value="Submit product ID"/>
</form>
<?php
}
?>
Just ask if you have any questions.
learn to track your id. sanitize and check the url sending the id for correct value passed and again in the begining check the value as in
<?php
echo $_GET['id'];
?>
use this to know what it is your id value

How to display mysql records as preselected checkboxes?

I have a table column called post_tags within a table called posts where assigned tags are stored separated by the # symbol. I also have a table called tags where all tag names are stored. I would like to design my database in a more normalized way but for the purpose I am trying to achieve this is the easiest option.
Anyway, I want to display on the screen all the entries from the tags table as checkboxes, so I do:
$query = mysql_query("SELECT * FROM tags ORDER BY name");
while ($row = mysql_fetch_assoc($query)) {
$tag = $row['name'];
echo "<input type='checkbox' name='tags[]' value='$tag' />\n";
}
Next I want to have the tags that are assigned to a particular post be preselected. For example, if I have a post with the following in it's post_tags column:
party#beaches#dolphins#
I want the "party", "beaches" and "dolphin" checkboxes to be checked by default (while the checkboxes for the other options are unchecked). How can this be done?
try the two results and the in_array() function.
<?php
$tags = mysql_query("SELECT * FROM tags ORDER BY name");
$post_tags = "party#beaches#dolphins#";
$arr_tags = explode("#", $post_tags);
while ($row = mysql_fetch_assoc($query)) {
$check = in_array($arr_tags, $row['name'])? 'checked="checked"' : "";
echo '<input type="checkbox" name="tags[]" value="'.$row['name'].'" '.$check.' />';
echo "\n";
}
?>
UPDATE
Because of Jeff question on performance, I looked for faster solutions and using isset() is faster so this would do a faster lookup of the values. the array_flip() is 3 time less taxing than in_array():
<?php
$tags = mysql_query("SELECT * FROM tags ORDER BY name");
$post_tags = "party#beaches#dolphins#";
$arr_tags = array_flip(explode("#", $post_tags));
while ($row = mysql_fetch_assoc($query)) {
$check = isset($arr_tags[$row['name']])? 'checked="checked"' : "";
echo '<input type="checkbox" name="tags[]" value="'.$row['name'].'" '.$check.' />';
echo "\n";
}
?>
The first thing to do is see if there is any existing data. So run that query and put the result of that table cell into lets say $checkedstring if not then put your default string in.
<?php
$checkedstring = "party#beaches#dolphins#";
//Pull from DB if exsists and set $checkedstring to that value
///
$checkeditems = explode ( "#" , $checkedstring);
$checked = array();
foreach($checkeditems as $item)
{
$checked[$item]=true;
}
$query = mysql_query("SELECT * FROM tags ORDER BY name");
while ($row = mysql_fetch_assoc($query))
{
$tag = $row['name'];
$checkedstatus = '';
if($checked[$tag])
{
$checkedstatus = "checked='checked'";
}
echo "<input type='checkbox' name='tags[]' value='$tag' $checkedstatus />\n";
}
?>

Categories