Domanda

Ok, anche se sto lavorando sulle mie competenze PHP e MySQL, sono nuovo nell'inserimento di dati in più tabelle in una volta sola.Ho letto alcune informazioni sull'argomento e apprezzo le nozioni di base e l'importanza dei dati normalizzati ecc. E come tale la necessità di inserire le informazioni in varie tabelle.

Ho messo insieme il codice seguente tratto da alcuni dei miei lavori precedenti e dal tutorial offerto su http://www.desilva.biz/mysql/insertid.html .Il problema che sto affrontando attualmente è che il tutorial da cui ho imparato il codice per l'inserimento in varie tabelle non era basato su una serie di dati e anche se sono riuscito quasi a farlo funzionare, non posso usare il mio Fuelrecords_id perché dove devo chiamarlo nel mio il codice attuale non è stato ancora definito.Pertanto per far funzionare il mio codice al momento devo solo usare una virgola per la colonna.

Infine, vorrei perfezionare un modo per far funzionare correttamente le istruzioni if ​​con i dati dell'array, quindi se viene inviato uno 0 o uno spazio come parte dell'array, una nuova riga non viene inserita con solo 0 nelle tabelle del mio database per quella rispettiva riga di dati

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

Le tabelle sono le seguenti:

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) 

Fondamentalmente lo scopo è registrare il consumo e il costo del carburante del veicolo.Poiché non ci saranno sempre dati per benzina, diesel e olio, sono presenti tabelle separate in modo che vengano registrati solo i dati necessari.Spero che questo chiarisca

Un aiuto e un'assistenza sempre disponibili sono molto apprezzati.

È stato utile?

Soluzione

Se ho capito bene il tuo codice hai 4 tabelle: fuelrecords, fuelrecords_die, fuelrecords_pet, fuelrecords_oil.

I 3 tavoli fuelrecords_die, fuelrecords_pet, fuelrecords_oil ognuno ha una chiave esterna fuelrecords_id A fuelrecords.fr_id.

Ora vuoi inserire più tuple in fuelrecords e, se vengono forniti dati aggiuntivi, più tuple nelle altre 3 tabelle.Presumo che fuelrecords.fr_id la colonna è una chiave primaria con incremento automatico.

Per inserire più tuple in fuelrecords e fare in modo che ciascuna abbia un nuovo fr_id, semplicemente non passi un valore per la colonna fr_id.Ciò equivale a passare NULL come valore.MySQL inserirà quindi automaticamente numeri consecutivi univoci per ciascuna tupla.

Dopodiché puoi chiamare mysql_insert_id() prendere il Primo inserito l'identificativo.Utilizzando mysql_affected_rows() puoi ottenere il numero di tuple inserite.Queste sono informazioni sufficienti per ottenere l'id di tutte le tuple inserite per ultime.Il primo è mysql_insert_id()+0 il secondo è mysql_insert_id()+1, ..., l'ultimo è mysql_insert_id()+(mysql_affected_rows()-1).

Nel passaggio successivo esegui nuovamente l'iterazione sui dati di input e inserisci il file fuelrecords_id in ciascuna delle tuple per le altre 3 tabelle, utilizzando il metodo sopra menzionato.Se $i è l'indice dei dati di input $_POST['FR_DIE_L'][$i] (a partire da $i==0), IL fuelrecords_id sarà mysql_insert_id()+$i.Ti è consentito solo eseguire iterazioni mysql_insert_id()+mysql_affected_rows()-1, ma probabilmente avrai comunque lo stesso conteggio di dati POST.

Un modo molto più semplice ma leggermente meno efficiente è farne solo uno insert into fuelrecords e poi uno inserito nelle altre 3 tabelle per ogni singolo oggetto dati POST.Non dovrai calcolare il fuelrecords_id COME mysql_insert_id() ti darà l'ID corretto dopo ogni inserimento.

<?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);
    }
}

?>

Una piccola aggiunta fuori tema:Cerca di non utilizzare nomi di variabili in maiuscolo.Gli identificatori maiuscoli vengono solitamente conservati per le costanti:

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;

Ciò non avrà alcun effetto sull'interprete PHP.È solo una notazione comune per rendere il tuo codice leggibile per gli altri.Ci sono molte guide di stile là fuori come quello di PERA.

Secondo esempio (vedi commenti)

<?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);
    }
}

?>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top