通过ajax将变量发布到mysql db - phonegap

时间:2015-06-26 11:30:55

标签: php mysql ajax cordova

我只想将一个简单的变量从我的phonegap应用程序发布到mysql数据库。但它不起作用。 db显示空结果。

Mysql数据库看起来像这样,Tablename是user

行:

user (varchar 25),vip (varchar 1),call (varchar 1)

在我的项目顶部插入:

            <script type="text/javascript" src="js/tcPlugin.js"></script>
            <script type="text/javascript" src="js/phoneApp.js"></script>
            <script type="text/javascript" src="js/start.js"></script>

start.js是我的ajax请求文件 - 其他两个工作正常,所以我猜没有问题

我的start.js文件如下所示:

$(document).ready( function() {
                  var email = "john@web.de"; 

                  $.ajax({
                         type: 'post',
                         url: 'http://www.blablabla.de/phone/action.php',
                         data: {
                         data: {"email" : email },
                         //data:email,
                         },
                         success: function(result) {
                         console.log(result);
                         }
                         });

我的action.php看起来像这样:

<?php
        $dbhost = "bla";
        $dbuser = "bla";
        $dbpass = "bla";
        $dbname = "bla";



$user = $_POST['data']['email'];

$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "INSERT INTO user (email)
VALUES ('" . $user . "')";


if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

?>

但是每次启动应用程序时,db都是空的。调试器concole没有给我任何错误。数据库连接正在运行,尝试使用echo连接结果。其他js工作正常。

1 个答案:

答案 0 :(得分:0)

action.php的

<?php
        $dbhost = "bla";
        $dbuser = "bla";
        $dbpass = "bla";
        $dbname = "bla";

print_r($_POST); // see full contents of the POST

$user = $_POST['data']['email'];

print PHP_EOL . $user . PHP_EOL; // see full contents of the $user var

$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "INSERT INTO user (email) VALUES ('" . $user . "')";

print PHP_EOL . $sql . PHP_EOL; // see the actual sql query, you can test this later in your sql editor ex. phpmyadmin


if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();

?>

进行这些编辑,运行ajax并检查调试器中的响应选项卡。