PHP: How to check if there is a field in the table, and if it does not exist, add

Asked

Viewed 43 times

-1

<?php

$servername = "servername ";
$database   = "database   ";
$username   = "username   ";
$password   = "password   ";

$conn       = new mysqli($servername, $username, $password, $database);

if ($conn->connect_error) 
{
  die("Falha na Conexão: " . $conn->connect_error);
}

//echo "Conexão feita com sucesso. <br />";

$sql = ("SHOW TABLES");
$query = $conn->query($sql);
while($row = $query->fetch_array(MYSQLI_NUM)){
    $rows[] = $row;
}

foreach($rows as $r){
    $query = ("SHOW COLUMNS FROM {$r[0]}");
    $search     = $conn->query($query);

    $created    = false;
    $updated    = false;
    $deleted    = false;
    
    while($row = $search->fetch_array(MYSQLI_NUM)){
        $ro[] = $row;
    }

    foreach($ro as $find) {
        if($find[0]  == 'created_at') {
            $created = true; 
        }
            
        if($find[0]  == 'updated_at' ) {
            $updated = true; 
        }
            
        if($find[0]  == 'deleted_at') {
            $deleted = true; 
        }
    }

    if($created == false) {
        //echo 'created </br>';
        $sql    = ("ALTER TABLE {$r[0]} ADD created_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP");
        $conn->query($sql);
        $created = true; 
    }

    if($updated == false) {
         //echo 'updated </br>';
         $sql    = ("ALTER TABLE {$r[0]} ADD updated_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP");
         $conn->query($sql);
         $updated = true; 
    }

    if($deleted == false) {
        //echo 'deleted </br>';
        $sql    = ("ALTER TABLE {$r[0]} ADD deleted_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP");   
        $conn->query($sql);     
        $deleted = true; 
    }
}

$conn->close();

?>

1 answer

1

You can do it this way:

$sql =  ("IF NOT EXISTS( SELECT NULL
        FROM INFORMATION_SCHEMA.COLUMNS
        WHERE table_name = 'NOME DA TABELA'
        AND table_schema = 'NOME DO BANCO'
        AND column_name = 'NOME DA COLUNA')  THEN

  ALTER TABLE tabela ADD created_at NOT NULL CURRENT_TIMESTAMP
  ADD updated_at NOT NULL CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP
  ADD deleted_at NULL
END IF;");
  • I changed the code to leave it the way it would run, it stops of error, but does not make the update, I will post the new code.

  • @Alexandresilveira, you can put all the code inside an sql command and test please, and the columns "updated_at" and "deleted_at", are also generated dynamically, or just updated ?

  • I just tested, not the error, but it also doesn’t update. "updated_at" and "deleted_at" columns are generated dynamically as well.

  • mysql_query allows IF in the query?

  • I took a look at the doc, there is no example of IF in the query

Browser other questions tagged

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