如何获取单个mysql值并将其输出到ajax调用?

时间:2016-04-18 21:12:07

标签: php mysql ajax

我试图从mysql行获取一个数字,然后将其输出到ajax。数字不能是一个字符串,因为我会在ajax中乘以它。这就是我到目前为止所拥有的。我不知道该怎么做。

AJAX:

$(document).ready(function()
{
    $("#btnCalc").click(function()
    {
        var user     = $("#txtUser").val();
        var amount   = $("#txtAmount").val();
        var category = $("txtCat").val();
        var number   = $("txtNum").val();
        var result = '';

        $.get("code/value.php",
        {
            ID:user,
            amount:amount,
            result:result

        },function(query)
        {
            if ( user > 0 and user < 30 ){
                alert(result);
            }
            else{
                alert( 'invalid user ID');
            }
        });
    });

});

PHP:

<?php

    $userID = $_GET["ID"];
    $amount = $_GET["amount"];
    $category = $_GET["category"];
    $num      = $_GET["number"];

    require "../code/connection.php";

    $SQL = "select userAmount from user where userID= '$userID'";

    $reply = $mysqli->query($SQL);

    while($row = $reply->fetch_array() )
    {


    }

    if($mysqli->affected_rows > 0){
        $msg= "query successful";
    }
    else{
        $msg= "error " . $mysqli->error;
    }

    $mysqli->close();

    echo $msg;
?>

3 个答案:

答案 0 :(得分:2)

非常简单 - 您只需从行中获取值并将其转换为浮点数。

while($row = $result->fetch_array() )
{
    $msg = floatval($row['userAmount']);
}
if($msg > 0) {
    echo $msg;
} else {
    echo "error" . $mysqli->error;
}

$mysqli->close();

你的ajax电话中的一个小变化:

    $.get("code/value.php",
    {
        ID:user,
        amount:amount,
        result:result

    },function(query)
    {
        alert(query);
    });
});

答案 1 :(得分:1)

您需要在echo $row['userAmount'];循环内或之后添加while,然后删除第二个echo。您应该能够在AJAX代码中使用result并将其直接用作数字。

答案 2 :(得分:1)

此处function(query)query是来自AJAX调用的响应。所以你的警报应该是:

alert(query);

result为空。

您还应该使用prepared statementsoutputting所需的值。

类似的东西:

<?php
    $userID = $_GET["ID"];
    $amount= $_GET["amount"];
    require "../code/connect.php";
    $SQL = "SELECT userAmount FROM user WHERE userID= ?";
    $reply = $mysqli->prepare($SQL);
    if($mysqli->execute(array($userID))) {
        $row = $reply->fetch_array();
        echo $row['amount'];
    }
    else
    {
        $msg = "error" . $mysqli->error;
    }
$mysqli->close();
?>

然后JS:

$(document).ready(function()
{
    $("#btnCalc").click(function()
    {
        var user       = $("#txtUser").val();
        var amount     = $("#txtAmount").val();
        var result = '';

        $.get("code/value.php",
        {
            ID:user,
            amount:amount,
            result:result

        },function(query)
        {
            alert(query);
        });
    });

});

您可以使用https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/parseFloathttps://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt将值转换为JS中的整数/浮点数。