简体   繁体   中英

Updating SQL database using jQuery Ajax and PHP

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

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

    $('.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

 <?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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM