3

So i am trying to use ajax to update a value in my sql database by grabbing the link that was clicked and finding that link in the database. I'm not sure why it isn't working :\

$('.visit').click( function() {
var thisLink = $(this).attr('href'); 
$.post("visit.php", { link: thisLink});
});

<?php
$link = $_POST['link'];
mysql_query("UPDATE items SET visited = 1 WHERE link = $link");
include("print.php");
?>
2
  • Also take a look at the 'bind-param' method. You currently have a situation where someone could post to the following url and cause issues. yoursite.com/visit.php?link='data;DROP TABLE [items]' Commented Mar 7, 2011 at 1:31
  • @rcravens right I understand. How would I modify this code using that? Commented Mar 7, 2011 at 1:37

3 Answers 3

2

To prevent the SQL injection use something like the following (typed from memory...double check).

<?php
    $db = new PDO('connection string', 'username', 'password');

    $query = "UPDATE items SET visited=1 WHERE link=:link";

    $stmt = $db->prepare($query);
    $stmt->execute(array(':link' => $link));
?>

Bob

Sign up to request clarification or add additional context in comments.

2 Comments

adding PDO support is php5 (PHP 5 >= 5.1.0, PECL pdo >= 0.1.0) or PECL
@kjy112 good point. Thanks for the example using mysql_real_escape_string.
2
    $('.visit').click( function() {
         var thisLink = $(this).attr('href'); 
         $.post("visit.php", { link: thisLink});
    });

    <?php
         $link = $_POST['link'];
         mysql_query("UPDATE items SET visited = '1' WHERE link = '".mysql_real_escape_string($link)."'");
         include("print.php");
    ?>

use single quote around SET and WHERE params. Also, mysql_escape_real_string inputs into database for SQL injection

Comments

1
 <?php 
  $link = $_POST['link']; 
  mysql_query("UPDATE items SET visited = 1 WHERE link = '$link'"); 
  include("print.php"); // what print.php does ?
 ?> 

put quotes around $link

compare $link with value in database field - it need to be exaclly match

4 Comments

this is the only problem I can see also
hmm yeah that didn't seem to work. I am checking the database and it isn't getting updated. My table is called items and the row is called link. Is my sql syntax right? Also the print.php just prints out the html
about print.php - your jQuery post seems to not care about return - so it wasting of CPU to produce it
well what im trying to do is repost the html and if the link has already been visited i was going to attach a css class to it to demonstrate that. So the print.php does that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.