将HTML表单中的输入数据插入JSON对象,然后将其存储在MYSQL中

时间:2022-05-29 17:11:08

I am trying to get the data from user registration form in HTML and then push the data to JSON and then get the JSON and store into MySQL. Please help me.

我试图从HTML中获取用户注册表单中的数据,然后将数据推送到JSON,然后获取JSON并存储到MySQL中。请帮我。

HTML

    <form id="myForm" action="userInfo.php" method="post">
        <table align="center">
            <tr>
                <td><label for="FirstNameLabel" class="tableproperties">First Name</label></td>
                <td><input type="text" class="signupTextBoxStyle" name="firstName" placeholder="Enter First Name" id="FirstNameBox" required/></td>
            </tr>
            <tr>
                <td><label for="LastNameLabel" class="tableproperties">Last Name</label></td>
                <td><input type="text" name="lastName" placeholder="Enter Last Name" id="LastNameBox" class="signupTextBoxStyle" required></td>
            </tr>
        <tr>
            <td><label for="eMailLabel" class="tableproperties">Email</label></td>
            <td><input type="email" name="email" placeholder="Enter Email" id="eMailBox" class="signupTextBoxStyle" required></td>
            <td id="emailStatus"></td>
        </tr>

        <tr>
            <td><label for="passwordLabel" class="tableproperties">Password</label></td>
            <td><input type="password" name="password" placeholder="Enter Password" id="passwordTextbox" maxlength="24" class="signupTextBoxStyle" required></td>
            <td><i class="fa fa-info-circle infoIcon" title="Password must contain minimum 3 upper case, 2 lower case and 2 special chars"></i></td>
            <td><progress value="0" max="100" class="progressBar" id="progressStatus"></progress></td>
            <td id="passwordStrength"></td>
        </tr>

        <tr>
            <td><label for="confirmPasswordLabel" class="tableproperties">Confirm Password</label></td>
            <td><input type="password" name="confirmpassword" placeholder="Must be same as password" maxlength="24" id="confirmPasswordBox" class="signupTextBoxStyle" required></td>
            <td id="passwordMismatch"></td>
        </tr>

        <tr>
            <td><label for="dobLabel" class="tableproperties">D.O.B</label></td>
            <td><input type="date" name="dob" placeholder="Enter D.O.B" id="dobBox" class="signupTextBoxStyle" required></td>
        </tr>

        <tr>
            <td><label for="dobTimeLabel" class="tableproperties">D.O.B with time</label></td>
            <td><input type="datetime" name="dobTime" placeholder="Enter D.O.B with time" id="dobTimeBox" class="signupTextBoxStyle" required></td>
        </tr>

        <tr>
            <td><label for="localDOBLabel" class="tableproperties">Local D.O.B</label></td>
            <td><input type="datetime-local" name="localdob" placeholder="Enter Local D.O.B" id="localDobBox" class="signupTextBoxStyle" required></td>
        </tr>

        <tr>
            <td><label for="ssnLabel" class="tableproperties">SSN</label></td>
            <td><input type="text" name="ssn" placeholder="000-00-0000" id="ssnBox" class="signupTextBoxStyle" required pattern="^(\d{3}-\d{2}-\d{4})$"></td>
        </tr>

        <tr>
            <td><label for="usPhoneNumber" class="tableproperties" >US Phone Number</label></td>
            <td><input type="text" name="phone" placeholder="000-000-0000" id="usNumberBox" class="signupTextBoxStyle" required></td>
            <td id="phoneStatus"></td>
        </tr>

        <tr>
            <td><label for="creditLabel" class="tableproperties" id="CreditText">Credit Card Number</label></td>
            <td><input type="text" name="creditCardNumber" placeholder="Enter Credit Card Number" id="creditBox" class="signupTextBoxStyle" required pattern="^[0-9]{12}(?:[0-9]{4})?$"></td>
        </tr>


        <tr>
            <td colspan='2'>
                <input type="submit" class="btn btn-primary btn-lg btn-block signupbuttonStyle" id="sub" />
                <button type="button" class="btn btn-danger btn-lg btn-block signupbuttonStyle" onclick="location.href = 'index.html';">Cancel</button>
            </td>
        </tr>
        </table>
    </form>

PHP(Just to test Data is getting saved to mySQL if i manually enter the data)

PHP(如果我手动输入数据,只是测试数据会保存到mySQL)

$json_obj = '{
      "jsonFirstName": "Kishan",
      "jsonLastName": "Kishan",
      "jsonEmail": "Kishan",
      "jsonPassword": "Kishan",
      "jsonDob": "Kishan",
      "jsonDobTime": "Kishan",
      "jsonLocaldob": "Kishan",
      "jsonSsn": "Kishan",
      "jsonPhonenumber": "Kishan",
      "jsonCreditcardnumber": "Kishan"
 }';

PHP(Error if i want to get the values from the form)

PHP(如果我想从表单中获取值,则会出错)

$json_obj = '{
      "jsonFirstName": (string) $_POST['firstName'],
      "jsonLastName": (string) $_POST['lastName'],
      "jsonEmail": (string) $_POST['email'],
      "jsonPassword": (string) $_POST['password'],
      "jsonDob": (string) $_POST['dob'],
      "jsonDobTime": (string) $_POST['dobTime'],
      "jsonLocaldob": (string) $_POST['localdob'],
      "jsonSsn": (string) $_POST['ssn'],
      "jsonPhonenumber": (string) $_POST['phone'],
      "jsonCreditcardnumber": (string) $_POST['creditCardNumber']
 }';

Error Description
Parse error: syntax error, unexpected 'firstName' (T_STRING) in /Applications/XAMPP/xamppfiles/htdocs/xampp/297test/userInfo.php on line 19

错误说明解析错误:语法错误,第19行/Applications/XAMPP/xamppfiles/htdocs/xampp/297test/userInfo.php中的意外'firstName'(T_STRING)

REST of PHP Code
$result = json_decode($json_obj);

REST代码$ result = json_decode($ json_obj);

$firstname = $result->jsonFirstName;
$lastname = $result->jsonLastName;
$email = $result->jsonEmail;
$password = $result->jsonPassword;
$dob = $result->jsonDob;
$dobTime = $result->jsonDobTime;
$localdob = $result->jsonLocaldob;
$ssn = $result->jsonSsn;
$phonenumber = $result->jsonPhonenumber;
$creditcardnumber = $result->jsonCreditcardnumber;


if(mysql_query("INSERT INTO user VALUES('$firstname', '$lastname', '$email', '$password', '$dob', '$dobTime', '$localdob', '$ssn','$phonenumber','$creditcardnumber')")){
    echo "Successfully Inserted";
}

else
    echo "Fail to Insert";

4 个解决方案

#1


1  

Creating JSON-Strings directly through concatenation is hard because of quotes, new line characters etc.

由于引号,新行字符等,直接通过串联创建JSON字符串很难。

Instead, create an array of values and encode that into a JSON string with json_encode:

相反,创建一个值数组并使用json_encode将其编码为JSON字符串:

$values = array(
  "jsonFirstName" =>        $_POST['firstName'],
  "jsonLastName" =>         $_POST['lastName'],
  "jsonEmail" =>            $_POST['email'],
  "jsonPassword" =>         $_POST['password'],
  "jsonDob" =>              $_POST['dob'],
  "jsonDobTime" =>          $_POST['dobTime'],
  "jsonLocaldob" =>         $_POST['localdob'],
  "jsonSsn" =>              $_POST['ssn'],
  "jsonPhonenumber" =>      $_POST['phone'],
  "jsonCreditcardnumber" => $_POST['creditCardNumber']
);

$json_obj = json_encode($values);

Alternatively you can just do:

或者你可以这样做:

$json_obj = json_encode($_POST);

You will then get a JSON object with every index of $_POST. The only difference is, that you can't rename your fields as you did in your example.

然后,您将获得每个索引为$ _POST的JSON对象。唯一的区别是,您不能像在示例中那样重命名字段。

#2


0  

Not sure why you are doing it this way, however the parse error is because you are using a single quote to open the string and then also using that to pick the array index.

不知道为什么你这样做,但解析错误是因为你使用单引号打开字符串,然后使用它来选择数组索引。

Change $_POST['firstName'] to use double quotes such as $_POST["firstName"]

更改$ _POST ['firstName']以使用双引号,例如$ _POST [“firstName”]

#3


0  

EDIT: Try to do this.

编辑:尝试这样做。

$array = (
      "jsonFirstName" =>  $_POST['firstName'],
      "jsonLastName" =>  $_POST['lastName'],
      "jsonEmail" => $_POST['email'],
      "jsonPassword" => $_POST['password'],
      "jsonDob" => $_POST['dob'],
      "jsonDobTime" => $_POST['dobTime'],
      "jsonLocaldob" => $_POST['localdob'],
      "jsonSsn" => $_POST['ssn'],
      "jsonPhonenumber" => $_POST['phone'],
      "jsonCreditcardnumber" => $_POST['creditCardNumber']
 );

$json = json_encode($array);

#4


0  

You're getting an error because you are creating the JSON object out of the POST variables in a wrong way. There is indeed an issue with quotes in your statement. It should rather be something like:

您收到错误是因为您以错误的方式从POST变量中创建JSON对象。您的陈述中确实存在引号问题。它应该是这样的:

  $json_obj = '{
  "jsonFirstName": "'.(string) $_POST['firstName'].'",
  "jsonLastName": "'.(string) $_POST['lastName'].'",
  "jsonEmail": "'.(string) $_POST['email'].'",
  "jsonPassword": "'.(string) $_POST['password'].'",
  "jsonDob": "'.(string) $_POST['dob'].'",
  "jsonDobTime": "'.(string) $_POST['dobTime'].'",
  "jsonLocaldob": "'.(string) $_POST['localdob'].'",
  "jsonSsn": "'.(string) $_POST['ssn'].'",
  "jsonPhonenumber": "'.(string) $_POST['phone'].'",
  "jsonCreditcardnumber": "'.(string) $_POST['creditCardNumber'].'"
  }';

If I just include the variable without the double quotes while constructing the JSON object I get something like:

如果我在构造JSON对象时只包含没有双引号的变量,我会得到类似的结果:

  $name = "Foo";
  $json_obj = '{"firstName" :'.$name.'}'; 

 //gets expanded to $json_obj = {"firstname" : Foo}
 //Whereas it should be $json_obj = {"firstname" :"Foo"}

It was because of the missing double quotes, you could not create a JSON object in the first place and therefore when you tried to decode it and further access an attribute, it gave an error suggesting :

这是因为缺少双引号,你无法在第一时间创建一个JSON对象,因此当你试图解码它并进一步访问一个属性时,它给出了一个错误提示:

 Trying to get property of non-object in /Applications/XAMPP/xamppfiles/htdocs/xampp/297test/userInfo.php on line 35

Try the code snippet I gave, it should hopefully help you out.

试试我给的代码片段,它应该有助于你。

#1


1  

Creating JSON-Strings directly through concatenation is hard because of quotes, new line characters etc.

由于引号,新行字符等,直接通过串联创建JSON字符串很难。

Instead, create an array of values and encode that into a JSON string with json_encode:

相反,创建一个值数组并使用json_encode将其编码为JSON字符串:

$values = array(
  "jsonFirstName" =>        $_POST['firstName'],
  "jsonLastName" =>         $_POST['lastName'],
  "jsonEmail" =>            $_POST['email'],
  "jsonPassword" =>         $_POST['password'],
  "jsonDob" =>              $_POST['dob'],
  "jsonDobTime" =>          $_POST['dobTime'],
  "jsonLocaldob" =>         $_POST['localdob'],
  "jsonSsn" =>              $_POST['ssn'],
  "jsonPhonenumber" =>      $_POST['phone'],
  "jsonCreditcardnumber" => $_POST['creditCardNumber']
);

$json_obj = json_encode($values);

Alternatively you can just do:

或者你可以这样做:

$json_obj = json_encode($_POST);

You will then get a JSON object with every index of $_POST. The only difference is, that you can't rename your fields as you did in your example.

然后,您将获得每个索引为$ _POST的JSON对象。唯一的区别是,您不能像在示例中那样重命名字段。

#2


0  

Not sure why you are doing it this way, however the parse error is because you are using a single quote to open the string and then also using that to pick the array index.

不知道为什么你这样做,但解析错误是因为你使用单引号打开字符串,然后使用它来选择数组索引。

Change $_POST['firstName'] to use double quotes such as $_POST["firstName"]

更改$ _POST ['firstName']以使用双引号,例如$ _POST [“firstName”]

#3


0  

EDIT: Try to do this.

编辑:尝试这样做。

$array = (
      "jsonFirstName" =>  $_POST['firstName'],
      "jsonLastName" =>  $_POST['lastName'],
      "jsonEmail" => $_POST['email'],
      "jsonPassword" => $_POST['password'],
      "jsonDob" => $_POST['dob'],
      "jsonDobTime" => $_POST['dobTime'],
      "jsonLocaldob" => $_POST['localdob'],
      "jsonSsn" => $_POST['ssn'],
      "jsonPhonenumber" => $_POST['phone'],
      "jsonCreditcardnumber" => $_POST['creditCardNumber']
 );

$json = json_encode($array);

#4


0  

You're getting an error because you are creating the JSON object out of the POST variables in a wrong way. There is indeed an issue with quotes in your statement. It should rather be something like:

您收到错误是因为您以错误的方式从POST变量中创建JSON对象。您的陈述中确实存在引号问题。它应该是这样的:

  $json_obj = '{
  "jsonFirstName": "'.(string) $_POST['firstName'].'",
  "jsonLastName": "'.(string) $_POST['lastName'].'",
  "jsonEmail": "'.(string) $_POST['email'].'",
  "jsonPassword": "'.(string) $_POST['password'].'",
  "jsonDob": "'.(string) $_POST['dob'].'",
  "jsonDobTime": "'.(string) $_POST['dobTime'].'",
  "jsonLocaldob": "'.(string) $_POST['localdob'].'",
  "jsonSsn": "'.(string) $_POST['ssn'].'",
  "jsonPhonenumber": "'.(string) $_POST['phone'].'",
  "jsonCreditcardnumber": "'.(string) $_POST['creditCardNumber'].'"
  }';

If I just include the variable without the double quotes while constructing the JSON object I get something like:

如果我在构造JSON对象时只包含没有双引号的变量,我会得到类似的结果:

  $name = "Foo";
  $json_obj = '{"firstName" :'.$name.'}'; 

 //gets expanded to $json_obj = {"firstname" : Foo}
 //Whereas it should be $json_obj = {"firstname" :"Foo"}

It was because of the missing double quotes, you could not create a JSON object in the first place and therefore when you tried to decode it and further access an attribute, it gave an error suggesting :

这是因为缺少双引号,你无法在第一时间创建一个JSON对象,因此当你试图解码它并进一步访问一个属性时,它给出了一个错误提示:

 Trying to get property of non-object in /Applications/XAMPP/xamppfiles/htdocs/xampp/297test/userInfo.php on line 35

Try the code snippet I gave, it should hopefully help you out.

试试我给的代码片段,它应该有助于你。