无法将表单数据传递给数据库(PHP,Jquery)

时间:2017-10-05 15:23:48

标签: javascript php jquery mysql

修改

我已经实施了建议的更改,但我仍然无法让它工作:

表单页面跟随(login.php)

<?php
   $mac=$_POST['mac'];
   $ip=$_POST['ip'];
   $username=$_POST['username'];
   $linklogin=$_POST['link-login'];
   $linkorig=$_POST['link-orig'];
   $error=$_POST['error'];
   $chapid=$_POST['chap-id'];
   $chapchallenge=$_POST['chap-challenge'];
   $linkloginonly=$_POST['link-login-only'];
   $linkorigesc=$_POST['link-orig-esc'];
   $macesc=$_POST['mac-esc'];
if (isset($_POST['postcode'])) {
    $postcode = $_POST['postcode'];
}
if (isset($_POST['email'])) {
    $email = $_POST['email'];
}
?>

**SOME HTML HERE**


<script src="jquery-3.2.1.min.js"></script>

<script>

var js-postcode = document.login.getElementsByName("postcode").value;
var js-email = document.login.getElementsByName("email").value;
var formdata = {postcode:js-postcode,email:js-email};

        $("button").click(function(){
                $.ajax(
                {
                type: "POST",
                url: "database.php", //Should probably echo true or false depending if it could do it
                data : formdata,
                success: function(feed) {
                  if (feed!="true") {
                     // DO STUFF
                  } else {
                    console.log(feed);
                     // WARNING THAT IT WASN'T DONE
                  }
                }}}

</script>

</head>

<body>

<table width="100%" style="margin-top: 10%;">
        <tr>
        <td align="center" valign="middle">
        <table width="240" height="240" style="border: 1px solid #cccccc; padding: 0px;" cellpadding="0" cellspacing="0">
        <tr>
        <td align="center" valign="bottom" height="175" colspan="2">
<!-- removed $(if chap-id) $(endif)  around OnSubmit -->
                <form name="login" action="<?php echo $linkloginonly; ?>" method="post" onSubmit="return doLogin()" >
                        <input type="hidden" name="dst" value="<?php echo $linkorig; ?>" />
                        <input type="hidden" name="popup" value="true" />

                        <table width="100" style="background-color: #ffffff">
                                <tr><td align="right">login</td>
                                <td><input style="width: 80px" name="username" type="text" value="<?php echo $username; ?>"/></td>
                                </tr>
                                <tr><td align="right">password</td>
                                <td><input style="width: 80px" name="password" type="password"/></td>
                                </tr>
                                <tr><td align="right">Postcode</td>
                                <td><input style="width: 80px" name="postcode" type="text" /></td>
                                </tr>
                                <tr><td align="right">Email</td>
                                <td><input style="width: 80px" name="email" type="text" /></td>
                                </tr>
                                <td><button><input type="submit" value="OK" /></button></td>
                                </tr>
                        </table>
                </form>
        </td>
        </tr>
        </table>

        </td>
        </tr>
</table>

<script type="text/javascript">
<!--
  document.login.username.focus();
//-->
</script>
</body>
</html>

并调用文件database.php如下:

<?php 

if ((isset($_POST['postcode'])) && (isset($_POST['email']))) {

   $postcode = $_POST['postcode'];
   $email = $_POST['email'];

  $connect= new mysqli_connect('xx','xx','xx','xx');


  if ($conn->connect_errno) {
    echo "There was a problem connecting to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
  }

  if (!($sql = $conn->prepare("INSERT INTO visitors(postcode,email) VALUES(postcode,email)"))) {
    echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
  }

  //NOTE: the "ss" part means that $postcode and $email are strings (mysql is expecting datatypes of strings). For example, if $postcode is an integer, you would do "is" instead.

  if (!$sql->bind_param("ss", $postcode, $email)) {
    echo "Binding parameters failed: (" . $sql->errno . ") " . $sql->error;
  } 


  if (!$sql->execute()) {
    echo "Execute failed: (" . $sql->errno . ") " . $sql->error;

  } 


} else {

  echo 'Variables did not send through ajax.'; // any echoed values would be sent back to javascript and stored in the 'response' variable of your success or fail functions for testing.

}

?>

我仍然没有从表单到数据库的任何东西。即使我将变量换成字符串,我也没有得到任何数据库,但是如果我单独运行database.php就可以了。当然,我现在接近让这个工作了......任何帮助表示感谢,并非常感谢迄今为止所提供的帮助。

*******************************原始问题如下***************** **

我有一个简单的表格如下:

       <form name="login" action="somethingelse.php" method="post" onSubmit="return doLogin()" >
                <input type="hidden" name="dst" value="<?php echo $linkorig; ?>" />
                <input type="hidden" name="popup" value="true" />

                <table width="100" style="background-color: #ffffff">
                        <tr><td align="right">login</td>
                        <td><input style="width: 80px" name="username" type="text" value="<?php e$
                        </tr>
                        <tr><td align="right">password</td>
                        <td><input style="width: 80px" name="password" type="password"/></td>
                        </tr>
                        <tr><td align="right">Postcode</td>
                        <td><input style="width: 80px" name="postcode" type="text" /></td>
                        </tr>
                        <tr><td align="right">Email</td>
                        <td><input style="width: 80px" name="email" type="text" /></td>
                        </tr>
                        <td><button><input type="submit" value="OK" /></button></td>
                        </tr>
                </table>
        </form>

因为我需要使用表单操作来执行其他操作,所以我需要在单击按钮时使用jQuery将数据发送到数据库。特别是从表单中获取的邮政编码和电子邮件地址。与jQuery相关的代码部分如下所示:

<script  language="JavaScript" >

$(document).ready(function(){
    $("button").click(function(){

mysqli_query();

});
});
</script>

调用函数mysqli_query是通过include语句声明的,因此它位于不同的文件中。调用的函数如下所示:

mysqli_query( $connect, "INSERT INTO visitors(postcode,email) VALUES(postcode,email)");

我已经绕圈了好几天了。我知道我接近使其工作,但不能跨越终点线。有人可以指出我在这里做错了吗?

4 个答案:

答案 0 :(得分:3)

警告: 从不信任用户输入始终清理输入首先使用预准备语句否则,你让自己容易受到 SQL INJECTION ATTACKS

的攻击

你正在混淆,Javascript是一种客户端语言,而mysqli是基于PHP的功能在服务器端。

你应该做的是ajax调用,使用不同PHP文件的值来建立数据库连接并插入数据。

var dataString = "postcode="+ postcode+"&email="+email;
$.ajax({
type: "POST",
url: "file_that_does_the_work.php", //Should probably echo true or false depending if it could do it
data: dataString,
success: function(feed) {
  if (feed=="true") {
     // DO STUFF
  } else {
    console.log(feed);
     // WARNING THAT IT WASN'T DONE
  }
}

file_that_does_the_work.php

<?
include("config.php"); // your thing that configures the connection
$postcode = sanitizationfunction($_POST["postcode"]);
$email = sanitizationfunction($_POST["email"]);
$query = $connection->prepare('INSERT INTO visitors(postcode,email) VALUES(?,?)');
$query->bindParam(1, $postcode);
$query->bindParam(2, $email);
if ($query->execute()) {
  echo "true";
} else {
  echo "false";
}
?>

答案 1 :(得分:1)

<强> form.php的

<table width="100" style="background-color: #ffffff">
        <tr><td align="right">login</td>
        <td><input style="width: 80px" name="username" type="text" value="<?php echo $username?>"/>
        </tr>
        <tr><td align="right">password</td>
        <td><input style="width: 80px" name="password" type="password"/></td>
        </tr>
        <tr><td align="right">Postcode</td>
        <td><input style="width: 80px" name="postcode" type="text" /></td>
        </tr>
        <tr><td align="right">Email</td>
        <td><input style="width: 80px" name="email" type="text" /></td>
        </tr>
        <td><input type="submit" value="OK" /></td>
        </tr>
</table>
</form>

`

<强> somethingelse.php

<?php foreach ($_POST as $key => $value) { echo $key."=".$value."<br/>"; } ?>

我将连接部分留给您:D

答案 2 :(得分:1)

因此,正如其他人所指出的那样,您正在混淆客户端代码和服务器端代码。您需要将所有表单数据发送到php文件。 jquery ajax将数据发送到脚本,并确定此调用是否成功。如果调用不成功,则可以运行测试逻辑。如果是,则可以执行其他逻辑,例如提醒用户提交成功表单。

以下是该过程的一个示例:

AJAX:

<script>

  var formData = 'some data' // Get your form values and save here - postcode and email

  $("button").click(function(){
    $.ajax ({
        method: 'POST',// you can do either post or get...
        url: "page_to_handle_mysql_code.php",
        data: formData
        success: function( response ) {
           //do something like alert("Submitted Successfully!");
        }
        fail: function( response) {
          //Do testing such as console.log(response); NOTE: Response will be what ever your php page sends back.
        }

      });
  )};

</script>

在您的php页面上:page_to_handle_mysql_code.php

<?php 

if ((isset($_POST['postcode'])) && (isset($_POST['email']))) {

   $postcode = $_POST['postcode'];
   $email = $_POST['email'];

  //connect to mysql - I prefer prepared statements as the variables are prepared for safety when sent to MySQL

  $conn = new mysqli($servername, $username, $password, $dbname);//you can either put the actually values in, or I include another php page in this one that sets my variables so I can resuse my code easily.


  if ($conn->connect_errno) {
    echo "There was a problem connecting to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
  }

  if (!($sql = $conn->prepare("INSERT INTO visitors(postcode,email) VALUES(?,?)"))) {
    echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
  }

  //NOTE: the "ss" part means that $postcode and $email are strings (mysql is expecting datatypes of strings). For example, if $postcode is an integer, you would do "is" instead.

  if (!$sql->bind_param("ss", $postcode, $email)) {
    echo "Binding parameters failed: (" . $sql->errno . ") " . $sql->error;
  } 


  if (!$sql->execute()) {
    echo "Execute failed: (" . $sql->errno . ") " . $sql->error;

  } 


} else {

  echo 'Variables did not send through ajax.'; // any echoed values would be sent back to javascript and stored in the 'response' variable of your success or fail functions for testing.

}

?>

这可以帮助您将值输入MySQL。我希望它有所帮助!

答案 3 :(得分:-1)

您可以使用jquery

提交表单

nodes是PHP中的一个函数,您的javascript无法访问该函数。你必须从你的PHP发出一个http调用,你的PHP将收到它并在其末尾运行mysqli_query