function __construct($id, $melding = "", $file = "", $lijn = "", $user = "") { $this->db = DB::getDB(); $this->id = $id; if ($this->id == "") { // nieuwe fout $this->melding = $melding; $this->file = $file; $this->lijn = $lijn; $this->user = $user; $statement = $this->db->prepare("INSERT INTO error (datum, melding, file, lijn, user) VALUES (NOW(), ?, ?, ?, ?)"); $statement->bind_param('ssss', $this->melding, $this->file, $this->lijn, $this->user); $statement->execute(); $this->id = $this->db->insert_id; $statement->close(); } else { if (!is_numeric($id) || $id < 1) { throw new BadParameterException(); } $statement = $this->db->prepare("SELECT datum, melding, file, lijn, user FROM error WHERE id = ?"); $statement->bind_param('i', $this->id); $statement->execute(); $statement->bind_result($this->datum, $this->melding, $this->file, $this->lijn, $this->user); $statement->fetch(); $statement->close(); } }
/** * Закрывает конект к БД * */ public static function Close() { $db = DB::getDB(); if ($db->conn instanceof \ADOConnection) { $db->conn->Close(); } }
/** * Статический метод для изменения данных у пользователя * @param array $data Массив данных, которые нужно обновить * @param string|int $userId Индекнтификатор пользователя, данные которого нужно изменить * @return bool Вернет истину если все удачно обновлено или ложь если не удалось обновить */ public static function changeUser($data, $userId) { $params = array_values($data); array_push($params, $userId); $updateData = array_keys($data); $db = DB::getDB(); return $db->update('users', $updateData, ['id' => '='], $params); }
public static function findSomeValidActGoods($actId, $beginTime, $endTime, $nextId, $size) { if (empty($actId) || $size <= 0) { return array(); } $ret = DB::getDB()->fetchSome('m_activity_goods', '*', array('act_id', 'begin_time >=', 'end_time <', 'id>'), array($actId, $beginTime, $endTime, $nextId), array('and', 'and', 'and'), array('id'), array('asc'), array($size)); return $ret === false ? array() : $ret; }
protected function aud($_sql) { $_db = DB::getDB(); $_db->query($_sql); $_affected_rows = $_db->affected_rows; DB::unDB($_result = null, $_db); return $_affected_rows; }
protected function aud($sql) { $db = DB::getDB(); $result = $db->query($sql); $affected_rows = $db->affected_rows; DB::unDB($result, $db); return $affected_rows; }
protected function _insert_id($_sql) { $_db = DB::getDB(); $_db->query($_sql); $_mid = $_db->insert_id; $_result = null; DB::unDB($_result, $_db); return $_mid; }
private function More_Agree() { $arr = $_POST['state']; foreach ($arr as $key => $value) { $sql .= "update comment set state ='{$value}' where id='{$key}';"; } $mysqli = DB::getDB(); $mysqli->multi_query($sql); Tool::alertLocation(null, PREV_URL); }
public static function getTypeImages($sid) { $db = DB::getDB(); $sql = "select * from images where sid='{$sid}' order by date desc limit 0,10"; $res = $db->query($sql); while (!!($rows = $res->fetch_object())) { $resArr[] = $rows; } DB::unDB($res, $db); return $resArr; }
private static function getSomeInOutBill($userId, $type, $nextId, $size) { if (empty($userId) || $size <= 0) { return array(); } $nextId = (int) $nextId; if ($nextId > 0) { $ret = DB::getDB()->fetchSome('u_bill', '*', array('user_id', 'bill_type', 'id<'), array($userId, $nextId), array('and', 'and'), array('id'), array('desc'), array($size)); } else { $ret = DB::getDB()->fetchSome('u_bill', '*', array('user_id', 'bill_type'), array($userId), array('and'), array('id'), array('desc'), array($size)); } return empty($ret) ? array() : $ret; }
protected function all($_sql) { $_db = DB::getDB(); //获取结果集 $_result = $_db->query($_sql); //打印出所有数据 $_html = array(); while ($_objects = $_result->fetch_object()) { $_html[] = $_objects; } DB::unDB($_result, $_db); return $_html; }
public function Date_Exist() { $this->id = $_GET['id']; $sql = "select * from manage,manage_level where manage.level='{$this->id}'"; $mysqli = DB::getDB(); $result = $mysqli->query($sql); if ($result->fetch_object()) { return true; } else { return false; } DB::unDB($result, $mysqli); }
protected function all($sql) { $mysqli = DB::getDB(); if (!mysqli_connect_errno()) { if (!($result = $mysqli->query($sql))) { echo $mysqli->error; } else { $result = $mysqli->query($sql); } } else { echo '数据库链接失败'; } $html = array(); while (!!($objects = $result->fetch_object())) { $html[] = $objects; } DB::unDB($result, $mysqli); return $html; }
protected function __construct($registry) { if (!isset($registry)) { $registry = new Registry(); $registry->set('db', DB::getDB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE)); } $this->registry = $registry; if (is_null(static::$newConfig)) { static::$newConfig = $this->registry->get('config'); } $this->config = static::$newConfig; if (is_null(static::$db)) { static::$db = $this->registry->get('db'); } if (is_null(static::$loader)) { static::$loader = $this->registry->get('load'); } $this->load = static::$loader; $this->log = $this->registry->get("log"); }
function after_login($openid, $userInfo) { // TODO:业务逻辑自行补充 // 获取数据库连接 $mysqli = DB::getDB(); if ($mysqli->connect_error) { die(json_encode(array("error" => "数据库连接失败"))); } $insert_update = "insert into user_info (open_id, name, head_icon, score) values (?, ?, ?, 0) on duplicate key update name = VALUES(name), head_icon = VALUES(head_icon)"; $stmt = $mysqli->prepare($insert_update); if (!$stmt) { die(json_encode(array("error" => "数据库连接失败"))); } $stmt->bind_param("sss", $v_open_id, $v_name, $v_head_icon); $v_open_id = $open_id; $v_name = $user_info["nickname"]; $v_head_icon = $user_info["headimgurl"]; $stmt->execute(); if ($stmt->errno) { die(json_encode(array("error" => "注册用户失败,错误代码:" . $stmt->errno))); } $stmt->close(); }
header('Access-Control-Allow-Origin:*'); // 查询排行榜 require_once "db.php"; // 从请求中获取参数 $rid = $_REQUEST["rid"]; $token = $_REQUEST["token"]; $score = $_REQUEST["score"]; // if (!isset($rid) || !isset($score)) { // die(json_encode(array( // "error" => "参数有误" // ))); // } // 这里可以使用token进行验证,是否允许调用存储数据库 // 这里不做实现 // 查询排行榜 $mysqli = DB::getDB(); $top = array(); $user = array(); // 获取前100的用户数据 $sql = "SELECT open_id as rid, name, score, head_icon FROM user_info where score > 0 ORDER BY score desc, update_time asc limit 100"; $result = $mysqli->query($sql); if ($result) { while ($obj = $result->fetch_object()) { array_push($top, $obj); } $result->close(); } $sql = "SELECT open_id, name, score, head_icon FROM user_info where open_id = '{$rid}'"; $result = $mysqli->query($sql); if ($result) { $user = $result->fetch_object();
foreach ($waarden as $key => $value) { if (sizeof(explode("|", $velden[$key])) > 1) { $e = explode("|", $velden[$key]); $q .= "(" . $e[0] . " LIKE '%" . $value . "%' OR " . $e[1] . " LIKE '%" . $value . "%') AND "; } else { $q .= $velden[$key] . " LIKE '%" . $value . "%' AND "; } } $q = substr($q, 0, -6); } $q .= " ORDER BY datum DESC"; $_SESSION["query"] = $q; //eerste een query voor het aantal resultaten $statement = DB::getDB()->prepare($q); $statement->execute(); $statement->store_result(); $paginering['aantal_rijen'] = $statement->num_rows; $q .= " LIMIT {$vanaf}, {$AANTAL_PER_PAGINA}"; $lijst = array(); $statement = DB::getDB()->prepare($q); $statement->execute(); $statement->store_result(); $statement->bind_result($id); while ($statement->fetch()) { $h = new Herstelformulier($id); $lijst[] = $h->toArray(); } $statement->close(); $paginering["aantal_paginas"] = ceil($paginering['aantal_rijen'] / $AANTAL_PER_PAGINA); $uitvoer = array($paginering, $lijst); echo json_encode($uitvoer);
public static function update($goodsId, $skuAttr, $skuValue, $data) { if (empty($goodsId) || empty($data)) { return false; } $ret = DB::getDB('w')->update('g_goods_sku', $data, array('goods_id', 'sku_attr', 'sku_value'), array($goodsId, $skuAttr, $skuValue), array('and', 'and'), 1); if ($ret === false) { return false; } self::onUpdateData($goodsId); return $ret > 0; }
<?php require_once './autoload.php'; ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <?php $util = new Util(); $dbc = new DB($util->getDBConfig()); $db = $dbc->getDB(); /* $stmt = $db->prepare("UPDATE test set dataone = :dataone, datatwo = :datatwo where id = :id"); $binds = array( ":id" => $id, ":dataone" => $dataone, ":datatwo" => $datatwo ); if ($stmt->execute($binds) && $stmt->rowCount() > 0) { $result = 'Record updated'; }*/ $login = new Login(); $email = filter_input(INPUT_POST, 'email'); $password = filter_input(INPUT_POST, 'password'); ?>
function isInStudentDatabase($id) { $db = DB::getDB(); $statement = $db->prepare("SELECT userId FROM student WHERE userId = ?"); $statement->bind_param('i', $id); $statement->execute(); $statement->store_result(); return $statement->num_rows == 1; }
public static function search($whereClause, $params, $orderByClause = '', $limitClause = '') { $className = get_called_class(); $fieldGetter = new $className(); $fields = $fieldGetter->getFields(); $DB = DB::getDB(); $selection = ''; $sep = ''; foreach ($fields as $field) { $selection .= $sep . '`' . $field['sql_name'] . '`'; $sep = ', '; } $tableName = strtolower($className); $tableName = Fields::getSQLTableName($tableName); $query = 'SELECT ' . $selection . ' FROM ' . $tableName . ' WHERE ' . $whereClause; if (!empty($orderByClause)) { $query .= ' ORDER BY ' . $orderByClause; } if (!empty($limitClause)) { $query .= ' LIMIT ' . $limitClause; } if (self::SEARCH_QUERY_DEBUG) { echo $query . "<br/>"; } $prep = $DB->prepare($query); foreach ($params as $param) { $prep->bindValue($param['id'], $param['value'], isset($param['type']) ? intval($param['type']) : PDO::PARAM_STR); if (self::SEARCH_QUERY_DEBUG) { echo 'Binding value ' . $param['value'] . ' to ' . $param['id'] . "<br />"; } } if (self::SEARCH_QUERY_DEBUG) { echo "<br />"; } $prep->execute(); $data = $prep->fetchAll(); self::reportSqlBugIfExists($prep->errorInfo()); if (!count($data)) { return array(); } $result = array(); foreach ($data as $elt) { $t = new $className(); foreach ($fields as $field) { $t->set($field['name'], $elt[$field['sql_name']]); } $t->setFromSql(); $result[] = $t; } return $result; }
} return true; }); // Registry $registry = new Registry(); // Cache $cache = new Cache(); $registry->set('cache', $cache); // Loader $loader = new Loader($registry); $registry->set('load', $loader); // Config $config = new Config(); $registry->set('config', $config); // Database $db = DB::getDB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE); $registry->set('db', $db); // Store if (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == '1')) { $store_query = $db->query("\r\n\t\tSELECT * FROM store WHERE `ssl` = :url\r\n\t\t", [':url' => 'https://' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\') . '/']); } else { $store_query = $db->query("\r\n\t\tSELECT * FROM store WHERE `url` = :url\r\n\t\t", [':url' => 'http://' . str_replace('www.', '', $_SERVER['HTTP_HOST']) . rtrim(dirname($_SERVER['PHP_SELF']), '/.\\') . '/']); } if ($store_query->num_rows) { $config->set('config_store_id', $store_query->row['store_id']); } else { $config->set('config_store_id', 0); } // Settings $settingsRows = $cache->get('setting.' . $config->get('config_store_id')); if (is_null($settingsRows)) {
<?php require_once '../smarty.inc'; require_once '../db.inc'; if (empty($_GET['no'])) { $smarty->assign('pageError', true); } else { // アンケートの名前を引き出す $sql = "SELECT * FROM inquiry_question WHERE id = :id"; $pre = DB::getDB()->prepare($sql); $pre->bindValue(':id', $_GET['no']); $pre->execute(); $name = $pre->fetchAll(); // 表示するアンケート番号からアンケートを引き出す $sql = "SELECT * FROM inquiry_answer WHERE id = :id ORDER BY count ASC"; $pre = DB::getDB()->prepare($sql); $pre->bindValue(':id', $_GET['no']); $pre->execute(); $questions = $pre->fetchAll(); if (isset($questions[0]) == true) { $smarty->assign('pageError', false); // 質問数 $smarty->assign('num', sizeof($questions)); // アンケートNo $smarty->assign('no', $_GET['no']); // アンケートタイトル $smarty->assign('name', $name[0]['title']); // 質問内容 $smarty->assign('questions', $questions); } else { $smarty->assign('pageError', true);
/** * Статический метод для добавления баннера * @param array|string $data Принимает поле или массив полей, значения которых нужно вставить в БД * @param array|string $params Принимает начение или массив значений, которые нужно вставить в БД * @return bool Вернет булево значение взависимости от того удалось ли вставить данные в БД */ public static function addBanner($data, $params) { $db = DB::getDB(); return $db->insert('banners', $data, $params); }
} break; case "png": if (!imagepng($image_p, $location)) { throw new RuntimeException('Failed to move uploaded file.'); } break; default: throw new RuntimeException("Error Bad Extension"); break; } imagedestroy($rImg); imagedestroy($image_p); $message = 'File is uploaded successfully.'; } catch (RuntimeException $e) { $message = $e->getMessage(); $status = 500; $location = ''; } header("HTTP/1.1 " . $status . " " . $status_codes[$status]); $response = array("status" => $status, "status_message" => $status_codes[$status], "message" => $message, "location" => $location); $u = new Util(); $db = new DB($u->getDBConfig()); $user_id = $_SESSION['user_id']; $file = $_SESSION['fileName'] . "." . $ext; $sql = $db->getDB()->prepare("INSERT INTO photos (user_id, filename, created)\n VALUES ({$user_id}, '{$file}', NOW())"); //$sql->bindParam(':user_id', $_SESSION['user_id']); //$sql->bindParam(':filename', $fileName); $sql->execute(); echo json_encode($response); die;
public static function findAllValidModule($beginTime, $endTime) { $ret = DB::getDB()->fetchAll('m_goods_module', '*', array('begin_time >=', 'end_time <'), array($beginTime, $endTime), array('and'), array('sort'), array('desc')); return $ret === false ? array() : $ret; }
function __construct() { $util = new Util(); $dbo = new DB($util->getDBConfig()); $this->setDb($dbo->getDB()); }
/** * Статический метод для добавления рекламы * @param array|string $data Принимает поле или массив полей, значения которых нужно вставить в БД * @param array|string $params Принимает начение или массив значений, которые нужно вставить в БД * @return bool Вернет булево значение взависимости от того удалось ли вставить данные в БД */ public static function addReclama($data, $params) { $db = DB::getDB(); return $db->insert('reclama', $data, $params); }
if (is_uploaded_file($_FILES['userimg']['tmp_name'])) { $imgName = date('YmdHis') . '.' . $ext; if (!move_uploaded_file($_FILES['userimg']['tmp_name'], 'photo/' . $imgName)) { echo '<script>alert("图片上传失败,请重新选择文件!");</script>'; exit; } else { Tool::resizeImg($imgName); //$_SESSION['imgName']=$imgName; } } else { echo '<script>alert("非法进入!");</script>'; } } if ($_GET['action'] == 'upload') { require 'include/DB.class.php'; $db = DB::getDB(); $imgValue = $_POST['feel']; $path = $_POST['name']; $db->query("INSERT INTO images (sid,bigimg_path,img_path,img_value,img_tag,user_tag,date) VALUES ('{$_POST['type']}','{$path}','200x160{$path}','{$imgValue}','{$_POST['img_tag']}','{$_POST['user_tag']}',NOW())"); if ($db->affected_rows) { echo '<script>alert("上传图片成功!");location.href="index.php";</script>'; } else { echo '<script>alert("上传图片失败!");history.back();</script>'; } } ?> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>上传图片</title>
/** * [encodeMysqlString 将要写入mysql的数据中的特殊字符进行转义] * @param [type] $str [要转义的字符串] * @return [type] [转义后的字符串] */ public static function encodeMysqlString($str) { require_once './DB.fun.php'; if (get_magic_quotes_gpc()) { return $str; } else { return DB::getDB()->real_escape_string($str); } }