Changed database interface from mysqli to PDO

multidb
Thomas Hooge 6 years ago
parent f3c949dcb0
commit b852dec610
  1. 80
      syntax.php

@ -79,53 +79,59 @@ class syntax_plugin_sqlquery extends DokuWiki_Syntax_Plugin {
$password = $this->getConf('password'); $password = $this->getConf('password');
// connect to database // connect to database
$link = mysqli_connect($data['host'], $user, $password, $data['db']); $dsn = "mysql:host={$data['host']};dbname={$data[db]}";
if (!$link) { try {
$renderer->doc .= "<pre>" . mysqli_connect_error() . "</pre>"; $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
$renderer->doc .= "<pre>Unable to connect ro database:" . $e->getMessage() . "</pre>\n";
return true; return true;
} }
mysqli_set_charset($link, "utf8"); $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_NUM);
// run query // run query
$result = mysqli_query($link, $data['query']); try {
if ($result) { $result = $dbh->query($data['query']);
} catch (PDOException $e) {
// get the number of fields in the table $renderer->doc .= "<pre>Error in query:" . $e->getMessage() . "</pre>\n";
$fieldcount = mysqli_num_fields($result); return true;
}
// build a table // get the number of fields in the table
$renderer->doc .= '<table id="sqlquerytable" class="inline">' . "\n"; $fieldcount = $result->columnCount();
// build the header section of the table // build a table
$renderer->doc .= "<thead><tr>"; $renderer->doc .= '<table id="sqlquerytable" class="inline">' . "\n";
while ($fieldinfo = mysqli_fetch_field($result)) {
$renderer->doc .= "<th>";
$renderer->doc .= $fieldinfo->name;
$renderer->doc .= "</th>";
}
$renderer->doc .= "</tr></thead>\n";
// build the contents of the table
$renderer->doc .= "<tbody>\n";
while ($row = mysqli_fetch_row($result)) {
$renderer->doc .= "<tr>";
for ( $i = 0; $i < $fieldcount; $i++ ) {
$renderer->doc .= "<td>";
$renderer->doc .= $row[$i];
$renderer->doc .= "</td>";
}
$renderer->doc .= "</tr>\n";
}
// finish the table // build the header section of the table
$renderer->doc .= "</tbody></table>\n"; $renderer->doc .= "<thead><tr>";
} else { for ($i = 0; $i < $fieldcount; $i++) {
// error in query $meta = $result->getColumnMeta($i);
$renderer->doc .= "<pre>" . mysqli_error($link) . "</pre>"; $renderer->doc .= "<th>";
$renderer->doc .= $meta['name'];
$renderer->doc .= "</th>";
}
$renderer->doc .= "</tr></thead>\n";
// build the contents of the table
$renderer->doc .= "<tbody>\n";
foreach ($result as $row) {
$renderer->doc .= "<tr>";
for ( $i = 0; $i < $fieldcount; $i++ ) {
$renderer->doc .= "<td>";
$renderer->doc .= $row[$i];
$renderer->doc .= "</td>";
}
$renderer->doc .= "</tr>\n";
} }
mysqli_close($link); // finish the table
$renderer->doc .= "</tbody>\n</table>\n";
// Close connection, there is no close() method with PDO :-(
$result = null;
$dbh = null;
return true; return true;
} }