简体   繁体   English

使用二维数组在mysql中存储数据

[英]Storing data in mysql using two dimensional array

Here is the form that collects employer's history and stores that data into 2d array, then I am trying to store that info into mysql database in a table employment . 这里是收集雇主的历史和数据到二维数组,然后我试图存储信息到mysql数据库中的表存储形式employment It gives me no error but it can't store data into mysql .. 它没有给我任何错误,但无法将数据存储到mysql ..

form1.php form1.php

<form action="result.php" method="post">
        <table width="676" border="0" cellspacing="0" cellpadding="7" align="center">
            <tr><td colspan="6" bgcolor="#C0C0C0">EMPLOYMENT HISTORY</td></tr>
<?php

for ($x=0; $x<2; $x++) 
{ 
?>
            <tr>
                <td colspan="3" align="left">NAME OF EMPLOYER<br>
                        <input type="text" name="emp[emp_name][]" size="38"></td>

                <td align="left">JOB TITLE <br>
                    <input type="text" name="emp[emp_title][]" size="32"></td>
            </tr>
            <tr>
                <td colspan="5" valign="top">ADDRESS<br>
                        <input type="text" name="emp[emp_addr][]" size="58"></td>
            </tr>
            <tr>
                <td colspan="2" valign="top">REASON FOR LEAVING<br>
                        <textarea name="emp[emp_reason][]" cols="25" rows="3"></textarea></td>
            </tr>
            <tr>
                <td align="left">DATE STARTED<br>
                        <input type="text" name="emp[emp_start][]" size="8"></td>
                <td align="left">DATE ENDED<br>
                        <input type="text" name="emp[emp_end][]" size="8"></td>
                <td colspan="2" align="left">TYPE OF BUSINESS<br>
                        <input type="text" name="emp[emp_btype][]" size="15"></td>
            </tr>
            <tr><td colspan="6" bgcolor="#C0C0C0">&nbsp;</td></tr>
<?php } ?>
</table>
<input type="submit" name="submit" value="SUBMIT">&nbsp;&nbsp;<input type="reset" value="RESET">
</form>

here is the result.php 这是result.php

 <?php
// open connection to the database
mysql_connect('localhost', 'user', 'pass');
mysql_select_db('userdb');

// get all the values
$app_id = 5;
$app_emp = array($emp => array(
                                   $emp_name => $_POST["emp_name"],
                                   $emp_title => $_POST["emp_title"],
                                   $emp_addr => $_POST["emp_addr"],
                                   $emp_reason => $_POST["emp_reason"],
                                   $emp_start => $_POST["emp_start"],
                                   $emp_end => $_POST["emp_end"],
                                   $emp_btype => $_POST["emp_btype"]
                                 ));
// set up error list array
$errorList = array();
$count = 0;

// validate
// making sure that they are filling in all the required fields for the employer for each of the 3 "boxes"
    for ($x=0; $x<sizeof($app_emp); $x++)
    {
        if(!empty($emp_name[$x]) || !empty($emp_start[$x]) || !empty($emp_end[$x]))
        {
            if(empty($emp_start[$x]) || empty($emp_end[$x])) 
            { 
            $errorList[$count] = "Invalid entry: Employment History, item " . ($x+1);
            $count++;
            }
        }
    }

    // if no errors
    if (sizeof($errorList) == 0)
    {
        // insert employment history
        for($i=0; $i<sizeof($emp_name); $i++)
        {
        $x = 0;
            if (!empty($emp_name[$i][$x]) && !empty($emp_start[$i][$x]) && !empty($emp_end[$i][$x]))
            {
            $query = "INSERT INTO `employment` (`app_id`,`name`,`title`,`addr`,`reason`,`start`,`end`,`bustype`) VALUES ('$app_id', '$emp_name[$x]', '$emp_title[$x]', '$emp_addr[$x]','$emp_reason[$x]', '$emp_start[$x]', '$emp_end[$x]', '$emp_btype[$x]')" or die(mysql_error());
            $result = mysql_query($query, $conn) or die ("Error in query: $query. " . mysql_error());
            }
        }
        // If it gets processed, print success code
        echo "Your information has been accepted.";
    }
    else
    {
    ?>
    <table width="676" border="0" cellspacing="0" cellpadding="8" align="center">
            <tr><td>
<?php
    // or list errors
    listErrors();
?>
            </span></td>
            </tr>
        </table>
<?
    }
?>
<?php
// print out the array
echo '<pre>';
print_r($_POST);
echo '</pre>'; 

?>

I know you have found a solution. 我知道您找到了解决方案。 Just incase someone found this and get curious :) 以防万一有人发现这个并感到好奇:)

There are couple of issues with the logic For start under this line: // get all the values 逻辑方面存在一些问题对于此行下的开始://获取所有值

$emp will be empty '' all the time as it is not initialised and if you initialise the entire logic will shatter. $ emp将一直为空'',因为它没有初始化,如果初始化,整个逻辑将崩溃。

Also the $_POST you have mentioned will always be empty. 同样,您提到的$ _POST将始终为空。 You need to address it from them Master (Level1) Just var_dump($_POST) and you see what I mean :) 您需要从他们那里解决它。Master(Level1)只是var_dump($ _ POST),您明白我的意思了:)

So do something like this: (I must stress this is not a good approach but just to shed some light on this question) 因此,请执行以下操作:(我必须强调这不是一个好方法,而只是为了阐明这个问题)

var_dump($_POST['emp']); // This is master array that holds everything
$app_emp = array();

foreach ($_POST['emp'] as $key => $val) {

    $app_emp[0][$key] = mysql_real_escape_string($val[0]);
    $app_emp[1][$key] = mysql_real_escape_string($val[1]);
}

// set up error list array
$errorList = array();
$count = 0;

var_dump($app_emp);

Now in the $app_emp you have got 2 separate arrays that you can go through, validate and add them to DB. 现在,在$ app_emp中,您可以通过2个独立的数组,进行验证并将其添加到DB中。 Of-course the current SQL is not going to work as you need to wiggle it to fit the new array. 当然,当前的SQL将无法正常工作,因为您需要使其摆动以适合新数组。 Rest should be easy. 休息应该很容易。

Couple Of handy note: 几个方便的注意事项:

  • I am sure you are cleaning up your form submit mysql_real_escape for all the vars. 我确定您正在清理所有var的表单,提交mysql_real_escape。
  • Also try to use redirection after successful submit, as users will intend to refresh the page. 成功提交后,也请尝试使用重定向,因为用户将打算刷新页面。 Otherwise user is going to get ugly do you want to resubmit the data. 否则用户会变得很丑陋,是否要重新提交数据。
  • Make sure you pass a token to the result page, and check it there. 确保将令牌传递到结果页面,然后在其中进行检查。 I would use a random DB number so stop the Cross Browser hacks. 我会使用一个随机的数据库编号,以便阻止跨浏览器黑客入侵。

Hope this help. 希望能有所帮助。 H. H。

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

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