コード例 #1
0
ファイル: del.php プロジェクト: jjling2011/sams
function del_imgs($kw)
{
    if (strlen(trim($kw)) <= 0) {
        return "";
    }
    $db = new MySQLi(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($db->connect_error) {
        return "";
    }
    echo "<table class='table'><tr><th class='text-center'>序号</th><th class='text-center'>删除文件</th>";
    echo "<th class='text-center'><button class='btn btn-danger btn-xs' onclick='self_close();' >关闭</button></th></tr>";
    $ps = explode(",", $kw);
    $count = 0;
    $res = null;
    foreach ($ps as $p) {
        if (strpos($p, "img/") !== 0) {
            continue;
        }
        if (!file_exists($p)) {
            continue;
        }
        $count++;
        $sql = "delete from " . TB_PIC . " where url='" . $p . "'";
        echo "<tr><td class='text-center'>{$count}</td><td>{$p}</td>";
        $res = $db->prepare($sql);
        $res->execute();
        unlink($p);
        if ($res) {
            echo "<td class='text-center'>Success</td></tr>";
        } else {
            echo "<td class='text-center'>Fail</td></tr>";
        }
    }
    echo "</table>";
}
コード例 #2
0
 /**
  * {@inheritdoc}
  */
 public function setUp()
 {
     parent::setUp();
     $this->addToContainer('link', function ($c) {
         $db_host = $this->getTestMySqlConnectionParam('host', 'localhost');
         $db_port = $this->getTestMySqlConnectionParam('port', 3306);
         $db_user = $this->getTestMySqlConnectionParam('user', 'root');
         $db_pass = $this->getTestMySqlConnectionParam('pass', '');
         $db_name = $this->getTestMySqlConnectionParam('database', $this->getTestMySqlDatabaseName($c['app_name']));
         $link = new \MySQLi("{$db_host}:{$db_port}", $db_user, $db_pass);
         if ($link->connect_error) {
             throw new RuntimeException('Failed to connect to database. MySQL said: ' . $link->connect_error);
         }
         if (!$link->select_db($db_name)) {
             throw new RuntimeException('Failed to select database');
         }
         return $link;
     });
     $this->addToContainer('connection', function ($c) {
         $connection = new MysqliConnection($c['link']);
         $connection->execute('SET foreign_key_checks = 0;');
         foreach ($connection->getTableNames() as $table_name) {
             $connection->dropTable($table_name);
         }
         $connection->execute('SET foreign_key_checks = 1;');
         return $connection;
     });
 }
コード例 #3
0
 public function fetchRelatedObjectRefsOfEntity(MySQLi $mySQLi, ObjectEntity $otherEntity, QueryContext $queryContext, Scope $scope, array &$fetchedObjectRefs)
 {
     // Find the corresponding relationship, ignoring link-relationships.
     $hasTerminatedObjects = FALSE;
     foreach ($this->objectEntity->getRelationships() as $relationship) {
         if ($relationship->getOppositeEntity($this->objectEntity) != $otherEntity) {
             continue;
         }
         // Select the id of the related object.
         $objectIdColumnName = $otherEntity->getObjectIdColumnName();
         $query = new QueryRelatedEntity($this->objectEntity, $this->id, $relationship, $queryContext, $scope);
         $query->setPropertyNames(array($objectIdColumnName));
         $queryString = $query->getQueryString();
         $queryResult = $mySQLi->query($queryString);
         if (!$queryResult) {
             throw new Exception("Error fetching ObjectRefs of entity '" . $otherEntity->getName() . "', associated to '" . $this->objectEntity->getName() . "[{$this->id}]' - " . $mySQLi->error . "\n<!--\n{$queryString}\n-->");
         }
         while ($dbObject = $queryResult->fetch_assoc()) {
             $objectRef = new ObjectRef($otherEntity, $dbObject[$objectIdColumnName]);
             if (!$queryContext->getParameterPublished() and isset($dbObject[QueryEntity::ID_TERMINATED])) {
                 $hasTerminatedObjects = TRUE;
             } else {
                 // Always use the objectRef if we're fetching published data or if it's not terminated.
                 $fetchedObjectRefs[] = $objectRef;
             }
         }
         $queryResult->close();
     }
     return $hasTerminatedObjects;
 }
コード例 #4
0
 private static function query($sql)
 {
     if (self::$debug) {
         tprintWarning($sql);
     }
     return self::$DB_CONN->query($sql);
 }
コード例 #5
0
ファイル: Query.php プロジェクト: jankal/mvc
 /**
  * @param \MySQLi $mysql
  * @param string $query
  */
 public function __construct(\MySQLi $mysql, $query)
 {
     $this->mysql = $mysql;
     $qobject = $this->mysql->query($query);
     if (substr($query, 0, strlen('INSERT INTO')) == 'INSERT INTO' || substr($query, 0, strlen('DELETE FROM')) == 'DELETE FROM') {
         $this->data = false;
     } else {
         while ($dat = $qobject->fetch_assoc()) {
             $this->data[] = $dat;
         }
         $qobject->close();
     }
 }
コード例 #6
0
ファイル: conexionbd.class.php プロジェクト: read424/ssphcm
 public function __construct()
 {
     @parent::connect(NAMESERVER, USERDB, PASSWDB, NAMEDB);
     if ($this->connect_errno) {
         throw new Exception(date('d/m/Y G:i:s T') . " Error#:" . $this->connect_errno . " [ " . $this->connect_error . " ]");
     }
 }
コード例 #7
0
ファイル: DBCond.php プロジェクト: openwebsolns/myorm
 /**
  * Formats this object, escaping the values as needed.
  *
  * @param MySQLi $con the connection to use for escaping
  */
 public function toSQL(\MySQLi $con)
 {
     $oper = null;
     $val = "NULL";
     if ($this->value === null) {
         if ($this->operator == self::EQ) {
             $oper = " is ";
         } else {
             $oper = " is not ";
         }
     } else {
         $oper = $this->operator;
         if ($this->value instanceof DBObject) {
             $val = '"' . $con->real_escape_string($this->value->id) . '"';
         } elseif ($this->value instanceof \DateTime) {
             $val = '"' . $this->value->format('Y-m-d H:i:s') . '"';
         } elseif ($this->value instanceof DBField) {
             $val = $this->value->getName();
         } else {
             $val = '"' . $con->real_escape_string($this->value) . '"';
         }
     }
     $field = $this->field;
     if ($field instanceof DBField) {
         $field = $field->getName();
     }
     return '(' . $field . $oper . $val . ')';
 }
コード例 #8
0
ファイル: MySQLi.php プロジェクト: JanPietrzyk/review
 /**
  * Performs a query on the database
  *
  * @param string $query
  * @param int $resultmode
  * @throws MySQLi\QueryException
  * @return bool
  */
 public function query($query, $resultmode = \MYSQLI_STORE_RESULT)
 {
     if (($result = parent::query($query, $resultmode)) === false) {
         throw new \mysqli_sql_exception($this->error);
     }
     return $result;
 }
コード例 #9
0
ファイル: CG_DB.php プロジェクト: codergma/myspider2
 /**
  * 数据库查询函数
  *
  * @param string $sql 查询语句 
  * @return mixed
  */
 public static function query($sql)
 {
     $sql = trim($sql);
     if (self::$db == NULL) {
         self::_init_mysql();
     }
     self::$mysqli_rst = self::$db->query($sql);
     if (FALSE == self::$mysqli_rst) {
         echo 'MySQL query  errno : ' . self::$db->errno . PHP_EOL;
         $backtrace = debug_backtrace();
         var_dump($backtrace);
         return FALSE;
     } else {
         return self::$mysqli_rst;
     }
 }
コード例 #10
0
ファイル: ModelCore.php プロジェクト: alican/HalloPizza
 public function __construct()
 {
     // inhibit subclassing and instantiation from outside
     require_once 'pwd.php';
     // read account data (including password)
     // initialize the transient associative array
     $this->modelTransient = array();
     // initialize new or open existing session
     session_name($config['session']);
     session_start();
     // connect to database
     try {
         parent::__construct($config['host'], $config['user'], $config['pwd'], "ewa");
         // check connection
         if (mysqli_connect_error()) {
             // $this is invalid in case of error
             throw new Exception("Keine Verbindung zur Datenbank: " . mysqli_connect_error());
         }
     } catch (Exception $e) {
         // do not show the password in an error message
         throw new Exception(str_replace($config['pwd'], "xxx", $e->getMessage()));
     }
     // define character encoding for connection to database
     if (!$this->set_charset(self::charsetDB)) {
         throw new Exception("Fehler beim Laden des Zeichensatzes " . self::charsetDB . ": " . $this->error);
     }
 }
コード例 #11
0
ファイル: db.php プロジェクト: Neurones67/BlooDy
    function query($req)
    {
        // Si c'est la première requête
        if ($this->reqcount == 0) {
            // on ititialise les paramètres
            $this->initParams();
        }
        // On incrémente le compteur de requêtes
        $this->reqcount++;
        // Si la requête n'arrive pas à s'exécuter
        if (!($res = parent::query($req))) {
            // On commencer à mettre la sortie dans un buffer (ob = output buffer)
            ob_start();
            // On affiche l'état de la pile d'appel (pour savoir pourquoi ça plante, d'uù le script est lancé)
            debug_print_backtrace();
            // On écrit tout ça dans un fichier de logs "mysql_errors" avec la date, l'erreur, la requête SQL associée et l'état de la pile d'appel dans le buffer
            file_put_contents(FONCTIONS . "mysql_errors", date('[d/m/Y - H:i:s]') . ' Erreur MySQL : ' . $this->error . ' pendant la requête ' . $req . '
Backtrace:
' . ob_get_contents());
            // On termine la capture de la sortie et on efface ce qu'on a enregistré
            ob_end_clean();
            // Et on termine le script.
            die("Une erreur s'est produite: " . $this->error);
        }
        // Sinon, tout va bien, on renvoie le résultat.
        return $res;
    }
コード例 #12
0
 /**
  * Fecha a conexão com o banco de dados.
  *
  * @return void
  */
 public function close()
 {
     if ($this->isConnected()) {
         $this->connection->close();
         unset($this->connection);
         $this->connection = null;
     }
 }
コード例 #13
0
ファイル: class.db.php プロジェクト: runderwood/redberry
 function __construct()
 {
     self::$host = Config::get('db_host');
     self::$db = Config::get('db_name');
     self::$user = Config::get('db_user');
     self::$password = Config::get('db_pass');
     parent::__construct(self::$host, self::$user, self::$password, self::$db);
 }
コード例 #14
0
ファイル: MySQL.php プロジェクト: catlabinteractive/neuron
 public function escape($txt)
 {
     if (is_array($txt)) {
         throw new Error('Invalid parameter: escape cannot handle arrays.');
     }
     $this->connect();
     return $this->connection->real_escape_string($txt);
 }
コード例 #15
0
ファイル: Database.php プロジェクト: priestd09/sleekmvc
 /**
  * Executes a query which returns rows. Use it with SELECT statements.
  * @param string $query
  * @return DatabaseResult|bool
  */
 public function query($query)
 {
     $this->lastQuery = $query;
     $result = parent::query($query);
     if ($result) {
         return is_bool($result) ? $result : new DatabaseResult($result);
     }
     return FALSE;
 }
コード例 #16
0
ファイル: Factory.php プロジェクト: haohong725/xmvc
 static function createDatabase($db = 'mysqli')
 {
     if ($db === 'MySQLi') {
         $db = MySQLi::getInstance();
     } else {
         $db = MySQLi::getInstance();
     }
     return $db;
 }
コード例 #17
0
 /**
  * Configura os metadados da tabela
  * @return void
  */
 private function setupMetadata()
 {
     if (empty($this->metadata)) {
         $this->metadata = $this->driver->describeTable($this->name);
         if (empty($this->metadata)) {
             throw new Exception("Impossível obter a descrição da tabela {$this->name}!");
         }
     }
 }
コード例 #18
0
 public function selectDatabase($name)
 {
     if ($this->dbConn->select_db($name)) {
         $this->databaseName = $name;
         return true;
     } else {
         return false;
     }
 }
コード例 #19
0
ファイル: mysqlssl.inc.php プロジェクト: tomec-martin/adminer
 function set_charset($charset)
 {
     if (parent::set_charset($charset)) {
         return true;
     }
     // the client library may not support utf8mb4
     parent::set_charset('utf8');
     return $this->query("SET NAMES {$charset}");
 }
コード例 #20
0
 public function getServerVersion()
 {
     $res = $this->dbcon->query("SELECT version() AS `version`");
     if (!$res || $res->num_rows == 0) {
         return '[not connected]';
     }
     $row = $res->fetch_assoc();
     return $row['version'];
 }
コード例 #21
0
ファイル: Factory.class.php プロジェクト: xxlixin1993/Frame
 /**
  * 数据库工厂方法
  */
 public static function getDatabase($id = 'master')
 {
     //读取数据库配置文件
     if ($id == 'master') {
         $db_conf = Init::getInstance()->config['DataBase']['master'];
     } else {
         $db_conf = Init::getInstance()->config['DataBase']['slave'];
     }
     $key = 'database_' . $id;
     //获取数据库对象
     $db = Register::get($key);
     if (!$db) {
         $db = new MySQLi();
         $db->connect($db_conf['host'], $db_conf['user'], $db_conf['password'], $db_conf['dbname']);
         Register::set($key, $db);
     }
     return $db;
 }
コード例 #22
0
ファイル: submit.php プロジェクト: prannayk/codefundo
function evaluate($stu_answers, $studentid, $quizid)
{
    // $myo = new MySQL();
    $some = new MySQLi('localhost', 'root', 'root', 'codefundo');
    $res = $some->query("SELECT * FROM answers") or die('fatal');
    $res2 = $some->query("SELECT * FROM marks") or die('fatal');
    // print_r($res2);
    $result = array();
    $marks = array();
    if ($res) {
        while ($s = $res->fetch_object()) {
            foreach ($s as $key => $value) {
                if ($s->{$key}) {
                    $result[$key] = $value;
                }
            }
        }
    }
    if ($res2) {
        while ($s = $res2->fetch_object()) {
            foreach ($s as $key => $value) {
                if ($s->{$key}) {
                    $marks[$key] = $value;
                }
            }
        }
    }
    unset($result['quizid']);
    $mark = 0;
    foreach ($stu_answers as $quesid => $ans) {
        if ($result[$quesid] == $ans) {
            $mark += $marks[$quesid];
        }
    }
    // var_dump($mark);
    echo 'Score is:';
    echo $mark;
    echo '<Br><a href="dash.php">Continue-></a>';
    if ($myo->Update($quizid, array('marks' => $mark), array('student_id' => $studentid))) {
        print_r('Marks');
    } else {
        die('fatal');
    }
}
コード例 #23
0
ファイル: btmysql.php プロジェクト: bluethrust/clanscriptsv4
 public function __construct($host, $username, $passwd, $dbname = "", $port, $socket)
 {
     $host = !isset($host) ? ini_get("mysqli.default_host") : $host;
     $username = !isset($username) ? ini_get("mysqli.default_user") : $username;
     $passwd = !isset($passwd) ? ini_get("mysqli.default_pw") : $passwd;
     $port = !isset($port) ? ini_get("mysqli.default_port") : $port;
     $socket = !isset($socket) ? ini_get("mysqli.default_socket") : $socket;
     parent::__construct($host, $username, $passwd, $dbname, $port, $socket);
     $this->query("SET SESSION sql_mode = ''");
 }
コード例 #24
0
ファイル: data.php プロジェクト: rmasters/progress
/**
 * Data sourcing - this is a little bit of commentary on the SQL as I found it
 * interesting.
 * 
 * We want to get each goal, and it's latest update (but not if no update exists).
 *
 * The method of doing this is fairly complex (I need to learn about it) - the
 * "per-group-maximum" question. Source:
 * http://stackoverflow.com/questions/3448573/is-it-possible-to/3448816#3448816
 * http://kristiannielsen.livejournal.com/6745.html
 *
 * This could be done using an ORM, by loading all of the goals and then
 * getting the latest status for each one - however this means executing 1 +
 * (the number of results) queries. - this single slow(er) query is better than
 * sending lots of queries, although an ORM is easier to understand and could be
 * cached to remove the bottleneck.
 */
function getGoals(MySQLi $db)
{
    $sql = <<<SQL
    SELECT
        Goal.id as id,
        Goal.name as name,
        g1.value AS value,
        Goal.value_mask AS mask,
        Goal.created AS created,
        g1.created AS updated
    FROM GoalStatus g1                      -- The first GoalStatus.
    LEFT JOIN Goal ON Goal.id = g1.goal     -- Goal information.
    WHERE EXISTS                            -- Check the goal exists if statuses
        (SELECT id                          -- exist from a deleted goal.
         FROM Goal 
         WHERE id = g1.goal)
    AND g1.created =                        -- Find the highest GS.created, by
        (SELECT MAX(created)                -- comparing the current GS.created to
         FROM GoalStatus g2                 -- the highest in the table.
         WHERE g1.goal = g2.goal);
SQL;
    $goalStmt = $db->prepare($sql);
    $goalStmt->execute();
    $goalStmt->bind_result($id, $name, $value, $mask, $created, $updated);
    $goals = array();
    $i = 0;
    // Fill an array
    while ($goalStmt->fetch()) {
        $value = (int) $value;
        $goals[] = array("id" => $id, "name" => $name, "value" => $value, "mask" => $mask, "value_label" => "", "created" => $created, "updated" => $updated, "width" => $value > 100 ? 100 : $value);
        // For done/not done tasks
        if (trim($mask) == "?" && ($value == 1 || $value == 0)) {
            $goals[$i]["value_label"] = $value == 1 ? "Completed" : "Not completed";
            $goals[$i]["width"] = $value == 1 ? 100 : 0;
        } else {
            $goals[$i]["value_label"] = str_replace("?", $value, $mask);
        }
        $i++;
    }
    $goalStmt->close();
    return $goals;
}
コード例 #25
0
ファイル: DBConnect.php プロジェクト: OpenBibleSearch/morphhb
 public function __construct($host = "", $username = "", $passwd = "", $dbname = "")
 {
     $this->host = $host ? $host : ini_get("mysql.default_host");
     $this->username = $username ? $username : ini_get("mysql.default_user");
     $this->passwd = $passwd ? $passwd : ini_get("mysql.default_password");
     $this->dbname = $dbname ? $dbname : "hb";
     parent::__construct($this->host, $this->username, $this->passwd, $this->dbname);
     if ($this->connect_errno) {
         die('Connect Error (' . $this->connect_errno . ') ' . $this->connect_error);
     }
 }
コード例 #26
0
ファイル: PdoMysql.php プロジェクト: hjr3/zf2
 public function getParams(array $constants = array())
 {
     $constants = parent::getParams($constants);
     if (!isset($constants['driver_options'])) {
         $constants['driver_options'] = array();
     }
     if (!isset($constants['driver_options'][\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY])) {
         $constants['driver_options'][\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY] = true;
     }
     return $constants;
 }
コード例 #27
0
 /**
  * Obtiene una instancia de un objeto de conexion a la base de datos
  * @param array $parametros
  * @return \mysqli Mysqli Instance
  * @throws string
  */
 public static function getInstance(array $parametros = array())
 {
     if (self::$instance) {
         return self::$instance;
     }
     $parametrosRequeridos = array("host", "user", "pass", "db");
     \Validator::validateArrayKeys($parametrosRequeridos, $parametros);
     if (!array_key_exists("port", $parametros)) {
         $parametros["port"] = 3306;
     } elseif (empty($parametros["port"])) {
         $parametros["port"] = 3306;
     }
     $mysqli = new \MySQLi(\Validator::emptyString($parametros["host"]), \Validator::emptyString($parametros["user"]), $parametros["pass"], \Validator::emptyString($parametros["db"]), \Validator::int($parametros["port"]));
     if ($mysqli->connect_error) {
         $msg = "No se pudo conectar a la base de datos " . $mysqli->connect_errno . ':' . $mysqli->error;
         throw new Exception($msg);
     }
     $mysqli->set_charset("utf8");
     self::$instance = $mysqli;
     return self::$instance;
 }
コード例 #28
0
ファイル: database.php プロジェクト: Hellysonrp/arastta
 private function _validateMysqli($data)
 {
     $conn = new \MySQLi($data['db_hostname'], $data['db_username'], $data['db_password']);
     if ($conn->connect_error) {
         $conn->close();
         return false;
     } else {
         // Try to create database, if doesn't exist
         $sql = "CREATE DATABASE IF NOT EXISTS " . $data['db_database'];
         if ($conn->query($sql) === false) {
             // Couldn't create it, just check if exists
             $sql = "SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '" . $data['db_database'] . "'";
             if (!$conn->query($sql)->num_rows) {
                 $conn->close();
                 return false;
             }
         }
         $conn->close();
         return true;
     }
 }
コード例 #29
0
ファイル: index.php プロジェクト: josh-channin/wotmanager
function getPlayers()
{
    $mysqli = new MySQLi("localhost", "wotmanager", "DT5HtrpaUlJ3iVGm", "testing", 3306);
    $stmt = $mysqli->prepare("SELECT ID,nick,battles,tier,wn8,wr,rwn8,rwr,clan,time FROM result order by time desc");
    $stmt->bind_result($id, $nick, $battles, $tier, $wn8, $wr, $rwn8, $rwr, $clan, $updated);
    $stmt->execute();
    while ($stmt->fetch()) {
        echo '<tr>
      <td><b><a href="http://stats.wotmanager.com/na/player/' . $nick . '" target="_blank">' . $nick . '</a></b></td>
      <td><b><font color="' . getColor($battles, "bat") . '">' . $battles . '</font></b></td>
      <td><b><font color="' . getColor($tier, "tier") . '">' . $tier . '</font></b></td>
      <td><b><font color="' . getColor($wn8, "wn8") . '">' . $wn8 . '</font></b></td>
      <td><b><font color="' . getColor($wr, "wr") . '">' . $wr . '</font></b></td>
      <td><b><font color="' . getColor($rwn8, "wn8") . '">' . $rwn8 . '</font></b></td>
      <td><b><font color="' . getColor($rwr, "wr") . '">' . $rwr . '</font></b></td>
      <td>' . $clan . '</td>
      <td>' . $updated . '</td>
      <td><a href="http://forum.worldoftanks.com/index.php?app=members&module=messaging&section=send&do=form&preview=1&_from=quickPM&fromMemberID=' . $id . '"target="_blank"><i class="fa fa-envelope fa-lg"></i></a></td>
    </tr>';
    }
}
コード例 #30
0
ファイル: DBCondIn.php プロジェクト: openwebsolns/myorm
 public function toSQL(\MySQLi $con)
 {
     if (is_array($this->values) || $this->values instanceof ArrayIterator) {
         $val = "";
         $index = 0;
         foreach ($this->values as $v) {
             if ($index++ > 0) {
                 $val .= ',';
             }
             if ($v instanceof DBObject) {
                 $v = $v->id;
             }
             $val .= '"' . $con->real_escape_string($v) . '"';
         }
     } else {
         $val = $this->values->toSQL();
     }
     $field = $this->field;
     if ($field instanceof DBField) {
         $field = $field->getName();
     }
     return "({$field} {$this->operator} ({$val}))";
 }