-1

Can somebody help regarding to my PHP and jQuery? I try to change my password using PHP, jQuery and Ajax. I know this method is kind of weird. But I want to explore more about Ajax, jQuery with PHP. I want to UPDATE my password without showing or typing the current password. I want my textbox empty and if I input something it will change my password in my db table. Don't need to type my current password. My problem is it didn't update my password. How can I update my db password? depends who is login.

<?php 
     $conn = new mysqli("localhost", "root", "", "mydb");
 if(isset($_POST["btnChange"])) {
        $checkUser = $conn->query("SELECT * FROM tbl_user WHERE id= $_SESSION[id]");
        if ($checkUser->num_rows > 0) {
            $conn->query("UPDATE tbl_user SET password = '$_POST[new_password]' WHERE id= $_SESSION[id]");
            echo "Update Successfully!";
        }
    }
?>

$(document).ready(function(){

 $("#btnChange").click(function(){
  $.ajax({
   url:"insert.php",
   method:"post",
   data:{btnChange: "", new_password: $("#new_password").val(),},
   success: function(data){
    alert(data);
   }
  });
 });
});
<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="jquery/jquery.js"></script>
        <script src="changeapasswordjs.js"></script>
        <title>Change password</title>
    </head>
    <body> 
        <h1>Change password</h1>
        <form id="simpleForm">
            <div>
                <label for="new_password">Your new_password</label>
                <input type="password" name="new_password" id="new_password" />
            </div> 
            <br>
            <div>
                <button id="btnChange">Change password</button>
            </div>    
        </form>  
    </body>
</html>
Boost PH
  • 15
  • 4
  • `header('Content-Type: application/json');` at the top of your PHP script, then use `json_encode()` to encode your output so your Javascript can read the output. Also, you need to concatenate your SQL. `....SET password = '" . $_POST['new_password'] . "' WHERE....` – Jaquarh Oct 21 '18 at 12:40

2 Answers2

0

To access an array, the key must be in quotes like so ['key']. Also, you can wrap {} around the variable to output it inside a string.

// First query you do
$checkUser = $conn->query("SELECT * FROM tbl_user WHERE id = '{$_SESSION['id']}'");

// Second query you do
$conn->query("UPDATE tbl_user SET password = '{$_POST['new_password']}' WHERE id = '{$_SESSION['id']}'");

You're also missing the content type you're outputting and should encode your response in json:

header('Content-Type: application/json');
echo json_encode("Update Successfully!");

Furthermore, to access the super variable $_SESSION you must first use session_start() prior to accessing the variable.

Further, none question related but a key point moving on, your queries are prone to SQL injection and you should consider turning error logging on.

Jaquarh
  • 6,493
  • 7
  • 34
  • 86
0

First of all, i think your code misses a very important statement which is the session_start() statement.

Secondly, the id session can't be called the way you are calling it in your code, you have to add quotes like this $_SESSION['id'].

You also need to add quotes in the WHERE clause so it becomes a valid statement like the following: WHERE id = '$_SESSION['id']'. Again, you are accessing $_POST array the wrong way, you have to add the quotes like this $_POST['new_password'].

After correcting these mistakes, the final code should look like this:

<?php
session_start(); //Initializing session
     $conn = new mysqli("localhost", "root", "", "mydb");
 if(isset($_POST["btnChange"])) {
        $checkUser = $conn->query("SELECT * FROM tbl_user WHERE id='".$_SESSION['id']."'");
        if ($checkUser->num_rows > 0) {
            $conn->query("UPDATE tbl_user SET password = '".$_POST["new_password"]."' WHERE id='".$_SESSION['id']."'");
            echo "Update Successfully!";
        }
    }
?>

UPDATE

Please reproduce the code to this, it is recommended to use an else statement in case the user doesn't exist.

 <?php
 session_start(); //Initializing session
      $conn = new mysqli("localhost", "root", "", "mydb");
  if(isset($_POST["btnChange"])) {
         $checkUser = $conn->query("SELECT * FROM tbl_user WHERE id='".$_SESSION['id']."'") or die(mysqli_error($conn));
         if ($checkUser->num_rows > 0) {
             $conn->query("UPDATE tbl_user SET password = '".$_POST['new_password']."' WHERE id='".$_SESSION['id']."'");
             echo "ID: ".$_SESSION['id'];
         }
         else {
             echo "User doesn't exist.";
             echo "<br>ID: ".$_SESSION['id'];
         }
     }
 ?>
nomorehere
  • 332
  • 2
  • 12
  • why it didn;t update my password? There something wrong with my jQuery and Ajax? – Boost PH Oct 21 '18 at 15:10
  • Try changing the `$conn = new mysqli('localhost','root','','mydb);'` to `$con = new mysqli('localhost','root','','mydb') or die(mysqli_error($con));` and see check if there is any mysqli errors – nomorehere Oct 21 '18 at 15:30
  • same sir no error and password didn't change at all. – Boost PH Oct 21 '18 at 15:36
  • Could you please add `echo '
    ID: '.$_SESSION['id'];` to the `if($checkUser->num_rows >) statement` and tell me what is the the current output? Also check if there are any spaces before the `session_start();` and delete them
    – nomorehere Oct 21 '18 at 15:42
  • This is the error in the alert box `
    Parse error: syntax error, unexpected '"', expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C: xampp\htdocs\userAndAdmin/change.php on line 7
    `
    – Boost PH Oct 21 '18 at 16:07
  • I have updated my answer, please check it out and comment the output. – nomorehere Oct 21 '18 at 16:15
  • Same error alert box show this message `
    Parse error: syntax error, unexpected '"', expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in C: xampp\htdocs\userAndAdmin/change.php on line 7
    `
    – Boost PH Oct 21 '18 at 16:25
  • my id is integer and my password is encrypted – Boost PH Oct 21 '18 at 16:33
  • Yeah, there really was syntax errors, i confused the usage of double quotes and single quotes, copy and paste the edited code again. – nomorehere Oct 21 '18 at 17:54