k1ng440
2/5/2013 - 10:28 AM

PHP: mysql_* to PDO prepare

PHP: mysql_* to PDO prepare

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>mysql_ To PDO converter</title>
</head>
<pre>
<?php
function mkpdostatement($query, $with) {
    $arr = array();
    $array = '';
    $count = 0;
    foreach($with as $k => $w) {
        $pdobind = str_replace(array("'", '"', "$", 'this->'), array("", '', ":", ''),  $w);
        if(in_array($pdobind, $arr)) {
            $count++;
            $arr[$k] = $pdobind . $count;
        } else {
            $arr[$k] = $pdobind;
        }


        $array .= "'{$arr[$k]}' => ".str_replace(array("'", '"'), "", $w).", ";

    }
    return '"'. str_replace($with, $arr, $query) . '", array(' . rtrim($array, ", ") .")";
}

$result = '';
if(isset($_POST['input']) === true) {
    $input = $_POST['input'];
    preg_match_all("/('\\$[^']+')/", $input, $matches);
    preg_match_all('/("\\$[^"]+")/', $input, $matches2);
    $array = array_merge($matches[1], $matches2[1]);

    $result = mkpdostatement($input, $array);
}
?>
</pre>


<body><br /><br /><br />
<form id="form1" name="form1" method="post" action="" style="width:1200px; margin: 0 auto;">
    <p><?php echo @$_POST['input']; ?></p>
  <p>
    <label for="input"></label>
    <textarea name="input" cols="200" style="width:100%;" rows="10" id="input"><?php echo $result; ?></textarea>
  </p>
  <p style="text-align: right;">
    <input type="submit" name="button" id="button" value="Submit" />
  </p>
</form>
</body>
</html>