Inserting data into SQL

0

Hello, I'd like to know how I can change area code 1 from insert using foreach ($ name as $ cod = > $ value) as the area code 2 I am not able to make an adaptation by changing the insert mode of code 2 so that foreach ($ name as $ cod => value) works.

Code 1

mysql_query("INSERT INTO 'episodios' SET 'nome'='".$_POST["nome"]."','media'='".$_POST["media"]."','tamanho'='".$_POST["tamanho"]."','tipo'='".$_POST["tipo"]."'")

Code 2

$nome = $_POST['nomes'];
$anime = $_POST['animes'];
$tamanho = $_POST['tamanhos'];
$tipo = $_POST['tipo'];

foreach($nome as $cod => $value){
$sql = "insert into episodios (id,nome,anime,tamanho,tipo) values ('','$nome[$cod]','$anime[$cod]','$tamanho[$cod]','$tipo')";
$consulta = mysql_query($sql) or die(mysql_error());
if($consulta) {
echo "<br/><center><div id=\"Aviso_ok\">Episodio Cadastrado com Sucesso</div></center><br/>";
}else{
echo "<br/><center><div id=\"Aviso_erro\">Erro ao Cadastrar o Episodio</div></center><br/>";}
}
    
asked by anonymous 09.04.2015 / 11:34

1 answer

1

To generate a single INSERT, which inserts all the records at once, you need an sql in this format:

INSERT INTO tabela(numero) VALUES (1), (2), (3), (4), (5), (6), (7), (8), (9), (10)

This is equivalent to this:

INSERT INTO tabela(numero) VALUES (1);
INSERT INTO tabela(numero) VALUES (2);
...
INSERT INTO tabela(numero) VALUES (10);

To do this, use a logic similar to this:

$valores = range( 1 , 10 );
$sql = sprintf( 'INSERT INTO tabela(numero) VALUES (%s)', implode( '), (' , $valores ) );

You will generate a single INSERT, leaving the system much faster

See more in this article: link

Your system has two other problems: SQL Injection and mysql.

  • To protect SQL Injection account, see: link

  • mysql_ * functions have been deprecated since PHP 5.5. Prefer to use MySQLi or PDO. See more here: link

  • 09.04.2015 / 15:25