How to avoid Multiple Inserts in the database

Asked

Viewed 160 times

3

Ola would like to know how I can use php to avoid adding the same item to a database on a save page that adds the names of the subcategories if you update your browser.

Since I cannot use in the database Unique in the table subcategory in the name field because it would make it impossible for me to use the same name if it is affiliated to another category.

Below are the two tables.

Table Category

CREATE TABLE IF NOT EXISTS `categoria` (
  `id` int(255) NOT NULL AUTO_INCREMENT,
  `categoria_url` char(255) COLLATE utf8_unicode_ci NOT NULL,
  `nome` char(255) COLLATE utf8_unicode_ci NOT NULL,
  `modo` enum('UNICO','MULTIPLO') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'UNICO',
  `data` date NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `categoriaUnica` (`categoria_url`),
  UNIQUE KEY `nomeUnico` (`nome`),
  KEY `colunasIndexadas` (`id`,`categoria_url`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

Table subcategory

CREATE TABLE IF NOT EXISTS `subcategoria` (
  `id` int(255) NOT NULL AUTO_INCREMENT,
  `categoria_url` char(255) COLLATE utf8_unicode_ci NOT NULL,
  `subcategoria_url` char(255) COLLATE utf8_unicode_ci NOT NULL,
  `temporada` int(3) NOT NULL,
  `nome` char(255) COLLATE utf8_unicode_ci NOT NULL,
  `cat` int(255) NOT NULL,
  `semana` enum('Selecionar Semana','Domingo','Segunda-Feira','Terca-Feira','Quarta-Feira','Quinta-Feira','Sexta-Feira','Sábado') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Selecionar Semana',
  `ativadorOn` enum('ON','OFF') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'OFF',
  `sinopse` text COLLATE utf8_unicode_ci NOT NULL,
  `status` enum('Completo','Incompleto','Andamento','Pausado','Lançamento') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Andamento',
  `genero` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `genero_url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `numeroMedias` int(255) NOT NULL DEFAULT '0',
  `autor` char(20) COLLATE utf8_unicode_ci NOT NULL,
  `acessos` int(255) NOT NULL,
  `arquivo_nome` varchar(355) COLLATE utf8_unicode_ci NOT NULL,
  `arquivo_tipo` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `arquivo_data_cad` date NOT NULL,
  `arquivo_hora_cad` time NOT NULL,
  PRIMARY KEY (`id`),
  KEY `colunasIndexadas` (`id`,`cat`,`categoria_url`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
  • It seems to me you have a database normalization problem. If you change the name of a subcategory or its url for example, you would need to update the entire category table with the new data. In this case we would have a relationship 1 to N. If you want to use a category aligned to more than one scrap, that is a relation N to N, you would need an auxiliary table to solve this situation by grouping the id of the category table and the id of the subcategory table. So you would avoid duplicity if there is already a match even if you exit the application and return

  • @Rodrigo posts the code of his pages, the registration and which inserts the data in the bank.

  • Do not rush to accept the first answer as absolute, it is not always the solution to your problem, the correct is to put as Unique the ( id of the category + name subcategory ), and treat the error "23000" example: UNIQUE INDEX nome_da_unique (cat, nome)

2 answers

3

In the Unique Key function, you can put as many fields as you want to keep in the table, the row as being Única

Example with more than one field

UNIQUE KEY `nomeIdUnique` (`nome`,`cat`)

On your table

CREATE TABLE `subcategoria` (
  `id` int(255) NOT NULL AUTO_INCREMENT,
  `categoria_url` char(255) COLLATE utf8_unicode_ci NOT NULL,
  `subcategoria_url` char(255) COLLATE utf8_unicode_ci NOT NULL,
  `temporada` int(3) NOT NULL,
  `nome` char(255) COLLATE utf8_unicode_ci NOT NULL,
  `cat` int(255) NOT NULL,
  `semana` enum('Selecionar Semana','Domingo','Segunda-Feira','Terca-Feira','Quarta-Feira','Quinta-Feira','Sexta-Feira','Sábado') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Selecionar Semana',
  `ativadorOn` enum('ON','OFF') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'OFF',
  `sinopse` text COLLATE utf8_unicode_ci NOT NULL,
  `status` enum('Completo','Incompleto','Andamento','Pausado','Lançamento') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'Andamento',
  `genero` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `genero_url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `numeroMedias` int(255) NOT NULL DEFAULT '0',
  `autor` char(20) COLLATE utf8_unicode_ci NOT NULL,
  `acessos` int(255) NOT NULL,
  `arquivo_nome` varchar(355) COLLATE utf8_unicode_ci NOT NULL,
  `arquivo_tipo` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `arquivo_data_cad` date NOT NULL,
  `arquivo_hora_cad` time NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `nomeIdUnique` (`nome`,`cat`),
  KEY `colunasIndexadas` (`id`,`cat`,`categoria_url`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

This way it will never repeat itself, and if you are using PDO, you do not need to send the error to the log file

try {

} catch (PDOException $e) {
    if ($e->getCode !== 23000) {
        //log
    }
}
  • In case I’m using Mysql.

  • @Rodrigo, PDO is a PHP database abstraction library, such as mysql_* and mysqli_*

  • I know tell already I’m passing everything to mysqli

2


  1. You can use access tokens.
  2. a 1 and 2 pages must have session_start(); at the beginning and pass a token with a randomly generated number or code, making it impossible to access the page again without going to 1 page!
  3. A 1 page and where the user ve adds things to the cart (by exeplo" on the 2 page where the add process occurs in the database!

How to generate the token in 1 page?

<?php
session_start();
function geraToken()
{
return rand(1, 1000)."".rand(1, 1000); // Gerar numeros aleatorios
}
$_SESSION['token'] = geraToken();
?>

How to use token on 2 page?

<?php
session_start();
if(!isset($_SESSION['token']))
{
    die("Acesso negado!");
}
//Adicione aki o resto da 2 pagina...
//...

// NO fim do processo adicione isto
$_SESSION['token'] = ""; // Fazendo a token invalida e impedindo o refresh da pagina!
?>
  • In case to be able to perform the save and mandatory in my If you pass through the adder first to go to the save certain case of refrash on the saved page this function returns access denied right ? And the part to add at the end would be in case after the right Insert code ?

  • right ;) the token is removed after the Insert process

  • Tie this way then it devalidates the number generated in the Rand I understood now grateful for the help. Only in case I use Sesssion for leasing but then I would only be validating only the right token ?

  • @Hardcorder, it is somewhat unusual, indicate solutions to CSRF to avoid database duplication.

  • @Mandrake But why put -1 vote? I did not understand. if the solution is there working perfectly! And it has security. I not only answered the question as I gave you a hint on how to use Tokens.

  • @Hardcorder, this is not solution to avoid duplication, if it were a select Count, or table index, you had my +1, but this ai was never solution and will never be!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.