我准备好的语句返回" null"

时间:2014-12-10 05:38:15

标签: javascript php mysqli prepared-statement

我正在阅读防止SQL注入,我试图转换我的代码。在我更改它之前,当页面被加载时,我会用'input[name="amount"]'中的任何内容更新我的sql并更改id" freetexts"无论echo json_encode($result);给出了什么。现在我改变之后,freetexts的值不断变为" null"

这是我的php

<?php
$username="XXX";
$password="XXX";
$database="XXX";
$amount = $_POST["amount"];


$conn = new mysqli(localhost, $username, $password, $database);

// Check connection
  if(mysqli_connect_errno()) {
      echo "Connection Failed: " . mysqli_connect_errno();
      exit();
   }

/* create a prepared statement */
if ($stmt = $conn->prepare("UPDATE freetexts SET amount = amount - ? WHERE 1")) {
}
/* Bind parameters: s - string, b - blob, i - int, etc */
$stmt -> bind_param("s", $amount);

//$update = "UPDATE freetexts SET amount = amount - '$amount' WHERE 1";
/* Execute it */
      $stmt -> execute();

      /* Bind results */
      $stmt -> bind_result($result);

      /* Fetch the value */
      $stmt -> fetch();

echo json_encode($result);

      /* Close statement */
      $stmt -> close();


?>

这是我的javascript

    var amount = $('input[name="amount"]').val();
    $.ajax({
        type: 'POST',
        data: {
            amount: amount
        },
        url: 'textlimit.php',
        success: function(data) { //Receives the data from the php code
            document.getElementById('freetexts').innerHTML = "Current FREE texts left: " + data;
        },
        error: function(xhr, err) {
            console.log("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
            console.log("responseText: " + xhr.responseText);
        }
    });

1 个答案:

答案 0 :(得分:0)

感谢@tkausl和@Darren,我已经意识到我的代码中没有实际选择我想要的行。我还了解到WHERE 1几乎没有。这是经过修改的php,它运行良好,但我也怀疑它是否经过优化。关于如何使代码更好的任何想法?如果没有必要,请删除$stmt -> fetch();

<?php
define('DB_SERVER', "localhost");
define('DB_USER', "XXX");
define('DB_PASSWORD', "XXX");
define('DB_DATABASE', "XXX");


$amount = $_POST["amount"];


$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);

// Check connection
  if(mysqli_connect_errno()) {
      echo "Connection Failed: " . mysqli_connect_errno();
      exit();
   }

/* create a prepared statement */
if ($stmt = $mysqli->prepare("UPDATE freetexts SET amount = amount - ?")) {

/* Bind parameters: s - string, b - blob, i - int, etc */
$stmt -> bind_param("s", $amount);

/* Execute it */
      $stmt -> execute();

      /* Bind results */
      $stmt -> bind_result($result);

      /* Fetch the value */
      $stmt -> fetch();



      /* Close statement */
      $stmt -> close();
      }

$query = "SELECT `amount` FROM `freetexts`";

$result = $mysqli->query($query);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
              echo json_encode($row["amount"]);  
    }
} else {
    echo "0 results";
}


$mysqli->close();
?>