简体   繁体   中英

Insert Multiple Rows into mysql DB

How would you go about inserting multiple rows into a db if certain fields contained data? Consider the following:

register_case = mysql_query ("INSERT INTO cases VALUES
                              ('$case','$p_firstname','$p_lastname','$city'),
                              ('$case','$p2_firstname','$p2_lastname','$city'),
                              ('$case','$p3_firstname','$p3_lastname','$city')"
                            );

This creates multiple rows with different first and last names but the case and city remain the same. However, in the event that there is only 1 entry, a row is still created for the other 2. How is it possible to create a row only if there is data present in a given field?

You can try an if case that would just do something like:

if (isset($field)) do thisquery 

or

if ($field != "") do thatquery

I assume this would be taking info from a form?

If so, name the inputs like "name="firstname[]"", which will cause them to be placed in an array when submitted, like $_POST['firstname'][0], so if you had 3 inputs named firstname[] then you'd get $_POST['firstname'][0],$_POST['firstname'][1], and $_POST['firstname'][2].

Then do something like this:

$sql = 'INSERT INTO `cases` VALUES ';

for($i = 0;$i < count($_POST['firstname']);$i++)
{
    $sql .= "('$case','".$_POST['firstname'][$i]."','".$_POST['lastname'][$i]."','$city')";
    if($i != count($_POST['firstname']) - 1)
    {
        $sql .= ',';  //Will insert a comma after each except the last.  Count - 1 since $i will equal count - 1 on the last one, since it starts at 0 and not 1.
    }
}

$register_case = mysql_query($sql);

I think that should work.

Alternatively you could do a foreach and append a ',' on every one and then trim it off the right end of the string when done, or do a foreach and keep an external counter that manually increments after at the end. On second thought, neither of those would catch the lastnames, well without doing a $key=>$value type thing, and doing $_POST['lastname'][$key]. Might also need to check for empty strings with an if.

Of course, you never want to directly pass $_POST or $_GET values to SQL, validate first and make sure there's no injection.

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