简体   繁体   中英

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 . It gives me no error but it can't store data into mysql ..

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

 <?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.

Also the $_POST you have mentioned will always be empty. You need to address it from them Master (Level1) Just var_dump($_POST) and you see what I mean :)

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. Of-course the current SQL is not going to work as you need to wiggle it to fit the new array. 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.
  • 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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