本文整理汇总了PHP中MySQLi类的典型用法代码示例。如果您正苦于以下问题:PHP MySQLi类的具体用法?PHP MySQLi怎么用?PHP MySQLi使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了MySQLi类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。
示例1: del_imgs
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>";
}
开发者ID:jjling2011,项目名称:sams,代码行数:35,代码来源:del.php
示例2: setUp
/**
* {@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;
});
}
开发者ID:activecollab,项目名称:bootstrap,代码行数:31,代码来源:DatabaseTestCase.php
示例3: fetchRelatedObjectRefsOfEntity
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;
}
开发者ID:RobBosman,项目名称:bransom.RestServer-PHP,代码行数:30,代码来源:ObjectRef.class.php
示例4: __construct
/**
* @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();
}
}
开发者ID:jankal,项目名称:mvc,代码行数:17,代码来源:Query.php
示例5: toSQL
/**
* 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 . ')';
}
开发者ID:openwebsolns,项目名称:myorm,代码行数:33,代码来源:DBCond.php
示例6: query
/**
* 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;
}
开发者ID:JanPietrzyk,项目名称:review,代码行数:15,代码来源:MySQLi.php
示例7: createDatabase
static function createDatabase($db = 'mysqli')
{
if ($db === 'MySQLi') {
$db = MySQLi::getInstance();
} else {
$db = MySQLi::getInstance();
}
return $db;
}
开发者ID:haohong725,项目名称:xmvc,代码行数:9,代码来源:Factory.php
示例8: getDatabase
/**
* 数据库工厂方法
*/
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;
}
开发者ID:xxlixin1993,项目名称:Frame,代码行数:21,代码来源:Factory.class.php
示例9: evaluate
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');
}
}
开发者ID:prannayk,项目名称:codefundo,代码行数:44,代码来源:submit.php
示例10: getGoals
/**
* 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;
}
开发者ID:rmasters,项目名称:progress,代码行数:59,代码来源:data.php
示例11: getInstance
/**
* 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;
}
开发者ID:elgodmaster,项目名称:lacalderadeldiablo,代码行数:27,代码来源:Singleton.class.php
示例12: _validateMysqli
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;
}
}
开发者ID:Hellysonrp,项目名称:arastta,代码行数:21,代码来源:database.php
示例13: getPlayers
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§ion=send&do=form&preview=1&_from=quickPM&fromMemberID=' . $id . '"target="_blank"><i class="fa fa-envelope fa-lg"></i></a></td>
</tr>';
}
}
开发者ID:josh-channin,项目名称:wotmanager,代码行数:21,代码来源:index.php
示例14: toSQL
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}))";
}
开发者ID:openwebsolns,项目名称:myorm,代码行数:23,代码来源:DBCondIn.php
示例15: query
private static function query($sql)
{
if (self::$debug) {
tprintWarning($sql);
}
return self::$DB_CONN->query($sql);
}
开发者ID:yangjian102621,项目名称:herosphp,代码行数:7,代码来源:DBFactory.class.php
示例16: __construct
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 . " ]");
}
}
开发者ID:read424,项目名称:ssphcm,代码行数:7,代码来源:conexionbd.class.php
示例17: query
/**
* 数据库查询函数
*
* @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;
}
}
开发者ID:codergma,项目名称:myspider2,代码行数:22,代码来源:CG_DB.php
示例18: __construct
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);
}
}
开发者ID:alican,项目名称:HalloPizza,代码行数:27,代码来源:ModelCore.php
示例19: query
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;
}
开发者ID:Neurones67,项目名称:BlooDy,代码行数:27,代码来源:db.php
示例20: close
/**
* 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;
}
}
开发者ID:hbarcelos,项目名称:iMasters-Articles-Sources,代码行数:13,代码来源:Driver.php
注:本文中的MySQLi类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论