<?php
class tinyIntSetUp
{
private $previousTableName = [];
private $tables = [];
private $sqls = [];
private $dbName = 'yellow';
private $db;
function __construct(PDO $db) {
$this->db = $db;
}
public function getTables()
{
$sql = "SHOW TABLES FROM $this->dbName";
$result = $this->db->query($sql);
while ($row = $result->fetch()) {
$tables[] = $row[0];
}
return $tables;
}
public function runDbUpdate(array $tables)
{
$callbackFields = function($tableName, $tableField){
if(!empty($tableName)){
$this->previousTableName = $tableName;
$sqlDataType = $this->__buildSchemaSql($tableName, $tableField);
$sqlToAlter = $this->__buildAlterSql($tableName, $tableField);
}else{
$sqlDataType = $this->__buildSchemaSql($this->previousTableName, $tableField);
$sqlToAlter = $this->__buildAlterSql($this->previousTableName, $tableField);
}
$result = $this->db->query($sqlDataType);
$row = $result->fetch();
if($row['data_type'] === 'tinyint'){
if($this->db->query($sqlToAlter)){
var_dump($sqlToAlter);
}
}
};
$callbackTable = function($tableName) use($callbackFields){
$sql = "DESCRIBE $tableName";
$result = $this->db->query($sql);
$tableFields = $result->fetchAll(PDO::FETCH_COLUMN);
return array_map($callbackFields, array_values([$tableName]), $tableFields);
};
array_map($callbackTable, $tables);
}
//build the query to get the data type from each field.
private function __buildSchemaSql($tableName, $tableField)
{
$sql = "select data_type from information_schema.columns where table_name='" . $tableName . "' and column_name='" . $tableField . "'";
//$sql .= " and table_schema='". $this->dbName ."';";
return $sql;
}
private function __buildAlterSql($tableName, $tableField)
{
return "ALTER TABLE " .$tableName . " MODIFY COLUMN " . $tableField . " TINYINT(5)";
}
}
$connection = new PDO('mysql:host=localhost; dbname=yellow; charset=utf8', 'root', 'root');
$tinyClass = new tinyIntSetUp($connection);
$tables = $tinyClass->getTables();
$tinyClass->runDbUpdate($tables);