简体   繁体   English

无法使用php从表单将数据插入MYSQL

[英]Can't insert data into MYSQL from form using php

I want to insert data into MYSQL from HTML form using PHP .When i enter a valid string in the form and submit it redirect as per code to main.php btw the entered string is not inserted into MYSQL table. 我想使用PHP将数据从HTML表单插入MYSQL中。当我在表单中输入有效字符串并将其提交后,按照代码重定向到main.php,顺便说一句,输入的字符串未插入MYSQL表中。

Here is my code below 这是我的下面的代码

HTML 的HTML


<form class="form" action="" method="post" >
    <input type="text" placeholder="User Id" id="userid" name="userid" title="Enter your Roll number">
    <button onclick="validate()" type="submit" id="login-button" name="formSubmit" value="submit">Login</button>

</form>

Here is the form validation. 这是表单验证。

JS JS


function validate()
{
    var id=document.getElementById('userid').value;
    if(id=="")
    {
        document.getElementById('msg').innerHTML = "Please enter User Id";
        setTimeout(function(){
        window.location.replace('index.php');
        }, 2000);
    }
    else
    {
        if(id.length=="10")
        {
            document.getElementById('msg').innerHTML = "Login Success";
            setTimeout(function(){
            window.location.replace('main.php');
            }, 2000);
        }
        else
        {   
            document.getElementById('msg').innerHTML = "Please enter valid User Id";
            setTimeout(function(){
            window.location.replace('index.php');
            }, 2000);
        }
    }
}

PHP 的PHP


mysql_connect("localhost", "root", "password") or die(mysql_error());
mysql_select_db("gcet_elib") or die(mysql_error());

if(isset($_POST['formSubmit']))
{

    $userid = $_POST['userid'];

    $query = "INSERT INTO users ( uid ) VALUES ('$userid')";

    $result = mysql_query($query);

    if($result){
        //$msg = "User Created Successfully.";

        echo '<script language="javascript">';
        echo 'alert("Login Successfull")';
        echo '</script>';

    }

else
{
    echo '<script language="javascript">';
    echo 'alert("Cant submit this form")';
    echo '</script>';
}

} }


这是MYSQL表结构


So please help me to find out the mistake in the code. 因此,请帮助我找出代码中的错误。

When I run this code it alerts like this "Cant submit this form" . 当我运行此代码时,它会发出类似“无法提交此表单”的警报。

it might be because your form requirements are not met which is to be met as defined in the validate() fucntion. 可能是因为未满足validate()功能中定义的表单要求。 check your javascript validate() function. 检查您的javascript validate()函数。 It might be wrong. 可能是错误的。 So post it as edit, or may be you are not passing the required information to the input fields which is required for validate() to be true. 因此,将其发布为编辑,或者可能是您没有将所需信息传递给validate()为true所必需的输入字段。

mysql or php is not the problem right now as your form is not even submitted. mysql或php现在不是问题,因为您的表单甚至都没有提交。

your script might be wrong check this see the comments i have put and give a thinking. 您的脚本可能是错误的,请检查此内容以查看我提出的意见并进行思考。

function validate()
        {
            var id=document.getElementById('userid').value;
            //if id is null this will rise
            if(id=="")
            {
                document.getElementById('msg').innerHTML = "Please enter User Id";
                setTimeout(function(){
                window.location.replace('index.php');
                }, 2000);
            }
            //if the id is not null this means a string is passed
            else
            {
                //if the id is exactly 10 characters long
                if(id.length=="10")
                {
                    document.getElementById('msg').innerHTML = "Login Success";
                    setTimeout(function(){
                    window.location.replace('main.php');
                    }, 2000);
                }
                //if the id is not null and character length is not equal to 10
                else
                {   
                    document.getElementById('msg').innerHTML = "Please enter valid User Id";
                    setTimeout(function(){
                    window.location.replace('index.php');
                    }, 2000);
                }
            }
        }

In this case if the id is not null or null it will redirect window.location.replace('index.php'); 在这种情况下,如果id不为null或null,它将重定向window.location.replace('index.php'); to index.php all the time which is btw meaning even if a string is passed to it or not it will refresh. 始终索引index.php,这是btw的意思,即使是否将字符串传递给它,它也会刷新。 So correct these conditional statements as you prefer to make it work 因此,请根据需要更正这些条件语句,以使其起作用

If you are seeing that error on load, its normal, because you didn't set a $_POST['formSubmit'] so that if loop will redirect to else and error will be shown. 如果在加载时看到该错误,那是正常现象,因为您没有设置$_POST['formSubmit']因此if循环将重定向到else并显示错误。

On loading page, you don't have a post variable set, but the php part will execute and it will find isset($_POST['formSubmit']) as false , and it will go else statement. 在加载页面上,您没有设置post变量,但是php部分将执行,它将发现isset($_POST['formSubmit'])false ,它将进入else语句。

Make the following changes. 进行以下更改。

  1. In JS, do all the validations and let JS submit the form. 在JS中,进行所有验证,然后让JS提交表单。
  2. Make complete php code inside if(isset($_POST['formSubmit']), so that php code will execute only after the submit done. 在if(isset($ _ POST ['formSubmit']))中制作完整的php代码,以便仅在提交完成后执行php代码。

Replace your html with following: 用以下内容替换您的html:

 <form class="form" action="main.php" method="post"> <input type="text" placeholder="User Id" id="userid" name="userid" title="Enter your Roll number"> <button onclick="return validate()" type="submit" id="login-button" name="formSubmit" value="submit">Login</button> </form> 

Replace you javascript with following: 将您的JavaScript替换为以下内容:

 function validate() { var id = document.getElementById('userid').value; if (id == "") { document.getElementById('msg').innerHTML = "Please enter User Id"; return false; } else { if (id.length == "10") { document.getElementById('msg').innerHTML = "Login Success"; return true; } else { document.getElementById('msg').innerHTML = "Please enter valid User Id"; return false; } } } 

Change your php code a bit like below : 更改您的php代码,如下所示:

mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("stackov") or die(mysql_error());

if(isset($_POST['formSubmit']))
      {

        $userid = $_POST['userid'];

        $query = "INSERT INTO users ( id ) VALUES ('$userid')";

        $result = mysql_query($query);

        if($result){
            //$msg = "User Created Successfully.";

            echo '<script language="javascript">';
            echo 'alert("Login Successfull")';
            echo '</script>';

        }
        else{
          echo '<script language="javascript">';
            echo 'alert("Cant submit this form")';
            echo '</script>';
      }
      }

I have just changed the postion of else block so the message cant submit form will not pop up. 我刚刚更改了else块的位置,因此无法弹出无法提交表单的消息。

if you want no error when page loading, change PHP file as: 如果您希望在页面加载时没有错误,请将PHP文件更改为:

<?php
  mysql_connect("localhost", "root", "root") or die(mysql_error());
  mysql_select_db("stackov") or die(mysql_error());

  if(isset($_POST['formSubmit']))
  {

    $userid = $_POST['userid'];

    $query = "INSERT INTO users ( uid ) VALUES ('$userid')";

    $result = mysql_query($query);

    if($result){
        //$msg = "User Created Successfully.";

        echo '<script language="javascript">';
        echo 'alert("Login Successfull")';
        echo '</script>';

    }
    else{
        echo '<script language="javascript">';
        echo 'alert("Cant submit this form")';
        echo '</script>';
    }
  }
?>

Move else statement on check isset($_POST) 在check isset($ _ POST)上移动else语句

You are just redirecting and changing window location . 您只是重定向和更改窗口位置。 you need to submit form . 您需要提交表格。 you need to provide action as action="main.php" and in validation if you field is not empty or correct according to your validation just use this $( "#formid" ).submit(); 您需要以action="main.php"提供操作,如果您的字段不为空或根据验证正确,则需要在验证中使用此$( "#formid" ).submit(); jquery function.You form will be submitted and and you will be able to access post values in main.php jQuery函数。您将提交表单,并且可以访问main.php中的帖子值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM