Add Mysql column with increment not to repeat

Asked

Viewed 322 times

0

My intention is to pick up a variable via POST and change its value.

$vem = $_POST['nome'];

if (isset($vem)){

    $vem = 1;
    $vem++;
    $vem = 'campo'.$vem;
}

I will add as column of a table within this change

$vem = $_POST['nome'];

if (isset($vem)){

$vem = 1;
    $vem++;
    $vem = 'campo'.$vem;

$sqli = mysql_query ("ALTER TABLE  grafica ADD $vem varchar(255)")  or die(mysql_error());
if($sqli){

     echo 'salvou '.$vem;
 }

}

So far everything okay! What I need is for him to understand that he already has the spine campo.2 and add the column campo.3

  • Try to get the names of the columns first. Take a look at this reply, in that and in that

  • actually I just need to know if you have the column, the column name I’m changing when comes the POST, type a select and then a query

2 answers

2

update 08/06/2018 22:59

This part is totally expendable and serves no purpose

$vem = 1;
    $vem++;
    $vem = 'campo'.$vem;

for the reasons listed below

  1. it’s pretty obvious that the way it is, the variable $vem will always be campo2
  2. If you want sequence column names there is no reason to enter any number in the field to be sent via post. For example, suppose that the number 8 has been entered and we have the columns field.1, field.2 and field.3 in the table, so the next column to be created is field.4 and the number sent via post has not been used for anything.

This variable $vem from $_POST['nome']; can be, for example, a prefix of the names of the columns to be created, giving margin to create columns with multiple prefixes and sequentially, such as field.1, field.2, etc.. or qqnome.1, qqnome.2, etc...

It is not common to name columns with . and this can cause errors if not treated correctly in the declaration ALTER TABLE. In this case it is essential to wrap the column name with inverted quotes that are nothing more than the crase accent of your keyboard. More details on Schema Object Names

$sql = "ALTER TABLE $table ADD `$nomeProxColuna` varchar(255)";

Proposed code

with Mysqli because mysql_* was discontinued and Column names without .

$vem = $_POST['nome'];

if (isset($vem)){

    $hostname="localhost";  
    $db_user="USUARIO";  
    $db_pw="SENHA";  
    $db_name = "nome_DB";  

    $con = mysqli_connect('localhost',$db_user,$db_pw,$db_name);

    //nome da tabela
    $table = 'artigos';

    /**
    * Obtem os nomes das colunas com prefixo = $vem (vindo do post)
    **/

      $sql = 'DESCRIBE '.$table;
      $result = mysqli_query($con, $sql);

      $rows = array();
      while($row = mysqli_fetch_assoc($result)) {
         //cria array com nomes das colunas que contem a palavra $vem
         $texto = $row['Field'];
         if (strstr($texto, $vem)){;
            $rows[] = $row['Field'];
         }

      }

      /********** caso haja nomes de colunas com prefixo vindo do post
       prepara o nome da proxima coluna *****************************/

      if($rows){
          /*****retorna maior valor do array dado pela parte numérica
          já que a parte anterior à numérica é/são igual(is) *******/

          $maior = max($rows);

         /********próximo nome da coluna********/

         //comprimento da variavel vindo do post
         $len=strlen($vem);

         //pega a parte numérica do nome dado pela variável $maior definida acima
         $proxNum = substr($maior,$len)+1;

         //cria o nome da próxima coluna
         $nomeProxColuna = $vem.$proxNum;

      }else{ 

         //se não existem colunas com prefixo vindo do post cria a primeira

         $nomeProxColuna=$vem."1";

      }

    //  altera a estrutura da tabela acrescentando campos

    $sql = "ALTER TABLE $table ADD `$nomeProxColuna` varchar(255)";

    $incluirColuna = $con->query($sql);
    if ($incluirColuna) {
      echo "coluna criada com sucesso\n";
    } else {
      echo "deu zebra: " . $con->error . "\n";
    }     

}

If column names prefixes will always be the same, just put it as variable value $vem. Example $vem="campo";

and the first lines of the code, for example, are

if (isset($_POST['criarColuna'])) {

   $vem="campo";

and in the form only an input/button, example <input type="submit" name="criarColuna" value="Criar coluna">

  • got it, but no if, as I will add an extra increment, not to give duplicate column and add in the comic with an extra number, ex... was 3, next is 4

  • In this case we return to the right original question?

  • and he did not give echo "there is"...rs does not return me the query

  • If it didn’t happen, it’s because it doesn’t exist!

  • Place a print_r($Rows); and see what returns

1


First of all, I have a few stitches to add:

  1. Column names with . are nothing common
  2. If a table X has several fields in this format (campo1, campo2, campo3), consider normalizing and creating a table X_Campo, where you would have a id, a key to the table X and a column with the value itself.
  3. Try not to use the functions mysql_*, use in place at least the mysqli_. They have been discontinued...

My solution would be this one:

<!DOCTYPE html>
<html>
<pre>
<?php
// conecta no bd
$mysqli = new mysqli("localhost", "root", "", "test");
if ($mysqli->connect_errno) {
  echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;  
} else {
  echo 'conexão: ' . $mysqli->host_info . "\n";

  // primeiro, precisamos saber dos campos da tabela. A query não precisa retornar nada, só precisamos do metadata inicialmente.
  $tableName = 'tabela';
  $res = $mysqli->query("SELECT * FROM tabela WHERE 0");
  if ($res) {
    $numeroNovoCampo = 1;
    $prefixoNovoCampo = 'campo';
    $fields = $res->fetch_fields();
    echo "verificando nomes dos campos pelo prefixo '$prefixoNovoCampo'...\n";
    foreach ($fields as $field) {
      printf("%s\n", $field->name);
      $pos = strpos($field->name, $prefixoNovoCampo);
      if ($pos !== false) {
        $apos = substr($field->name, strlen($prefixoNovoCampo) + $pos);
        echo "encontrou o prefixo, verifica o que está depois ($apos)\n";
        $numero = intval($apos);
        $numeroNovoCampo = max($numeroNovoCampo, $numero+1);
      }
    }
    $sql = "ALTER TABLE $tableName ADD $prefixoNovoCampo$numeroNovoCampo varchar(255)";
    echo "criando campo com nome $prefixoNovoCampo$numeroNovoCampo: $sql\n";
    $altTab = $mysqli->query($sql);
    if ($altTab) {
      echo "campo criado com sucesso\n";
    } else {
      echo "deu um erro? " . $mysqli->error . "\n";
    }
    $res->close();
  } else {
    echo "erro na consulta\n";
  }
}

$mysqli->close();

?>
</pre>
</html>

I created a table to test here and put some campoN just to see how it would look, and I had this exit:

conexão: localhost via TCP/IP
verificando nomes dos campos pelo prefixo 'campo'...
id
id_usuario
usuario
momento
random
valor
campo1
encontrou o prefixo, verifica o que está depois (1)
campo2
encontrou o prefixo, verifica o que está depois (2)
campo3
encontrou o prefixo, verifica o que está depois (3)
criando campo com nome campo4
campo criado com sucesso
  • 1

    perfect, adapted in what I need and worked, obg!

Browser other questions tagged

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