붉은거위 노트 (redgoose note)

hex 형태로 된 db값을 문자로 변경 스크립트

Nest
Development
Category
PHP
Hit
657
Star
1

특정필드에 문자열로 hex값이 있으면 문자로 변환시켜주는 php스크립트.
mysql 데이터 호출은 pdo이니 주의!!

<?php
header("Content-Type: text/plain; charset=utf8");
//header("Content-Type: text/html; charset=euc-kr");

// set database
$dbUser = '{USER_NAME}';
$dbName = '{DATABASE_NAME}';
$dbPassword = '{PASSWORD}';

// 변환시킬 테이블
$table = '{TABLE}';
// 변환시킬 필드의 이름. `id`필드는 꼭 필요함
$field = 'id,{FIELD_NAMES}';
// 치환실행 여부
$run = false;

try
{
  $db = new PDO('mysql:dbname='.$dbName.';host=localhost', $dbUser, $dbPassword);
}
catch (PDOException $e)
{
  echo 'Connection failed: '.$e->getMessage();
  $db = null;
  die();
}

/**
 * hex to string
 *
 * @param string $hex
 * @return string
 */
function hextostr($hex)
{
  $str='';
  for ($i=0; $i < strlen($hex)-1; $i+=2)
  {
    $str .= chr(hexdec($hex[$i].$hex[$i+1]));
  }
  // `euc-kr`문자셋을 `utf-8`으로 변환
  $str = iconv('EUC-KR', 'UTF-8', $str);
  return $str;
}

// get index
$qry = $db->query('select '.$field.' from '.$table);
$result = $qry->fetchAll(PDO::FETCH_ASSOC);

// replace area
foreach($result as $k=>$o)
{
  $qry_src = '';
  foreach($o as $kk=>$oo)
  {
    if ($oo && $kk != 'id')
    {
      $str = $oo;
      $str = str_replace('0x', '', $str);
      $str = hextostr($str);
      $qry_src .= ",$kk=\"$str\"";
    }
    //echo "$kk: $oo ----- $str\n";
  }

  if ($qry_src)
  {
    $qry_src = preg_replace('/^,/', '', $qry_src);
    $qry = 'update '.$table.' set '.$qry_src.' where id='.(int)$o['id'].';';
    echo $qry;
  }

  // run replace script
  if ($run)
  {
    if ($db->query($qry))
    {
      echo "\nsuccess";
    }
    else
    {
      echo "\nfail";
    }
  }

  echo "\n=============\n\n";
}