Example #1
0
function SQL($Query)
{
    global $DB;
    $args = func_get_args();
    if (count($args) == 1) {
        $result = $DB->query($Query);
        if ($result == false) {
            dieDb();
        } else {
            if ($result === true) {
                return true;
            } else {
                if ($result->num_rows) {
                    return $result->fetch_all(MYSQLI_ASSOC);
                }
            }
        }
        return null;
    } else {
        if (!($stmt = $DB->prepare($Query))) {
            dieDb();
        }
        array_shift($args);
        //remove $Query from args
        //the following three lines are the only way to copy an array values in PHP
        $a = array();
        foreach ($args as $k => &$v) {
            $a[$k] =& $v;
        }
        $types = str_repeat("s", count($args));
        //all params are strings, works well on MySQL and SQLite
        array_unshift($a, $types);
        call_user_func_array(array($stmt, 'bind_param'), $a);
        $stmt->execute();
        //fetching all results in a 2D array
        $metadata = $stmt->result_metadata();
        $out = array();
        $fields = array();
        if (!$metadata) {
            if ($stmt->affected_rows > 0) {
                return true;
            }
            return null;
        }
        while (null != ($field = mysqli_fetch_field($metadata))) {
            $fields[] =& $out[$field->name];
        }
        $metadata->close();
        call_user_func_array(array($stmt, "bind_result"), $fields);
        $output = array();
        $count = 0;
        while ($stmt->fetch()) {
            foreach ($out as $k => $v) {
                $output[$count][$k] = $v;
            }
            $count++;
        }
        $stmt->free_result();
        return $count == 0 ? null : $output;
    }
}
Example #2
0
require_once "php/include.php";
$currentPage = 0;
$itemsPerPage = 10;
if (isset($_GET["page"]) && !empty($_GET["page"]) && is_numeric($_GET["page"])) {
    $currentPage = $_GET["page"];
}
$res = SQL("SELECT COUNT(*) FROM news_posts");
$itemTotal = $res[0]["COUNT(*)"];
$lastPage = intval($itemTotal / $itemsPerPage);
$skipItems = $currentPage * $itemsPerPage;
if ($lastPage < $currentPage) {
    die("Invalid request");
}
$items = SQL("SELECT title, author, date, content FROM news_posts\n                    ORDER BY date DESC LIMIT ? OFFSET ?", $itemsPerPage, $skipItems);
if ($items == null) {
    dieDb($mysqli);
}
?>
<!DOCTYPE html>
<html>
<head>
    <?php 
require "php/head.php";
?>
</head>
<body>
<?php 
require "php/header.php";
?>
<div id="main">
    <h2><?php