Jump to content

Inserting multiple records into one table


monaya

Recommended Posts

Hi I'm using this code to insert multiple records. The code executes but nothing is entered into my database. This usually happens when there's a mismatch in data types.

 

How do I ensure that description goes in as text which in sql is wrapped in single quotes, but also make sure the other variables go in as numeric.

 // an array items to insert
    $array = array( 'theid'   => $theid,
            'descr'      =>   $descr,
            'costperunit'    => $costperunit,
            'quantity'       => $quantity,
'costperlot'       => $costperlot
            );


    // begin the sql statement
    $sql1 = "INSERT INTO  descriptions (jobid, description, costperunit, quantity, costperlot) VALUES ";

    $it = new ArrayIterator( $array );


    // a new caching iterator gives us access to hasNext()
    $cit = new CachingIterator( $it );


    // loop over the array
    foreach ( $cit as $value )
    {
        // add to query
        $sql1 .= "('".$cit->key()."','" .$cit->current()."')";
       

        if( $cit->hasNext() )
        {
            $sql1 .= ",";
        }
    }

You are trying to add two values to the database, but you have 5 columns listed.  Yes, the database is going to puke on that one.  It doesn't know what columns you want to add to.  You will either have to shorten the columns, or add to the values.

You should be using prepared statements to interact with the database.  Couple that with error logging, you will see the problem pretty quick.

Edit: prepared statements will cure the data type problem as well.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.