使用PHP和AJAX更新MySQL数据库

时间:2015-12-12 11:56:22

标签: php jquery mysql ajax

我最近创建了一个Web项目。我想通过ajax和PHP更新mysql查询。我创建了代码但是我遇到了问题。我的服务器使用PHP 5.2 *。当我按下按钮更新数据库时,有时没有任何反应,有时我会收到数据库错误。我不确切地知道问题出在哪里,因为这是我第一次在后端开发工作,所以任何帮助都会受到赞赏!

    --------------------HOME.JS--------------------
 $('#update_profile').click(function(e) {
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: 'lib/preferences.php',
            data: {
                email: $('#pref-changes input[name="email"]').val(),
                pass: $('#pref-changes input[name="pass"]').val(),
                username, $('#pref-changes input[name="username"]').val(),

            },
            dataType: "html",
            success: function(data){
                    window.location.href = data;
                }
        });
});


--------------------HOME.HTML--------------------
<form class="pref-changes" id="pref-changes">
        <div class="pref_avatar">
           <div class="avatar_change">Change</div>
        </div> 

        <div style="margin-top: 10px;">
           <label>Change Username</label>
           <input name="username" class="pref_inp" placeholder="GeorgeGkas" type="text">
        </div>

        <div class="lbl">
           <label>Change Email</label>
           <input name="email" class="pref_inp" placeholder="georgegkas@gmail.com" type="email">
        </div>

        <div class="lbl">
           <label>Change Password</label>
           <input name="pass" class="pref_inp" placeholder="Password" type="password">
        </div>

        <div class="update_btn">
          <button type="submit" id="update_profile" name="update_profile">Update</button>
        </div>

</form>


 --------------------PREFERENCES.PHP--------------------
<?php
  session_start();

    define("DB_HOST", 'mysql6.000webhost.com');
    define("DB_USER", '');
    define("DB_PASSWORD", '');
    define("DB_DATABSE", '');
    $UserEmail = $_SESSION['login'];
    $conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
    mysql_select_db(DB_DATABSE, $conn);

    if ($email != "") {
      $sql = "UPDATE Users SET UserEmail='".$email."' WHERE UserEmail=".$UserEmail."";
      mysql_query($conn, $sql);
    }

    if ($pass != "") {
      $sql = "UPDATE Users SET UserPass='".$pass."' WHERE UserEmail=".$UserEmail."";
      mysql_query($conn, $sql);
    }

    if ($username != "") {
      $sql = "UPDATE Users SET UserName='".$username."' WHERE UserEmail=".$UserEmail."";
      mysql_query($conn, $sql);
    }

    $host  = $_SERVER['HTTP_HOST'];
    $link = "http://$host/home.php";
    echo $link;
?> 

1 个答案:

答案 0 :(得分:1)

在您的PHP代码中,您是否定义了$email$pass$username? 也许在你检查它们是否与“”

不同之前你需要这个
$email = $_POST["email"];
$pass = $_POST["pass"];
$username = $_POST["username"];