使用mysql insert id和if语句插入数组数据

时间:2012-03-11 10:43:49

标签: php mysql arrays insert lastinsertid

好的,虽然我一直在研究我的PHP和MySQL技能,但我很想一次性将数据插入到多个表中。我已经围绕这个主题做了一些阅读,我很欣赏标准化数据等的基础知识和重要性,因此需要将信息放入各种表格中。

我已经从以前的一些工作以及http://www.desilva.biz/mysql/insertid.html提供的教程中拼凑了下面的代码。我目前面临的问题是,我学习输入各种表格的代码的教程并不是基于数据数组,虽然我已经得到它几乎工作但我不能使用我的fuelrecords_id,因为我必须在我的地方调用它目前的代码还没有定义。因此,为了使我的代码目前工作,我只需要使用逗号作为列。

最后,我想完善一种方法,使if语句与数组数据一起正常工作,所以如果将0或空白作为数组的一部分提交,则不会在我的数据库表中插入新的0行。各行数据

<?php
$wedrf=trim($_POST['FR_WE']);
list($d, $m, $y) = explode('/', $wedrf);
$mk=mktime(0, 0, 0, $m, $d, $y);
$wed_refor=strftime('%Y-%m-%d',$mk);

$con = mysql_connect("ip","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("jbsrint", $con);

//New Code

$row_data = array(); 
foreach($_POST['VEH_LIST_REG'] as $row=>$VEH_LIST_REG) { 
$WEDATE=$wed_refor;
$VEH_LIST_REG=mysql_real_escape_string($VEH_LIST_REG); 
$FR_DIE_L=mysql_real_escape_string($_POST['FR_DIE_L'][$row]); 
$FR_DIE_C=mysql_real_escape_string($_POST['FR_DIE_C'][$row]); 
$FR_PET_L=mysql_real_escape_string($_POST['FR_PET_L'][$row]); 
$FR_PET_C=mysql_real_escape_string($_POST['FR_PET_C'][$row]); 
$FR_OIL_L=mysql_real_escape_string($_POST['FR_OIL_L'][$row]); 
$FR_OIL_C=mysql_real_escape_string($_POST['FR_OIL_C'][$row]); 
$row_data[] = "(',', '$VEH_LIST_REG', '$WEDATE')"; 
$row_data1[] = "(',','$FR_DIE_L', '$FR_DIE_C', ',')";
$row_data2[] = "(',', '$FR_PET_L', '$FR_PET_C', ',')";
$row_data3[] = "(',', '$FR_OIL_L', '$FR_OIL_C', '$FR_OIL_C')";
} 
if (!empty($row_data)) { 
$query = 'INSERT INTO fuelrecords(FR_ID, VEH_LIST_REG, FR_WE) VALUES '.implode(',', $row_data); 
#$result = mysql_query( $query);

#  get fuelrecord id  
$fuelrecords_ID = mysql_insert_id();

#  if the user submitted diesel information
if( isset($FR_DIE_L) )
{

#  and insert the diesel details
$sql = "INSERT INTO fuelrecords_die(FRD_ID,FR_DIE_L,FR_DIE_C,fuelrecords_ID) VALUES ".implode(',', $row_data1);
$result = mysql_query( $sql);
}

#  if the user submitted petrol information
if( isset($FR_PET_L) )
{

#  and insert the diesel details
$sql = "INSERT INTO fuelrecords_pet(FRP_ID,FR_PET_L,FR_PET_C,fuelrecords_ID) VALUES ".implode(',', $row_data2);
$result = mysql_query( $sql);
}

#  if the user submitted oil information
if( isset($FR_OIL_L) )
{

#  and insert the oil details
$sql = "INSERT INTO fuelrecords_oil(FRO_ID,FR_OIL_L,FR_OIL_C,fuelrecords_ID) VALUES ".implode(',', $row_data3);
$result = mysql_query( $sql);
}

if (mysql_query($query)) 
    echo '<font color=\"FFFFFF\" size=\"3px\">Successful inserted</font>'; 
else 
    echo '<font color=\"FFFFFF\" size=\"3px\">Insert failed</font>'; 
} 

?>

<?php
mysql_close($con)
?>

表格如下:

fuelrecords 
FR_ID (Auto increment) 
VEH_LIST_REG 
FR_WE 

fuelrecords_die 
FRD_ID (AUTO INCREMENT) 
FR_DIE_L 
FR_DIE_C 
fuelrecords_ID (foreign ID from fuelrecords) 

fuelrecords_pet 
FRP_ID (AUTO INCREMENT) 
FR_PET_L 
FR_PET_C 
fuelrecords_ID (foreign ID from fuelrecords) 

fuelrecords_oil 
FRO_ID (AUTO INCREMENT) 
FR_OIL_L 
FR_OIL_C 
fuelrecords_ID (foreign ID from fuelrecords) 

基本上,目的是记录车辆燃料使用和成本。由于不会总是有汽油,柴油和油的数据因此单独的表,所以只需要记录数据。 希望这澄清

总是非常感谢所有帮助和帮助。

1 个答案:

答案 0 :(得分:1)

如果我正确理解您的代码,则您有4个表:fuelrecordsfuelrecords_diefuelrecords_petfuelrecords_oil

3个表fuelrecords_diefuelrecords_petfuelrecords_oil每个都有一个外键fuelrecords_idfuelrecords.fr_id

您现在想要将多个元组插入fuelrecords,如果提供了其他数据,则将多个元组插入到其他3个表中。我假设fuelrecords.fr_id列是一个自动递增的主键。

要将多个元组插入到燃料记录中并让每个元组都有一个新的fr_id,您只需要为列fr_id传递一个值。这相当于将NULL作为值传递。然后,MySQL将自动为每个元组插入唯一的连续数字。

之后,您可以致电mysql_insert_id()以获取第一个插入ID。使用mysql_affected_rows(),您可以获得插入元组的数量。这是获取所有最后插入的元组的id的足够信息。第一个是mysql_insert_id()+0,第二个是mysql_insert_id()+1,...,最后一个是mysql_insert_id()+(mysql_affected_rows()-1)

在下一步中,您将再次迭代输入数据,并使用上述方法将fuelrecords_id插入其他3个表的每个元组中。如果$i是输入数据$_POST['FR_DIE_L'][$i]的索引(从$i==0开始),则fuelrecords_id将为mysql_insert_id()+$i。您只能迭代到mysql_insert_id()+mysql_affected_rows()-1,但无论如何您可能会拥有相同数量的POST数据。

一种更简单但效率稍低的方法是只为一个insert into fuelrecords执行一次,然后为每个单个POST数据对象插入另外3个表。您不必计算fuelrecords_id,因为mysql_insert_id()会在每次插入后为您提供正确的ID。

<?php

$wedrf=trim($_POST['FR_WE']);
list($d, $m, $y) = explode('/', $wedrf);
$mk=mktime(0, 0, 0, $m, $d, $y);
$wed_refor=strftime('%Y-%m-%d',$mk);

$row_data = array(); 

// shorthand for mysql_real_escape_string
function esc($value) {
    return mysql_real_escape_string($value);
}

// all tuples for fuelrecords to be inserted
foreach($_POST['VEH_LIST_REG'] as $row => $VEH_LIST_REG) { 
    $row_data[] = "(NULL, '".esc($VEH_LIST_REG)."', '".esc($wed_refor)."')";
} 

if (!empty($row_data)) { 
    $query = 'INSERT INTO fuelrecords(FR_ID, VEH_LIST_REG, FR_WE) VALUES '.implode(',', $row_data);
    $result = mysql_query($query);

    # get first fuelrecord id  
    $first_fuelrecords_id = mysql_insert_id();

    // all tuples for the other 3 tables. insert only if data is givin.
    $die_data = array();
    $pet_data = array();
    $oil_data = array();
    foreach($_POST['VEH_LIST_REG'] as $row => $VEH_LIST_REG) {

        // calculate the right fuelrecords_id for this tuple
        $fuelrecords_id = (int)($first_fuelrecords_id + $row);

        // insert for fuelrecords_die
        if (isset($_POST['FR_DIE_L'][$row]))
        {
            $die_data[] = "(NULL, ".$fuelrecords_id.", '".esc($_POST['FR_DIE_L'][$row])."', '".esc($_POST['FR_DIE_C'][$row])."')";
        }

        // insert for fuelrecords_pet
        if (isset($_POST['FR_PET_L'][$row]))
        {
            $pet_data[] = "(NULL, ".$fuelrecords_id.", '".esc($_POST['FR_PET_L'][$row])."', '".esc($_POST['FR_PET_C'][$row])."')";
        }

        // insert for fuelrecords_oil
        if (isset($_POST['FR_OIL_L'][$row]))
        {
            $oil_data[] = "(NULL, ".$fuelrecords_id.", '".esc($_POST['FR_OIL_L'][$row])."', '".esc($_POST['FR_OIL_C'][$row])."')";
        }
    }

    // insert the tuples into fuelrecords_die
    if (!empty($die_data))
    {
        $sql = "INSERT INTO fuelrecords_die(FRD_ID, fuelrecords_ID, FR_DIE_L, FR_DIE_C) VALUES ".implode(',', $die_data);
        $result = mysql_query( $sql);
    }

    // insert the tuples into fuelrecords_pet
    if (!empty($pet_data))
    {
        $sql = "INSERT INTO fuelrecords_pet(FRP_ID, fuelrecords_ID, FR_PET_L, FR_PET_C) VALUES ".implode(',', $pet_data);
        $result = mysql_query( $sql);
    }

    // insert the tuples into fuelrecords_oil
    if (!empty($oil_data))
    {
        $sql = "INSERT INTO fuelrecords_oil(FRO_ID, fuelrecords_ID, FR_OIL_L, FR_OIL_C) VALUES ".implode(',', $oil_data);
        $result = mysql_query( $sql);
    }
}

?>

一个小的偏离主题的补充:尽量不要使用大写变量名。大写标识符通常保留为常量:

define("MY_SHORT_PI", 3.14159265);
define("MY_CONST", "foobar");

$my_variable = "bat";

echo "I am a constant ".MY_SHORT_PI;
echo "Me too ".MY_CONST;
echo "I am a variable ".$my_variable;

这对PHP解释器没有任何影响。这只是让您的代码对其他人可读的常见表示法。那里有很多风格指南,如the one from PEAR

第二个例子(见评论)

<?php

$wedrf=trim($_POST['FR_WE']);
list($d, $m, $y) = explode('/', $wedrf);
$mk=mktime(0, 0, 0, $m, $d, $y);
$wed_refor=strftime('%Y-%m-%d',$mk);

// VALUES strings for fuelrecords
$row_data = array();

// temporary storage for just _L and _C values
$die_data_tmp = array();
$pet_data_tmp = array();
$oil_data_tmp = array();

// VALUES strings for the three tables
$die_data = array();
$pet_data = array();
$oil_data = array();

// shorthand for mysql_real_escape_string
function esc($value) {
    return mysql_real_escape_string($value);
}

// all tuples for fuelrecords to be inserted
foreach($_POST['VEH_LIST_REG'] as $row => $VEH_LIST_REG) { 

    // check if diesel values are greater than 0
    if (0 < (int)$_POST['FR_DIE_L'][$row] && 0 < (int)$_POST['FR_DIE_C'][$row])
        $die_data_tmp[$row] = array($_POST['FR_DIE_L'][$row], $_POST['FR_DIE_C'][$row]);

    // check if petrolium values are greater than 0
    if (0 < (int)$_POST['FR_PET_L'][$row] && 0 < (int)$_POST['FR_PET_C'][$row])
        $pet_data_tmp[$row] = array($_POST['FR_PET_L'][$row], $_POST['FR_PET_C'][$row]);

    // check if oil values are greater than 0
    if (0 < (int)$_POST['FR_OIL_L'][$row] && 0 < (int)$_POST['FR_OIL_C'][$row])
        $oil_data_tmp[$row] = array($_POST['FR_OIL_L'][$row], $_POST['FR_OIL_C'][$row]);

    // check if at least one of the 3 tables will get tuples. if not just continue 
    // with the next and don't assign this fuelrecord tuple to $row_data
    if (! isset($die_data_tmp[$row]) && ! isset($pet_data_tmp[$row]) && ! isset($oil_data_tmp[$row]))
        continue;

    // all values are at least 1, so add this tuple to our inserts
    $row_data[$row] = "(NULL, '".esc($VEH_LIST_REG)."', '".esc($wed_refor)."')";
}

if (!empty($row_data)) { 
    $query = 'INSERT INTO fuelrecords(FR_ID, VEH_LIST_REG, FR_WE) VALUES '.implode(',', $row_data);
    $result = mysql_query($query);

    # get first fuelrecord id  
    $current_fuelrecords_id = mysql_insert_id();

    // all tuples for the other 3 tables. insert only if data is givin.
    foreach($row_data as $row => $VEH_LIST_REG) {

        // insert for fuelrecords_die
        if (isset($die_data_tmp[$row]))
        {
            $die_data[] = "(NULL, ".$current_fuelrecords_id.", '".esc($die_data_tmp[$row][0])."', '".esc($die_data_tmp[$row][1])."')";
        }

        // insert for fuelrecords_pet
        if (isset($pet_data_tmp[$row]))
        {
            $pet_data[] = "(NULL, ".$current_fuelrecords_id.", '".esc($pet_data_tmp[$row][0])."', '".esc($pet_data_tmp[$row][1])."')";
        }

        // insert for fuelrecords_oil
        if (isset($oil_data_tmp[$row]))
        {
            $oil_data[] = "(NULL, ".$current_fuelrecords_id.", '".esc($oil_data_tmp[$row][0])."', '".esc($oil_data_tmp[$row][1])."')";
        }

        // increment the fuelrecords_id for the next tuple.
        ++$current_fuelrecords_id;
    }

    // insert the tuples into fuelrecords_die
    if (!empty($die_data))
    {
        $sql = "INSERT INTO fuelrecords_die(FRD_ID, fuelrecords_ID, FR_DIE_L, FR_DIE_C) VALUES ".implode(',', $die_data);
        $result = mysql_query( $sql);
    }

    // insert the tuples into fuelrecords_pet
    if (!empty($pet_data))
    {
        $sql = "INSERT INTO fuelrecords_pet(FRP_ID, fuelrecords_ID, FR_PET_L, FR_PET_C) VALUES ".implode(',', $pet_data);
        $result = mysql_query( $sql);
    }

    // insert the tuples into fuelrecords_oil
    if (!empty($oil_data))
    {
        $sql = "INSERT INTO fuelrecords_oil(FRO_ID, fuelrecords_ID, FR_OIL_L, FR_OIL_C) VALUES ".implode(',', $oil_data);
        $result = mysql_query( $sql);
    }
}

?>