PHP Link Click counter - php

I want to write simple counter for links/tags. So I have tags and random displayed them to the website
$zmienna = "SELECT name, link FROM tag_content ORDER BY RAND() LIMIT 4";
$result2 = mysql_query($zmienna);
echo $result2;
while($row=mysql_fetch_array($result2)){
echo "<a href='http://www.simplelink.xx/tag/".$row['link']."'>".$row['name']."</a><br>";
}
And now I want to count how many users clicked tags. I created another row named "wys" and tried to write SQL stuff
$wtf = "UPDATE tag_content SET wys=wys+1 WHERE id=2";
$result3=mysql_query($wtf);
As u can see it only works for tag id = 2. And now the problem: how to make it work for all tags?
For example: I have 4 tags with different id. How to make counter "read" the actual clicked tag and make it add "1" to the "wys"?
Thx for help and let me know if u need more information (like code etc.)

As the link field is unique, you can simply use it as an identifier instead of id.
$wtf = "UPDATE tag_content SET wys=wys+1 WHERE link='".$something."";
where $something is a last part of page URL (you should parse it). Of course you also need to check this variable before you use it, because you got it from client side and it could have code for SQL-injection.

You need a way to get the id of all links. Either provide it as a query parameter for the link, or use parse out the name and url from the clicked link and make a relevant SELECT to get the id to loop over.

Use jquery :eq() selector to find out the exact link and then make an ajax request for updating the count

Related

How would i go about producing a username instead of a user id in profile.php?

Ok guys well to boot this up what i am wanting is to remove the echo of userid in the url and replace it with the actual username.
the full code is in the link below the partial code.
if(!isset($_GET["u"]) || !($u = $db->getRow("SELECT * FROM `".MLS_PREFIX."users` WHERE `userid`= ?i", $_GET["u"]))){
http://pastebin.com/yM5gLAkr
EXAMPLE:
CURRENT: index.php?u=1
what i want: index.php?u=username
Simply change
WHERE userid= ?i
to
WHERE username= ?s
This should be enough, unless there's a bunch of other stuff using $_GET['u'].
You will also need to update every single link / form on the website that redirects with ?u=$userid.

How to store post variables value

I got a Index page on which search page is included, and when I submit it, it passes values to find.php through action and method post. The code is below
if($_POST['searchsubmit']=="Search"){
$cat=$_POST['searchcategory'];
$area=$_POST['searcharea'];
$term=$_POST['searchbox'];
}
The above code is written on find.php, Now when I try to implement paging through basic paging method with where conditions to make appropiate search query
$where="where approved='yes'";
if($term!=""){
$where.=" and name like '%$term%'";
}
if($cat!=""){
$where.=" and category like '%$cat%'";
}
if($area!=""){
$where.=" and area like '%$area%'";
}
$start=0;
$end=5;
if($_GET['page']!="")
{
$start=$_GET['page']*$end;
}
Where $start is my initial limit, and $end is my number of records. For the first page of paging, I pass a variable page with 0 for first page
First
and my search query now becomes
$que="select * from shops ".$where." ORDER BY likes DESC limit $start,$end";
As soon as I click on "first", My new link become "/find.php?page=0"
and the post values which I recivied from index page search bar are lost.
Is there any way to retain those values ?The two methods which I though are sending them again through url with GET, or the other way is to store them in session.
Is there any third method available ?
Marc is absolutely right. Do not use the code as it is.
As an alternate solution to your problem -
Your page index.php (search form) submits to itself
Assemble your search query as querystring in index.php if its a post
Redirect to find.php with the assembled querystring
Every search information will always be in the querystring.
Use your pagination happily.
The comments are correct.
Use:
// Start the session
session_start();
// Save variables into session
$_SESSION['somevalue'] = $_POST['value'];
Then when any page calls session_start it will have access to $_SESSION['somevalue']
Also, you are wide open for SQL injection. Sanitize your values to ensure no one can put arbitrary sql code into the string. if you are using mysqli it should as simple as this:
// After connecting to the DB
$_POST['somevalue' = $mysqli->real_escape_string($_POST['somevalue']);
Then be sure to hardcode quotes around string values like you are doing.
If you want to be safer you can use prepared statement instead.
Hope this helps.

Random URL redirect using PHP and MySQL

I have a question about adding a link to my website that when 'clicked' will send the user to a random URL stored in my MySQL database.
My database is titled "movie" and I would like to be able to have the user click on a link and it would send them to one of the movie page URLs stored in my database.
EX: The user clicks the "Random" link and gets taken to a movie page from my database(I have about 110 URLs listed with a unique Id).
Would I use something like:
header('Location: 'xxxxx);
To accomplish this?
I know I should be able to accomplish this task using PHP, I am just having trouble figuring this one out. Any help would be great! Thanks.
I'm assuming the query you posted selects one random movie, and that the field where the url is stored is called 'url'.
$result = mysql_query("SELECT url FROM movie ORDER BY RAND() LIMIT 0, 10")
or die(mysql_error());
$row = mysql_fetch_assoc($result);
mysql_free_result($result);
header('Location: '.$row['url']);
This should redirect to the url in the database.
try this:
mt_rand("", ""); // this creates random numbers and use it in a variable as:
$id= mt_rand("1", "110");
// hatever id number is generated it will put out that one in the query but it is only for one if you want multiple put $id in a for loop than print the result in while loop.
$result = mysql_query("SELECT url FROM movie WHERE id= '$id' LIMIT 0, 10")
or die(mysql_error());
$row = mysql_fetch_assoc($result);
mysql_free_result($result);
header('Location: '.$row['url']);

Correct way to use an if statement and a $GET in PHP

Am fairly new to PHP and am making a basic CRUD style management system. I Have an update page and it displays data from a News table, and populates a form with it. The current picture ?(reference) is pulled through and displayed on the form. However if a user wants to change the picture they can press a 'delete' button and then I have written some PHP to display a upload button, set the values in the database for the image to null and hide the delete button, allowing the user to upload a new picture.
The Delete button only removes the reference (path) to the picture from the database, it doesn't delete the actual picture.
This is the HTML control to show the image and delete button. It also shows how the delete button works:
<td align="right">Image 1:</td>
<td align="left"><img src="uploads/newsimages/<?php echo $row["Image"]; ?>" width="230" border="0"> delete</td>
As you can see, when clicked it sets change=imagex and cid= the current news id.
There is then an if statement I have written, but it doesn't seem to only get activated when the delete button is clicked. Because I always get an error that 'cid' is undefined. It is as follows:
<?php
if (isset($_GET['change'] = "image1") {
$query = "UPDATE Table_Name SET Image = '' WHERE NewsID =".$_GET['cid']." ";
}
?>
I am pretty sure my lack of PHP knowledge is letting me down and I am trying to go about this the wrong way, because however I alter the if statement it always gives me an error. First it was cid is undefined so I changed to id but i already use that for something else, another query/function. I hope that all amde sense, can anyone tell me where Im going wrong?
You are missing a parenthesis + you have to specify individually:
if (isset($_GET['change'] = "image1") {
Change to:
if (isset($_GET['change']) && $_GET['change'] == "image1") {
Some more things to consider:
1) Don't use unsanitized values directly from $_GET in a mysql query
WHERE NewsID =".$_GET['cid']."
It is very easy to exploit this with some funky sql injection (see http://xkcd.com/327/ ).
If you are using numeric values for cid, you should cast your $_GET value to integer to prevent sql injection:
$cid = (int)$_GET['cid];
$query = '(...)WHERE NewsID = '.$cid.' limit 1';
Or even better:
$cid = (int)(array_key_exists('cid', $_GET) ? $_GET['cid'] : 0);
if ($cid) {
$query = (...)
}
If you need this kind of sanitizing in different places, you should think about writing a helper function for it to keep your code readable.
2) Don't use GET requests to change data on your server
Imagine a google bot browsing your site and following all those links that you use to delete images. Other scenarios involve users with prefetch plugins for their browsers (e.g. Fasterfox). Also, GET requests may be cached by proxies and browsers, so that the request won't hit the server if you click the link.
The HTTP specification comes with numerous request methods, the most important ones are:
GET to fetch content from the server
PUT to store new information on the server
POST to update existing information on the server
To update your news record (by removing the image) the appropriate method would be POST. To send a POST request, you can use the <form method="POST"> tag.
try this
<?php
if (isset($_GET['change']) && $_GET['change'] == "image1") {
$query = "UPDATE Table_Name SET Image = '' WHERE NewsID =".$_GET['cid']." ";
}
?>

Displaying name instead of ID PHP MySQL

I need something simple; I have page where a user clicks an author to see the books associated with that author. On my page displaying the list of books for the author, I want a simple HTML title saying: 'The books for: AUTHORNAME'
I can get the page to display author ID but not the name. When the user clicks the link in the previous page of the author, it looks likes this:
<?php echo $row['authorname']?>
And then on the 'viewauthorbooks.php?author_id=23' I have declared this at the start:
$author_id = $_GET['author_id'];
$authorname = $_GET['authorname'];
And finally, 'The books for: AUTHORNAME, where it says AUTHORNAME, I have this:
echo $authorname
(With PHP tags, buts its not letting me put them in!) And this doesnt show anything, however if I change it to author_id, it displays the correct author ID that has been clicked, but its not exactly user friendly!! Can anyone help me out!
You could pull the author_id from the query string as you did using $_GET but beware you will need to validate what is coming through by the query. I hope you can see that without validation how bad of a security hole this is.
I am at work at the moment, but this is a quick example that should give you what you need without sanitizing your query.
$id = intval($_GET['author_id']);
// of course, perform more validation checks
// just don't assume its safe.
$sql = "SELECT authorname FROM authors_tb WHERE author_id=" . $id;
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
echo "The books for: " . $row['authorname'];
}
The reason why your approach wasn't working was because you utilize the $_GET URL parameter passing for author_name where you weren't supplying the parameters in the URL, just the author_id.
You don't send it in the query string, thus you can't get it from the $_GET array.
Just request it from the database using id.
An important note: Always use htmlspacialchars() when you display the data, coming from the client side.
This is because you do not define the author name in your get.
You should make the following your url:
<?php echo $row['authorname']?>
Or rather select the data from the database again, on the new page, using the ID you retrieved from the URI.
Author name won't be in $_GET. As your code stands, you only use it as the link title. It is no where in the address. Try this instead:
<?php echo $row['authorname']?>
It would be better to re-request it from the database using the author_id though.
EDIT:
To explain the problem in more detail. You have two pages, the new.php page and the viewauthorbooks.php page. You're sending users from the new page to the view page using the link you posted, right?
The problem with that is, your link assigns one variable in get. Here's the query string it would generate:
viewauthorbooks.php?author_id=13
What that will do is send the user to viewauthorbooks and place the value '13' in the $_GET variable: $_GET['author_id']. That is why the author_id is there and displays on viewauthorbooks. However, authorname is never passed to viewauthorbooks, it isn't in $_GET['authorname'] because you never set $_GET['authorname']. If you want it to be in $_GET, then you need your query string to look like this:
viewauthorbooks.php?author_id=13&authorname=bob
You can accomplish that using the new HTML code for the link I posted above. Look at it closely, there's a key difference from the one you have now.
However, it is generally discouraged to pass data through GET, because the query string is displayed to the user and it leaves you open to injection attacks. A better way to do this would be to use the author_id you are already passing to viewauthorbooks.php to retrieve the authorname from the database again. You can use the same code you used on the new.php page.

Categories