0

I'm trying to click a picture and change a database value to "0" via an onclick Javascript function. I looked at a few examples but I can't seem to make it work.

How can you use php in a javascript function

How to update data using onclick even CHECKBOX without button submit in php and mysql

Update Database from Javascript onClick By Ajax PHP

This is the index.html file

<script language="javascript">
    function update() {
        $.post("update.php", { num: 0 }, function(result) { 
           alert(result); 
        });
    }
</script>

<img src="image.png" onclick="update()">

This is the update.php file.

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";


$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$num = $_POST["num"];
$id = 1;
$sql2 = "UPDATE db SET Column1='$num' WHERE id='$id'";

if ($conn->query($sql2) === TRUE) {
    echo "Updated";
} else {
    echo "Failed";
}

Would someone please point out what I'm doing wrong?

Matt
  • 5,315
  • 1
  • 30
  • 57
Fr33
  • 61
  • 6
  • 1
    Please, [quit using `alert()` for troubleshooting.](http://stravid.com/en/stop-the-javascript-alert-madness/), use `console.log()` instead. – Jay Blanchard Jun 23 '17 at 18:33
  • 1
    [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)***. Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Jun 23 '17 at 18:34
  • 2
    [Have you watched the AJAX request / response in the browser's developer tools? Have you included the jQuery library in the project? Are there any errors reported? Are you running this on a web-server?](http://jayblanchard.net/basics_of_jquery_ajax.html) – Jay Blanchard Jun 23 '17 at 18:34
  • What is the server response ? the `result` value ? – Mohamed Abbas Jun 23 '17 at 18:36
  • Break this down. Is your problem in Javascript (F12 console) or is it in PHP and updating the database (Php error log) – Matt Jun 23 '17 at 18:37
  • Did you check ajax response in your browser console? – Sehdev Jun 23 '17 at 18:47
  • Thank you all. Jay solved it. – Fr33 Jun 23 '17 at 18:49

1 Answers1

0

Hoping that your table name is not named db You should use a table name (not db) and if the values for column1 and id are number you don't need quotes

 $sql2 = "UPDATE your_table_name SET Column1=$num WHERE id=$id";
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107