multiple records insert with foreach

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
nicademus
Forum Newbie
Posts: 14
Joined: Tue Apr 14, 2009 8:36 am

multiple records insert with foreach

Post by nicademus »

Hello All!

I am trying to figure out how to insert multiple records with a single php script. I have this at the moment:

Code: Select all

 
<?php
foreach($_POST['co_name'] as $co_name => $value)
{
  $sql="INSERT INTO links (co_name)
         VALUES ($value)";
}
 
foreach($_POST['link'] as $link => $value)
{
  $sql="INSERT INTO links (co_name)
         VALUES ($value)";
}
 
 
foreach($_POST['text'] as $text => $value)
{
  $sql="INSERT INTO links (co_name)
         VALUES ($value)";
}
?>
 
And the HTML form

Code: Select all

 
<form id="list" action="db-co_links-script.php" method="post">
 
<legend>Links to retailers and Designers</legend>
<br />
<table cellspacing="3">
  <tr>
    <td>Company Name</td> <td><input type="text" name="co_name[]" /></td>
  </tr>
  <tr>
    <td>Link</td> <td><input type="text" name="link[]" /></td> <td>Text</td> <td><input type="text" name="text[]" />
  </tr>
  
</table>
 
 
 
</fieldset><br />
 
<input type="submit" value="Submit To Database?" />
</form>
 
I would be inserting 6 records for each company in a single form - after I get this to work I will add the other form elements.
A push in the right direction would be greatly appreciated!
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: multiple records insert with foreach

Post by McInfo »

I was bored, so I wrote a script that you can build on. You will need to change some things, like add some appropriate validation and database functions.

form.php

Code: Select all

<form method="post" action="accept.php">
    <table cellspacing="0" cellpadding="3" border="1">
        <tr>
            <th>#</th>
            <th>Company Name</th>
            <th>Link Location</th>
            <th>Link Text</th>
        </tr>
        <?php for ($i = 0; $i < 4; $i++) : ?>
        <tr>
            <td><?php echo $i; ?></td>
            <td><input type="text" name="company_links[name][]" value="name<?php echo $i; ?>" size="25" /></td>
            <td><input type="text" name="company_links[href][]" value="href<?php echo $i; ?>" size="40" /></td>
            <td><input type="text" name="company_links[text][]" value="text<?php echo $i; ?>" size="25" /></td>
        </tr>
        <?php endfor; ?>
        <tr>
            <td colspan="4" align="center"><input type="submit" value="Submit links" /></td>
        </tr>
    </table>
</form>
accept.php

Code: Select all

<?php
error_reporting(E_ALL);
header('Content-Type: text/plain');
 
$company_links_qry = array();
$company_links_str = array();
$company_links_arr = array();
 
if (isset_array($_POST['company_links']))
{
    echo 'Company links were posted.'."\n";
   
    // Easier to manage short variable names (by reference)
    $names =& $_POST['company_links']['name'];
    $hrefs =& $_POST['company_links']['href'];
    $texts =& $_POST['company_links']['text'];
   
    if (isset_array($names)
    &&  isset_array($hrefs)
    &&  isset_array($texts))
    {
        echo 'Required parameters are set.'."\n";
       
        $link_count = count($names);
       
        // Ensures that all three arrays have the same number of elements
        if (count($hrefs) == $link_count
        &&  count($texts) == $link_count)
        {
            echo 'Array counts match.'."\n";
           
            for ($i = 0; $i < $link_count; $i++)
            {
                // Cleans and validates each input
                if (isset($names[$i], $hrefs[$i], $texts[$i])
                &&  validate_name($names[$i])
                &&  validate_href($hrefs[$i])
                &&  validate_text($texts[$i]))
                {
                    echo 'Company link '.$i.' passed validation.'."\n";
                   
                    // Builds queries for the database
                    $company_links_qry[$i] =
                        sprintf('INSERT INTO `company_links` (`name`, `href`, `text`) '
                              . "VALUES ('%s', '%s', '%s')"
                               , $names[$i]
                               , $hrefs[$i]
                               , $texts[$i]);
                   
                    // Builds example HTML links (optional)
                    $company_links_str[$i] =
                        sprintf('%s: <a href="%s">%s</a>'
                               , $names[$i]
                               , $hrefs[$i]
                               , $texts[$i]);
                   
                    // Stores the clean inputs in a new array (optional)
                    $company_links_arr[$i] =
                        array($names[$i], $hrefs[$i], $texts[$i]);
                   
                }
                else
                    echo 'Company link '.$i.' failed validation.'."\n";
            }
        }
        else
            echo 'Array counts do not match.'."\n";
    }
    else
        echo 'Not all required parameters are set.'."\n";
}
else
    echo 'No company links were posted.'."\n";
 
// Displays prepared queries
if (0 < count($company_links_qry))
    print_r($company_links_qry);
   
// Displays complany links strings
if (0 < count($company_links_str))
    print_r($company_links_str);
 
// Displays company links data
if (0 < count($company_links_arr))
    print_r($company_links_arr);
 
/**
 * Determines whether the given string is
 * a valid company name for company links
 * and cleans the string.
 *
 * @param $name str
 * @return bool
 */
function validate_name (&$name)
{
    $name = trim($name);
   
    //@TODO Do more cleaning if necessary
   
    if (strlen($name) < 1)
        return false;
   
    /*
     * This is a ridiculous test to encourage you
     * to modify the validation requirements
     */
    if (preg_match('/[^A-Z0-9]/i', $name))
        return false;
   
    //@TODO Do more validation if necessary
   
    // If the string makes it through the gauntlet, return true
    return true;
}
 
/**
 * Determines whether the given string is
 * a valid URL for company links
 * and cleans the string.
 *
 * @param $href str
 * @return bool
 */
function validate_href (&$href)
{
    $href = trim($href);
   
    //@TODO Do more cleaning if necessary
   
    if (strlen($href) < 1)
        return false;
   
    /*
     * This is a ridiculous test to encourage you
     * to modify the validation requirements
     */
    if (preg_match('/[^A-Z0-9]/i', $href))
        return false;
   
    //@TODO Do more validation if necessary
   
    // If the string makes it through the gauntlet, return true
    return true;
}
 
/**
 * Determines whether the given string is
 * a valid link text string for company links
 * and cleans the string.
 *
 * @param $text str
 * @return bool
 */
function validate_text (&$text)
{
    $text = trim($text);
   
    //@TODO Do more cleaning if necessary
   
    if (strlen($text) < 1)
        return false;
   
    /*
     * This is a ridiculous test to encourage you
     * to modify the validation requirements
     */
    if (preg_match('/[^A-Z0-9]/i', $text))
        return false;
   
    //@TODO Do more validation if necessary
   
    // If the string makes it through the gauntlet, return true
    return true;
}
 
/**
 * Determines whether a variable is set and is an array.
 *  
 * @param $var mixed
 * @return bool
 */
function isset_array (&$var)
{
    if (isset($var) && is_array($var))
        return true;
    else
        return false;
}
 
?>
Edit: This post was recovered from search engine cache.
Last edited by McInfo on Mon Jun 14, 2010 3:12 pm, edited 1 time in total.
nicademus
Forum Newbie
Posts: 14
Joined: Tue Apr 14, 2009 8:36 am

Re: multiple records insert with foreach

Post by nicademus »

Wow, THANK YOU! It's going to take me some time to understand this as I am just starting php mysql. I wasn't expecting such a long script :)

Thanx again!

**********************************************8
I think I need something far more simple LOL
I have almost no idea how to follow this. I will try though. :)
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: multiple records insert with foreach

Post by McInfo »

Simple is elegant, but too simple is a security hole.

Edit: This post was recovered from search engine cache.
Last edited by McInfo on Mon Jun 14, 2010 3:12 pm, edited 1 time in total.
nicademus
Forum Newbie
Posts: 14
Joined: Tue Apr 14, 2009 8:36 am

Re: multiple records insert with foreach

Post by nicademus »

This is just a simple form I am using to insert the data for my site's launch - all forms are local. As I am new I thought I would wait until after launch to secure the forms and add them to the site as an admin area for me - a simple CMS. Thanx again!
Post Reply