Last active
August 22, 2018 15:08
-
-
Save Fabio-Ottaviani-Dev/d602e4abd5b9c22a7e24b053ed1b290d to your computer and use it in GitHub Desktop.
if you end up after an csv import with anonymous field name set like COL1.. etc, and you need to rename and sanitize the field name based on the first record that contains the name, this is one (of many) posible solution.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function sanitize($str) | |
{ | |
$str = mb_strtolower($str, 'UTF-8'); | |
$search = array(" - ", " ", "(", ")", "-", "/"); | |
$replace = array("_", '_', "", "", "", "_"); | |
$str = str_replace($search, $replace, $str); | |
return $str; | |
} | |
// Preset | |
$db = "mydb"; | |
$table = "my_table"; | |
$mysqli = new mysqli("localhost", "user", "12345", $db); | |
if ($mysqli->connect_errno) { | |
print_r($mysqli->connect_error); | |
exit(); | |
} | |
$query = "SELECT * FROM $table LIMIT 1"; | |
$result = $mysqli->query($query); | |
while($row = $result->fetch_array(MYSQLI_NUM)) | |
{ | |
$field['name'] = $row; | |
} | |
$result->free(); | |
for ($i = 0; $i < count($field['name']); $i++) | |
{ | |
$fieldId = ($i+1); | |
$sql = "SELECT character_maximum_length AS `maxLength` FROM information_schema.columns WHERE table_name = '$table' AND column_name = 'COL $fieldId'"; | |
$result = $mysqli->query($sql); | |
$row = $result->fetch_assoc(); | |
$sqlAlter = "ALTER TABLE `$table` CHANGE `COL $fieldId` `" . sanitize($field['name'][$i]) . "` VARCHAR(". $row['maxLength'] .") NULL"; | |
$result->free(); | |
$mysqli->query($sqlAlter); | |
} | |
$mysqli->close(); | |
echo "done!"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment