Check if there is a column in the table and if not create it from PHP

0

I have the following problem:

Check if there is a column with the name that goes through a variable and if not create with the column with the name of the variable.

This is what I have tried so far:

$talla= "xg";
if ($fila["codigo_articulo"] no existe){
    ALTER TABLE productos ADD COLUMN IF NOT EXISTS " . $talla. "  not null;
}
    
asked by Cesar 21.02.2017 в 18:33
source

4 answers

2

In MySQL , to know if a column exists you can use SHOW COLUMNS .

Example:

SHOW COLUMNS FROM nombre_tabla WHERE Field = "nombreColumna"

Applied to your code, you could do it like this:

$mysqli = new mysqli('localhost', 'mi_usuario', 'mi_contraseña', 'mi_bd');

$columnName = 'xg';
$result = $mysqli->query("SHOW COLUMNS FROM productos WHERE Field = '$columnName'");

if ($result->num_rows === 0) {
    // Si no encontramos la columna, la agregamos
    $mysqli->query("ALTER TABLE productos ADD '$columnName' tinyint(1) unsigned NOT NULL");
}
    
answered by 21.02.2017 / 23:03
source
1

In MySql the query to add a column is the following:

ALTER TABLE tutabla ADD tucolumna VARCHAR( 255 ) NOT NULL DEFAULT ''

It did not work for you because you were not specifying the VARCHAR column type in this case, and the size 255

You place your query in the PHP variable and send it to the database, assuming you are connected to it.

You can also indicate if you want it to be added after another column of your table.

Example:

ALTER TABLE ejemplo ADD materno VARCHAR(20) AFTER paterno

You will add a column named materno of type VARCHAR (20) after the column named paterno

    
answered by 21.02.2017 в 19:04
0

I think you mean to see if the field exists in your case would do something like:

  $talla= "xg";
    if (!isset($fila["codigo_articulo"])){
        $query = "ALTER TABLE productos ADD COLUMN IF NOT EXISTS " . $talla. "  not null";
    }
    
answered by 21.02.2017 в 19:09
0

I did something similar, I think you need to add the type of variable that is in the database (INT, VARCHAR, LONGTEXT ...). I solved this problem by creating a table with all the types that could be created. That is, first create a table 'fields' with id, name and type that looks like this

___________campos_________
ID         NOMBRE     TIPO
1           xg         VARCHAR(255)

Once this is done, in the function in which you create the new column, before creating it, you make a query like the following:

$sql = "SELECT tipo FROM campos WHERE nombre = 'xg';";

Now we would stay (assuming we are already connected to the bbdd with mysqli)

$resource = $conn -> query($sql);
$campoDetalles = $resource -> fetch_object();
$infoExtra = $campoDetalles -> tipo;

Once this is done, you only have to do what you were doing with the new info

$sql = "ALTER TABLE <la_tabla> ADD ".$variable." ".$infoExtra.";";

I hope it helps you!

    
answered by 21.02.2017 в 18:59