diff --git a/syntax.php b/syntax.php index ac3f9b7..f379b68 100644 --- a/syntax.php +++ b/syntax.php @@ -79,53 +79,59 @@ class syntax_plugin_sqlquery extends DokuWiki_Syntax_Plugin { $password = $this->getConf('password'); // connect to database - $link = mysqli_connect($data['host'], $user, $password, $data['db']); - if (!$link) { - $renderer->doc .= "
" . mysqli_connect_error() . "
"; + $dsn = "mysql:host={$data['host']};dbname={$data[db]}"; + try { + $dbh = new PDO($dsn, $user, $password); + } catch (PDOException $e) { + $renderer->doc .= "
Unable to connect ro database:" . $e->getMessage() . "
\n"; 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 - $result = mysqli_query($link, $data['query']); - if ($result) { - - // get the number of fields in the table - $fieldcount = mysqli_num_fields($result); + try { + $result = $dbh->query($data['query']); + } catch (PDOException $e) { + $renderer->doc .= "
Error in query:" . $e->getMessage() . "
\n"; + return true; + } - // build a table - $renderer->doc .= '' . "\n"; + // get the number of fields in the table + $fieldcount = $result->columnCount(); - // build the header section of the table - $renderer->doc .= ""; - while ($fieldinfo = mysqli_fetch_field($result)) { - $renderer->doc .= ""; - } - $renderer->doc .= "\n"; - - // build the contents of the table - $renderer->doc .= "\n"; - while ($row = mysqli_fetch_row($result)) { - $renderer->doc .= ""; - for ( $i = 0; $i < $fieldcount; $i++ ) { - $renderer->doc .= ""; - } - $renderer->doc .= "\n"; - } + // build a table + $renderer->doc .= '
"; - $renderer->doc .= $fieldinfo->name; - $renderer->doc .= "
"; - $renderer->doc .= $row[$i]; - $renderer->doc .= "
' . "\n"; - // finish the table - $renderer->doc .= "
\n"; + // build the header section of the table + $renderer->doc .= ""; - } else { - // error in query - $renderer->doc .= "
" . mysqli_error($link) . "
"; + for ($i = 0; $i < $fieldcount; $i++) { + $meta = $result->getColumnMeta($i); + $renderer->doc .= ""; + $renderer->doc .= $meta['name']; + $renderer->doc .= ""; + } + $renderer->doc .= "\n"; + + // build the contents of the table + $renderer->doc .= "\n"; + foreach ($result as $row) { + $renderer->doc .= ""; + for ( $i = 0; $i < $fieldcount; $i++ ) { + $renderer->doc .= ""; + $renderer->doc .= $row[$i]; + $renderer->doc .= ""; + } + $renderer->doc .= "\n"; } - mysqli_close($link); + // finish the table + $renderer->doc .= "\n\n"; + + // Close connection, there is no close() method with PDO :-( + $result = null; + $dbh = null; return true; }