【问题标题】:mySQL php AJAX data not inserting from AJAX js filemySQL php AJAX 数据未从 AJAX js 文件插入
【发布时间】:2011-10-31 14:34:16
【问题描述】:

尝试在我的网站上创建评论应用程序。 尽管数据“发布”到 AJAX JavaScript 文件,但数据未正确插入。 这是主页:http://micromedia.vaniercollege.qc.ca/home/nortonb/php/

作品:

您可以使用已注册的用户插入评论:sn@dot.com 密码:sn (注意:alert 来自 js/ajax.js)

  • 在主页上包含 db/cmets.php 以显示 cmets
  • 包含到 js/ajax.js 文件中
  • 在提交时通过 ajax.js 文件将信息传递给 comment_ins.php

    <input name="submit" type="button" class="indent" value="add your comment" onclick="loadXMLDoc('db/comments_ins.php')">

不起作用:

如果数据库中不存在用户的电子邮件,comment_ins.php 会显示另一个包含名字和姓氏输入的表单。

这使用相同的 ajax.js 文件,但现在使用 db/cmets_add_user.php 插入新用户,然后在相关表中插入他们的评论。

(注意:参数是传给ajax.js文件的,但是信息没有提交到数据库中)

我尝试过: - 对 db/cmets_add_user.php 中的数据进行硬编码工作

-从常规表单传递信息但仍然使用 js/ajax.js 有效

http://micromedia.vaniercollege.qc.ca/home/nortonb/php/c_test.htm

提前致谢。 布鲁斯

这是我的 index.php 文件的内容:

<h4>Comments</h4>
    <article id="comms">

    <form name="intro" action="" method="post">
        <fieldset> 
            <legend>Add your comment</legend> 
            <label for="comment">
                Comments:<br /><textarea name="comment" id="comment" cols="30" rows="5" class="indent"></textarea><br /> 
            </label>   
            <label for="email">
                Email:<br /><input name="email" id="email" type="text" size="32" class="indent"/>
                <span id="emailMessage"></span>
            </label><br />

            <label for="password">
                Password:<br /><input name="password" id="password" type="password" size="32" class="indent"/>
                <span id="passwordMessage"></span>
            </label><br />

                <input name="submit" type="button" class="indent" value="add your comment" onclick="loadXMLDoc('db/comments_ins.php')">

        </fieldset> 
    </form> 
    <?php include("db/comments.php"); ?>

    </article>

这里是 js/ajax.js 文件:

// JavaScript Document
function loadXMLDoc(xmlDoc){
    var xmlhttp;
    if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
    }else{// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200){
            document.getElementById("comms").innerHTML=xmlhttp.responseText;
        }
    }


    var commentValue=encodeURIComponent(document.getElementById("comment").value);
    var emailValue=encodeURIComponent(document.getElementById("email").value);
    var passwordValue=encodeURIComponent(document.getElementById("password").value);

    var parameters="comment="+commentValue+"&email="+emailValue+"&password="+passwordValue;
    //if a new user then add these things
    if(document.getElementById("firstName")){ 
        var firstNameValue=encodeURIComponent(document.getElementById("firstName").value);
        var lastNameValue=encodeURIComponent(document.getElementById("lastName").value);
        //parameters are formatted in name=value pairs
        var parameters="firstName="+firstNameValue+"&lastName="+lastNameValue+"&comment="+commentValue+"&email="+emailValue+"&password="+passwordValue;

    }
    alert(xmlDoc + " parameters: "+parameters);
    xmlhttp.open("POST", xmlDoc, true);//true = asynchronous
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.send(parameters);

}

这是 db/cmets_ins.php(看起来工作正常)

<?php
    //comments_ins.php adds new comments to the database
    //if the user has already registered, the comment is displayed
    //else a form is displayed for new users keeping the comment and email from the original comment form

    //to do list:
    // ??? should I combine this into comments.php?
    // ??? should I separate the forms into a separate .php file with a conditional for new users?
    //fix scrolling issue? 
    //jQuery? AJAX?
    include  'includes/mysqli_connect.php';
    //get the posted info
    echo("comments_ins.php<br />");
    if(isset($_POST["comment"])){
        $password = trim($_POST["password"]);
        $hashedPassword = hash(sha256,$password);
        $email = trim($_POST["email"]);
        $comment = trim($_POST["comment"]);
        //see if user exists
        $query = "select * from users where email = '$email' and password = '$hashedPassword' limit 1";//adding limit 1 speeds up the query on big tables
        $result = mysqli_query($link, $query);
        //get response from database    
        if($result = mysqli_query($link, $query)){
            $numrows = $result->num_rows;
            //echo ('found '.$numrows.' user: <br>'. $firstName.'<br>');
            while ($row = $result->fetch_object()) {    
                $userArray[] = array('userID'=>$row->userID,
                    'firstName'=>$row->firstName, 
                    'lastName'=>$row->lastName,
                    'email'=>$row->email
                );//line breaks for readability
            }
            $verifiedUserID = $userArray[0]['userID'];//get userID for insert below
            //echo("\$verifiedUserID: ".$verifiedUserID);
        }else{
            // This means the query failed
            echo("errr...");
            echo $mysqli->error;
        } 

        //if the user already exists...
        if($numrows > 0){//should add something if numrows > 1 i.e. for duplicate users!!
            //echo("user is registered <br />");
            $commentQuery="INSERT INTO comments (comment, userID) VALUES ('$comment', '$verifiedUserID')";
            $commentResult = mysqli_query($link, $commentQuery);
            //get response from database
            $commentNum =  mysqli_affected_rows($link);
            echo(mysqli_error());
            //echo ('<br />inserted '.$commentNum.' record: <br />'. $comment.'<br />');
            include("comments.php");
        }else{//if the user does not exist
            echo("Please register to display your comment: <br />");
            ?>
            <form name="intro" action="" method="post">
                <fieldset> 
                    <legend>Register to share your comment:</legend> 
                      <label for="firstName">
                        First Name: <br />
                        <input name="firstName" id="firstName" type="text" class="indent" size="32" />
                        <span id="firstMessage"></span>
                      </label>
                      <br /> 
                      <label for="lastName">
                        Last Name:<br />
                        <input name="lastName" id="lastName" type="text" class="indent" size="32" />
                        <span id="lastMessage"></span>
                      </label>
                      <br />  
                      <label for="email">
                        Email:<br />
                        <input name="email" id="email" type="text" size="32" class="indent" value="<?php echo($email); ?>"/>
                        <span id="emailMessage"></span>
                      </label>
                      <br />
                      </label>
                      <label for="password">
                        Password:<br />
                        <input name="password" id="password" type="password" size="32" class="indent"/>
                        <span id="passwordMessage"></span>
                      </label>
                      <br />
                      <label for="comment">
                        Edit your comment?<br />
                        <textarea name="comment" id="comment" cols="30" rows="5" class="indent"><?php echo($comment); ?></textarea>
                      </label> <br /> 
                      <input name="submit" type="submit" class="indent" value="join us" onclick="loadXMLDoc('db/comments_add_user.php')"/>
                    <p class="note">(Of course we will keep your stuff private!!)</p>
                </fieldset> 
            </form> 
        <?php   
        }//end else($numrows <=0)

        //close connection
        mysql_close($link);
    }
    ?>

这里是 cmets_add_user.php 文件(从 js/ajax.js 文件调用时不起作用,但从调用时起作用

<?php
    include  'includes/mysqli_connect.php';
    //get the posted info
    echo("hi mom");
    $firstName = $_POST["firstName"];//"Two";//
    $lastName = $_POST["lastName"];//"Two";//
    $password = $_POST["password"];//"Two";//
    $hashedPassword = hash(sha256,$password);
    $email = $_POST["email"];//"Two";//
    $comment = $_POST["comment"];//"Two";//
    echo($firstName." from comments_add_user.php<br>");

    //since email does not exist, 
        $query="INSERT INTO users (firstName, lastName, password, email) VALUES ('$firstName', '$lastName', '$hashedPassword', '$email')";
        $result=mysqli_query($link, $query);
        //get response from database
        $num=  mysqli_affected_rows($link);
        echo(mysqli_error());
        echo ('inserted '.$num.' record: <br>'. $firstName.'<br>');
    //** add error checking ?!?

    //get the userID for the new user
        $userQuery = "select userID from users where email = '$email' limit 1";//adding limit 1 speeds up the query on big tables
        $userResult = mysqli_query($link, $userQuery);

        //get response from database    
        if($userResult = mysqli_query($link, $userQuery)){
            $numrows = $userResult->num_rows;
            echo ('found '.$numrows.' user: <br>'. $firstName.'<br>');
            while ($row = $userResult->fetch_object()) {
                $userArray[] = array('userID'=>$row->userID);//line breaks for readability
            }
            $newUserID = $userArray[0]['userID'];//get userID for insert below
            //echo("\$verifiedUserID: ".$verifiedUserID);
        }else{
            // This means the query failed
            echo("errr...");
            echo $mysqli->error;
        } 

    //now insert the comment
        $commentQuery="INSERT INTO comments (comment, userID) VALUES ('$comment', '$newUserID')";
        $commentResult=mysqli_query($link, $commentQuery);
        //get response from database
        $commentNum=  mysqli_affected_rows($link);
        echo(mysqli_error());
        echo ('inserted '.$commentNum.' record: <br>'. $comment.'<br>');


    echo('<br><a href="comments_display.php">display all comments</a><br />');
    //close connection
    mysql_close($link);

    ?>

【问题讨论】:

  • 你已经找到了很好的 SQL 注入孔......如果有人开着卡车穿过它们进入你的服务器,那就太可惜了。
  • 谢谢 Mark B。我知道我应该在发帖之前把它们塞进去。
  • 没有卡车了。添加了一些削减和剥离。一旦我得到这个工作,计划添加准备好的语句。再次感谢马克 B。

标签: php mysql ajax


【解决方案1】:

我有点不明白你现在的问题出在哪里

所以可能需要你帮我回顾一下,这样我才能帮助你..

除此之外,我注意到你有&lt;form name="intro" action="" method="post"&gt;

我只是想确保你没看错,action="" 表示实际上指向 index.php 而不是 db/cmets_ins.php

我不知道这是否是你真正想要发生的事情......

编辑:我知道发生了什么,您单击添加评论,出现注册表单,您单击加入我们,它确实调用了 AJAX,但随后页面被刷新,因为 &lt;input&gt; 的类型为 submit,这意味着这单击它时提交表单 所以这会让你的页面重新加载......你需要将comment_ins.php中的那一行更改为:

<input name="submit" type="button" class="indent" value="join us" onclick="loadXMLDoc('db/comments_add_user.php')"/>

在我进行了更改之后,我正在从添加用户文件中获取输出...

【讨论】:

  • 谢谢@DanyKhalife 问题是当我尝试注册用户时 AJAX 不起作用。如果电子邮件(和密码)不存在或不匹配,则由 db/cmets_ins.php 创建新表单。您是对的:action="" 指向 index.php(或在本例中为 database.php 文件)。通过以下方式 $_POST 信息是 onClick 事件:onclick="loadXMLDoc('db/cmets_ins.php')
  • 所以你的注册表出现了,但是当用户点击“加入我们”时没有任何反应?编辑:好的,我明白了,我会把它加载到我的服务器上为你调试它..
  • 好的,我更新了我的答案,如果这能解决您的问题,请告诉我,如果解决了,请投票:)
  • 是啊!!! @Dany,非常感谢。用罗伯托·德·维琴佐(Roberto De Vicenzo)的不朽名言……“我真是个愚蠢的人!” (ps。还不能投票...没有足够的代表)
  • 疯了......这是一个小世界。现在我有更多的 cmets ......我的代表 > 15 我可以投票并接受答案。另外,我已将所有 php 脚本更新为 OOP 样式和准备好的语句。
猜你喜欢
  • 2011-07-05
  • 2014-11-26
  • 2016-12-12
  • 2013-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-21
相关资源
最近更新 更多