0

I have an issue with php and javascript included. Sedning form from data index.php to edit.php

this is my edit.php file:

<script>
function ConfirmNull() {
if (confirm("Are You Sure?")) {
}
else {
window.history.back();
}
}
</script>

<?php 
    session_start();

    // connect to database  
    include("connection.php");


    // update records
    if (isset($_POST['update'])) {
        $chk=$_POST['chk'];
        $manyids=implode(",",$chk);
        //$id = $_POST['id'];
        $name = $_POST['name'];
        $time = $_POST['time'];
        $user = $_POST['user'];

    // if time is NULL ask if you are sure
        if ($time == "") {
            echo "<script type='text/JavaScript'>  
            ConfirmNull(); 
            </script>";
            mysqli_query($db, "UPDATE db SET name='$name', time='$time', user='$user' WHERE id in($manyids)");
            header('location: index.php');
    }           
        else {
            mysqli_query($db, "UPDATE db SET name='$name', time='$time', user='$user' WHERE id in($manyids)");
            header('location: index.php');
        }
}
?>

Right now if the value time variable is NULL it should run javascript with the question: are you sure? If YES continue with SQL and update the db. If Cancell stop the php code and run windows.history.back and do NOT run SQL.

Unfortunately its updating the db when i hit Cancel.

Lucas
  • 93
  • 2
  • 12
  • 1
    Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. You should use prepared statements with bound parameters, via either [**mysqli**](https://secure.php.net/manual/en/mysqli.prepare.php) or [**PDO**](https://secure.php.net/manual/en/pdo.prepared-statements.php). [**This post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) has some good examples. – Alex Howansky Jun 24 '19 at 16:02

1 Answers1

1

PHP's job is to generate the HTML that gets sent to the browser. As far as PHP is concerned, all your JavaScript is just text. It doesn't have any meaning until it gets to the browser. As such, all your PHP will run before any of your JavaScript.

So the proper place to put your check is in a form submit handler in index.php, before the browser even fetches edit.php:

document.querySelector('#myForm').addEventListener('submit', evt => {
  if (evt.target.querySelector('[name="time"]').value === '') {
    if (!confirm('Are you sure?')) evt.preventDefault();
  }
});

And you really do need to fix your vulnerable database code. As a general rule, $ should never appear in an SQL query string.

AuxTaco
  • 4,883
  • 1
  • 12
  • 27