Skip to content
Advertisement

SELECT doesn’t retrieve updated data from DB after INSERT

On one page I’m sending AJAX-request to itself. After getting this request in success-function with PHP I’m adding new record to table “some_table” in some MySQL database. And after that in the same success-function I’m selecting data from this table and showing it on the page by JQuery. The problem is that all old records are shown but not the record which I’ve added just:

$.ajax({
    url: 'http://somesite.com', 
    type: "POST",
    data: ({param1: value1, param2: value2, act: "I"}),
    success: function(data){
        <?php $mysqli = new mysqli("some_server", "some_database", "some_login", "some_password"); 
              $query = "INSERT INTO some_table VALUES ("'.$_POST["param1"].'","'.$_POST["param2"].'")";
              $mysqli->query($query);
              $mysqli->close();
        ?>
        alert("New record was added");
        <?php echo '$("#left_region").html('');';
              $mysqli = new mysqli("some_server", "some_database", "some_login", "some_password"); 
              $result = $mysqli->query("SELECT some_column1, some_column2 FROM some_table"); 
              while($obj = $result->fetch_object()) { 
                  echo '$("#left_region").append("<p class="some_class"><a href="#">'.$obj->some_column1.'</a></p>");';
              } 
              $result->close();
              $mysqli->close();
        ?>
    }
});

Could anybody hint how to solve it?

Advertisement

Answer

You can’t expect for a page to execute the code again if the page has already loaded.

Take this as an example:

Client-side:

$.post("some_url.php",{param1: value1, param2: value2, act: "I"},
      function(response){
         if(isNaN(response)==="true")
             $("#left_region").html(response);
         else
             alert("An error ocurred");
      }
)

Server-side:

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("some_server", "some_database", "some_login", "some_password");
if ($_POST['act']) {
    $stmt = $mysqli->prepare("INSERT INTO some_table VALUES (?, ?)");
    $stmt->bind_param('ss', $_POST["param1"], $_POST["param2"]);
    $stmt->execute();

    $last_inserted_id = $mysqli->insert_id;
    $stmt = $mysqli->prepare("SELECT some_column1, some_column2 FROM some_table where some_column=?");
    $stmt->bind_param('s', $last_inserted_id);
    $stmt->execute();
    $result = $stmt->get_result();
    echo $result->fetch_assoc();
}

Try something like this(if someone finds an error, please correct it, thanks).

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement