Re: Multiple MySQL INSERT into loop

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Rob G wrote:
> //BEGIN EXAMPLE
> 
>  
> 
> mysql_query ("INSERT INTO testimonials (id, quote, name) VALUES ('$id_1',
> '$entry_1', '$name_1')");
> 
>  
> 
> mysql_query ("INSERT INTO testimonials (id, quote, name) VALUES ('$id_2',
> '$entry_2', '$name_2')");
> 
>  
> 
> mysql_query ("INSERT INTO testimonials (id, quote, name) VALUES ('$id_3',
> '$entry_3', '$name_3')");
> 
>  
> 
> //END EXAMPLE
> 
> 
> I'd like to put this into a loop, so that the variable that are being
> defined as the VALUES change as needed.
> 
>  
> 
> //BEGIN EXAMPLE
> while ($i<16)
> {
> $i++;
> mysql_query ("INSERT INTO testimonials (id,quote,name) VALUES ('$id_1',
> '$entry_1', '$name_1')");)");
> }
> 
> //END EXAMPLE
> 
> What I'm trying to figure out, is exactly how I need to format my entry
> within the VALUES section, so that it will change based on the value of $i.

Simplest way would be to define your data in an array instead:

e.g. $data = array(1 => array('id' => x, 'entry' => y, 'name' => z), ...).

Then you can do:
mysql_query ("INSERT INTO testimonials (id,quote,name) VALUES
('".$data[$i]['id']."','".$data[$i]['entry']."','".$data[$i]['name']."');");

(normal rules about escaping data should apply to the above - e.g. pass
unsafe values through mysql_real_escape_string rather than put the
quotes in yourself)

Of course if you are inserting a lot of data with mysql, it's *much*
faster to use the extended instert syntax:

INSERT INTO table (col1, col2) VALUES (val1a, val1b),(val2a, val2b),(...);

HTHs

Col

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux