This question is about parsing in PHP, not how to migrate MySQLi to PDO.
I want to migrate some old code from MySQLi to PDO. The site has over 400 string query statements. I want to revise the code to use prepared statements.
I.e., convert
$query = 'SELECT * from table where x='.$x.' and y > '.$y.' or (z<= 35 and auth like "%ed")'
$result = $conn->query($query);
to
$query = 'SELECT * from table where x = ? and y > ? or (z <= ? and auth like ?)';
$stmt = $conn->prepare($query);
$stmt->bind_param($x, $y, $35, '%ed');
$stmt->execute();
I started out by parsing the $query string to find 'where', then looking for 'and' to separate parameter/value pairs, etc.
Edit: This is basic code to read lines in a file (in this case, a .php file):
$fn = fopen("myfile.php","r+");
while(!feof($fn)) {
$line = fgets($fn);
if (strpos($line, 'select'){
// add parse code here
};
}
when finding a line with a query statement, the line will be a literal string something like this:
($line = ) $query = 'select * from menu where authlvl>0 and authlvl<=' . $authlvl . ' order by title';
Then, the code to parse may look something like this:
$where = substr($line, strpos($line, 'where') + 5);
$pair = array();
$j = 0;
$st = 0;
if (strpos(substr($where, $st), 'and', $st)) > 0){
while (($and = strpos(substr($where, $st), 'and', $st)) > 0){
$pair[$j] = trim(substr($where, $st, $and - 1));
$pair[$j+1] = trim(substr($where, $and + 4));
$st = $and;
$j++;
}
}
$ops = array(' ', '<', '>', '=');
(find operators to identify parameters and values for each pair...)
This intuitively is not efficient. Is there a better way to parse the $query string to find the parameters than this? Note that there may be 'order by', etc. in the string that should just append after finding the parameters.