Saturday, 27 June 2015

PHP: Converts enum fields from mysql into an array

enumExplode.php

<?php
function enumExplode($tableCol) {
    $expl = explode(".", $tableCol);
    $table = $expl[0];
    $column = $expl[1];
    $query = "show columns from {$table} where field = :column";
    $res = querydb($query, array("column" => $column), $error);
    $enum = $res[0]['Type'];
    $enum = explode(",", str_replace(array("enum(", ")", "'"), "", $enum));
    return $error ?: $enum;
}
/**
 *  queryDB
 *  -------
 *  @param string  sql query
 *  @param array   values for query
 *  @param array   errors returned
 *
 */
function queryDB($query, $values = array(), &$errors = null) {
    $pdo = new PDO(DBINFO, DBUSER, DBPASS);
    $stmt = $pdo->prepare($query);
    $stmt->execute($values);
    $res = $stmt->fetchAll(PDO::FETCH_ASSOC);
    $errorInfo = $stmt->errorInfo();
    $errors = empty($errorInfo[2]) ? false : $stmt->errorInfo();
    $stmt->closeCursor();
    return $res;
}
?>

gistfile1.php
<?php
querydb("select * where id = :id and name = :name", array("id" => $id, "name" => $name), $error);
$query = "select * where id = :id and name = :name";
$values = array("id" => $id,"name" => $name);
$results = querydb($query, $values, $err);

/*
$results = array(
  0 => array(
    "name" => name,
    "id" => id
    ),
  1 => array(
    "name" => name,
    "id" => id
    )
  );
*/
?>

0 comments:

Post a Comment