Colby Aley
Colby Aley

Reputation: 331

PHP not inserting into SQL columns

I'm using Ajax to collect the data such as the winningReddit, the LosingReddit, and the win and lose photos. The PHP script (below) is then supposed to send that to the MySQL tables. The "win" and "lose" columns should increase by 1 each time.

For some reason this script is not saving to the database though. What am I doing wrong? Am I missing something?

<?php
if(isset ($_POST['action'])) {

include( 'connection.php');

$winnerLink = $_POST['winnerReddit'];
$loserLink = $_POST['losingReddit'];
$win = $_POST['win'];
$lose = $_POST['lose'];


mysql_query("UPDATE $winnerLink SET win = win + 1 WHERE imagelink = '$win'");
mysql_query("UPDATE $loserLink SET lose = lose + 1 WHERE imagelink = '$lose'");

}

?>

Here's the Ajax code I'm using:

    $.ajax({
        url: 'http://website.com/vote.php',
        method: 'POST',
        data: {
            action: 'save',
            win: chosenURL,
            lose: chosenURL,
            winnerReddit: $(this).attr('id'),
            losingReddit: $(this).siblings('div').attr('id')
        },
        success: function(data) {
            alert('sent');
        },
        error: function() {
            alert('nope')
        }
    });
})
})

Upvotes: 0

Views: 96

Answers (1)

Jason Sperske
Jason Sperske

Reputation: 30446

Replace this

mysql_query("UPDATE $winnerLink SET win = win + 1 WHERE imagelink = $win");
mysql_query("UPDATE $loserLink SET lose = lose + 1 WHERE imagelink = $lose");

With this prepared statement:

$stmt = mysqli_prepare("UPDATE ? SET win = win + 1 WHERE imagelink = ?");
$stmt->bind_param("ss", $_POST['winnerReddit'], $_POST['win']);
$stmt->execute();
$stmt->close();

$stmt = mysqli_prepare("UPDATE ? SET lose = lose + 1 WHERE imagelink = ?");
$stmt->bind_param("ss", $_POST['losingReddit'], $_POST['lose']);
$stmt->execute();
$stmt->close();

You will also need make sure you have connected to a database.

Upvotes: 2

Related Questions