本文整理汇总了PHP中pdo::prepare方法的典型用法代码示例。如果您正苦于以下问题:PHP pdo::prepare方法的具体用法?PHP pdo::prepare怎么用?PHP pdo::prepare使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pdo
的用法示例。
在下文中一共展示了pdo::prepare方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: executeQuery
/**
* This method will execute sql query.
*
* @param queryId - The query id to execute. if no value is given the method will seach for it as request param.
* @param params - List of parameters to bind to teh stored procedure.
* If no parameters are passed all the request params will be used as bind parameters.
*
* @return - Returns an array containing all of the result set rows
*/
public function executeQuery($queryId = null, $params = null)
{
if (!isset($queryId)) {
$queryId = Utils::getParam('queryId', null);
if (!isset($queryId)) {
throw new Exception('Missing queryId');
}
}
// -----------------------------------------------------------------------------------
// -- If no parameters are passed auto build the params from all the GET/POST pairs --
// -----------------------------------------------------------------------------------
if (!isset($params)) {
$params = array();
// We read the parameters form the request since it contains both get and post params
foreach ($_REQUEST as $key => $value) {
$params[':' . $key] = $value;
}
}
// Get the query we wish to execute
$query = $this->sql_queries[$queryId];
$statment = $this->pdo->prepare($query);
$statment->setFetchMode(PDO::FETCH_ASSOC);
$statment->execute($params);
// Check to see if we have error or not
$error = $statment->errorInfo();
// Set the error message
if ($error[0] > 0) {
$_REQUEST['DBLayer.executeQuery.error'] = $statment->errorInfo();
}
// return all the rows
return $statment->fetchAll();
}
示例2: setAllMsgDeleteInThread
public function setAllMsgDeleteInThread($threadId)
{
$sql = $this->getQuery('UPDATE ' . self::$SCHEMA . '.MSG_BOX set "Status"=(
CASE WHEN ( "To_User_ID" = ' . $this->userId . ' AND "Status" = ' . self::$DELETED_BY_FROM_USER . ') THEN ' . self::$DELETED_BY_BOTH . '
WHEN ( "From_User_ID" = ' . $this->userId . ' AND "Status" = ' . self::$DELETED_BY_TO_USER . ') THEN ' . self::$DELETED_BY_BOTH . '
WHEN "From_User_ID" = ' . $this->userId . ' AND "Status" = ' . self::$NOT_READED . ' THEN ' . self::$DELETED_FROM_USER_NOT_READED_BY_TO_USER . '
WHEN "To_User_ID" = ' . $this->userId . ' THEN ' . self::$DELETED_BY_TO_USER . '
WHEN "From_User_ID" = ' . $this->userId . ' THEN ' . self::$DELETED_BY_FROM_USER . '
END )
WHERE "MSG_ID" in (Select "ID" from ' . self::$SCHEMA . '.MSG where "Thread_ID"=?) AND ("To_User_ID"=' . $this->userId . ' OR "From_User_ID"=' . $this->userId . ')');
$stmt = $this->pdo->prepare($sql);
$stmt->execute(array($threadId));
}
示例3: displayMsgUser
public function displayMsgUser(pdo $conexao, $idUsuario)
{
try {
$msg = "";
$stmtSel = $conexao->prepare(mensagemDAO::$SELECT_MENSAGEM_USER);
$stmtSel->execute(array(':idUsuario' => $idUsuario));
$resultado = $stmtSel->fetchAll();
foreach ($resultado as $linha) {
$msg .= "<div class='listMsg'>\n <span class='usuario1'>{$linha['3']}</span>";
}
return $msg;
} catch (PDOException $e) {
print_r($e);
}
}
示例4: updateInformation
public function updateInformation($table, $update, $where, $val)
{
foreach ($update as $key => $value) {
$x++;
$set .= "" . $key . " = " . $value . "";
if (count($update) > $x) {
$set .= ", ";
}
}
try {
$db = new pdo($this->db_config["host"], $this->db_config["user"], $this->db_config["pswd"]);
$sql = $db->prepare("UPDATE " . $table . " SET " . $set . " WHERE " . $where . " = " . $val . "");
$sql->execute();
unset($db);
return $row;
} catch (PDOException $e) {
die("Database Error: " . $e);
return false;
}
}
示例5: pdo
if (isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'Google App Engine') !== false) {
// Connect from App Engine.
try {
$conn = new pdo('mysql:unix_socket=/cloudsql/artgallery-1156:art;dbname=artgallery', 'root', '');
} catch (PDOException $ex) {
die(json_encode(array('outcome' => false, 'message' => 'Unable to connect :((((')));
}
} else {
// Connect from a development environment.
try {
$conn = new pdo('mysql:host=173.194.105.221;dbname=artgallery', 'joseph', 'admin');
} catch (PDOException $ex) {
die(json_encode(array('outcome' => false, 'message' => 'Unable to connect')));
}
}
$statement = $conn->prepare("select * from purchases natural join customers where purchases.custname=customers.name and purchaseid= :id");
$statement->bindParam(':id', $id);
$statement->execute();
$pur = $statement->fetch();
$pieceid = $pur[pieceid];
$statement = $conn->prepare("select * from art_data natural join art_pieces where pieceid= :id");
$statement->bindParam(':id', $pieceid);
$statement->execute();
$gen = $statement->fetch();
echo "<h2>" . $gen[name] . "</h2>";
echo "<table style='width:50%'>";
echo "<tr><td><h4>General Info</h4></td></tr>";
echo "<tr><td>Artist</td><td>" . $gen[artist] . "</td></tr>";
echo "<tr><td>Date</td><td>" . $gen[date] . "</td></tr>";
echo "<tr><td>Price</td><td>\$" . $gen[price] . "</td></tr>";
echo "<tr><td><h4></h4></td></tr>";
示例6: sprintf
<?php
echo "this is a database test.";
$ip = '192.168.33.61';
$port = '3306';
$user = 'root';
$pass = '';
$info = sprintf("mysql:host=%s;port=%s,database=;", $ip, $port);
$db = new pdo($info, $user, $pass, array(PDO::ATTR_PERSISTENT => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$sth = $db->query('use test_database');
$sth = $db->prepare('select * from fukens');
$sth->execute(array());
while ($line = $sth->fetch()) {
var_dump($line);
}
exit;
示例7: install
public function install($ctn)
{
if (!$ctn['config']['installed']) {
$msg = "";
// no sec here, just install
if ($_REQUEST['action'] == 'save') {
$file = $ctn['pathApp'] . "config.json";
$config = $ctn['config'];
// update DB settings
$config['database']['name'] = $_REQUEST['db_name'];
$config['database']['user'] = $_REQUEST['db_user'];
$config['database']['pass'] = $_REQUEST['db_pass'];
$config['database']['host'] = $_REQUEST['db_host'];
$config['database']['port'] = $_REQUEST['db_port'];
unset($config['database']['nodatabase']);
// set basic data
$config['url'] = $_REQUEST['url'];
$config['site'] = preg_replace("/[^0-9a-zA-Z_\\s]+/", "", $_REQUEST['url']);
$config['salt'] = md5(time() . rand(10, 20));
// connect to database (with new parameters)
try {
$db = new pdo('mysql:host=' . $_REQUEST['db_host'] . ':' . $_REQUEST['db_port'] . ';dbname=' . $_REQUEST['db_name'], $_REQUEST['db_user'], $_REQUEST['db_pass']);
// install mysql structure
$structureFile = $ctn['pathApp'] . "database.sql";
if (!file_exists($structureFile)) {
$msg = "Could not fine database file";
} else {
$cmd = file_get_contents($structureFile);
$sth = $db->prepare($cmd);
$sth->execute();
// create user
$sth = $db->prepare("INSERT INTO user (role_id,username,password) VALUES (3,:user,:pass); ");
$sth->bindValue("user", $_REQUEST['user']);
$sth->bindValue("pass", password_hash($_REQUEST['pass'] . $config['salt'], PASSWORD_BCRYPT, array('cost' => 12)));
$sth->execute();
$config['installed'] = true;
$json = json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
file_put_contents($file, $json);
apcu_clear_cache();
header("Location: /");
}
} catch (\PDOException $e) {
$msg = $e->getMessage();
}
}
?>
<form action="/">
<input type="hidden" name="action" value="save" />
<h1>Install</h1>
<h2>Website Settings</h2>
<table>
<tr>
<td>URL:</td>
<td><input type="text" name="url" value="<?php
echo $_REQUEST['url'];
?>
" /></td>
</tr>
<tr>
<td>Username:</td>
<td><input type="text" name="user" value="<?php
echo $_REQUEST['user'];
?>
" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="pass" value="<?php
echo $_REQUEST['pass'];
?>
" /></td>
</tr>
</table>
<h2>Database Settings</h2>
<p style='color: red;'><?php
echo $msg;
?>
</p>
<table>
<tr>
<td>DB-Name:</td>
<td><input type="text" name="db_name" value="<?php
echo $_REQUEST['db_name'];
?>
" /></td>
</tr>
<tr>
<td>Username:</td>
<td><input type="text" name="db_user" value="<?php
echo $_REQUEST['db_user'];
?>
" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="db_pass" value="<?php
echo $_REQUEST['db_pass'];
?>
" /></td>
</tr>
//.........这里部分代码省略.........
示例8: unlock
/**
* Removes a lock from a uri
*
* @param string $uri
* @param Sabre_DAV_Locks_LockInfo $lockInfo
* @return bool
*/
public function unlock($uri, Sabre_DAV_Locks_LockInfo $lockInfo)
{
$stmt = $this->pdo->prepare('DELETE FROM locks WHERE uri = ? AND token = ?');
$stmt->execute(array($uri, $lockInfo->token));
return $stmt->rowCount() === 1;
}
示例9: trim
$_SESSION["errorMsg"] = "";
}
/*
* Session verification. If no session value page redirect to login.php
*/
$mode = $_REQUEST["mode"];
if ($mode == "login") {
$username = trim($_POST['username']);
$pass = trim($_POST['user_password']);
if ($username == "" || $pass == "") {
$_SESSION["errorType"] = "danger";
$_SESSION["errorMsg"] = "Enter manadatory fields";
} else {
$sql = "SELECT * FROM system_users WHERE u_username = :uname AND u_password = :upass ";
try {
$stmt = $DB->prepare($sql);
// bind the values
$stmt->bindValue(":uname", $username);
$stmt->bindValue(":upass", md5($pass));
// execute Query
$stmt->execute();
$results = $stmt->fetchAll();
if (count($results) > 0) {
$_SESSION["errorType"] = "success";
$_SESSION["errorMsg"] = "You have successfully logged in.";
$_SESSION["user_id"] = $results[0]["u_userid"];
$_SESSION["rolecode"] = $results[0]["u_rolecode"];
$_SESSION["username"] = $results[0]["u_username"];
$_SESSION["name"] = $results[0]["u_name"];
$_SESSION['timeout'] = time();
header("Location:dashboard.php");
示例10: pdo
<?php
if (isset($_POST["submit"])) {
try {
$db = new pdo('mysql:host=localhost;dbname=bieren', 'root', '');
// Root password not set up
$message = "db init";
$brNaam = $_POST["brouwernaam"];
$adres = $_POST["adres"];
$postcode = $_POST["postcode"];
$gemeente = $_POST["gemeente"];
$omzet = $_POST["omzet"];
$insertQuery = "INSERT INTO brouwers (brnaam, adres, postcode, gemeente, omzet) VALUES('{$brNaam}','{$adres}','{$postcode}','{$gemeente}','{$omzet}');";
// var_dump("INSERT INTO brouwers (brnaam, adres, postcode, gemeente, omzet) VALUES(" . $brNaam . ", " . $adres . ", ". $postcode . ", " . $gemeente . ", " . $omzet . ");");
$statement = $db->prepare($insertQuery);
$isAdded = $statement->execute();
if ($isAdded) {
$id = $db->lastInsertId();
// Returns id of the last inserted row
$message = 'Brouwerij succesvol toegevoegd. Het unieke nummer van deze brouwerij is ' . $id . '.';
} else {
$message = 'Er ging iets mis met het toevoegen, probeer opnieuw';
}
} catch (PDOException $e) {
$message = 'De connectie is niet gelukt.';
}
}
?>
<!doctype html>
<html>
示例11: catch
}
// verwijderen
$teVerwijderen = '';
if (isset($_GET['delete'])) {
$_SESSION['teVerwijderen'] = $_GET['delete'];
}
if (isset($_SESSION['teVerwijderen'])) {
$teVerwijderen = $_SESSION['teVerwijderen'];
}
if (isset($_GET['bevestiging'])) {
if ($_GET['bevestiging'] == 'ja') {
$verwijderQuery = 'DELETE FROM brouwers
WHERE brouwernr = :teVerwijderen';
//echo('Query: <code> ' . $verwijderQuery . '</code>') ;
try {
$statement = $db->prepare($verwijderQuery);
$statement->bindValue(':teVerwijderen', $teVerwijderen);
$statement->execute();
$boodschap = 'De datarij werd goed verwijderd';
} catch (PDOException $e) {
$boodschap = 'De datarij kon niet verwijderd worden. Probeer opnieuw.';
}
$_SESSION['teVerwijderen'] = '';
$teVerwijderen = '';
} else {
header("Location: {$ditBestand}");
$_SESSION['teVerwijderen'] = '';
$teVerwijderen = '';
}
}
// edit
示例12: execute
/**
* 执行
* @param string $query
* @param string $parameters
*/
protected function execute($query, $parameters = "")
{
try {
$this->sQuery = $this->pdo->prepare($query);
$this->bindMore($parameters);
if (!empty($this->parameters)) {
foreach ($this->parameters as $param) {
$parameters = explode("", $param);
$this->sQuery->bindParam($parameters[0], $parameters[1]);
}
}
$this->succes = $this->sQuery->execute();
} catch (\PDOException $e) {
// 服务端断开时重连一次
if ($e->errorInfo[1] == 2006 || $e->errorInfo[1] == 2013) {
$this->closeConnection();
$this->connect();
try {
$this->sQuery = $this->pdo->prepare($query);
$this->bindMore($parameters);
if (!empty($this->parameters)) {
foreach ($this->parameters as $param) {
$parameters = explode("", $param);
$this->sQuery->bindParam($parameters[0], $parameters[1]);
}
}
$this->succes = $this->sQuery->execute();
} catch (\PDOException $ex) {
$this->rollBackTrans();
throw $ex;
}
} else {
$this->rollBackTrans();
throw $e;
}
}
$this->parameters = array();
}
示例13: pdo
/**
* Scan e carga para banco SQL, dos XMLs dispostos em filesystem. Ver scripts "ini.sql".
*/
// // // //
// CONFIGURACOES:
$PG_USER = 'postgres';
$PG_PW = 'pp@123456';
$pasta = '/home/peter/Área de Trabalho/hackday/xml-scielo';
$n = 0;
$dsn = "pgsql:dbname=postgres;host=localhost";
$db = new pdo($dsn, $PG_USER, $PG_PW);
$XHEAD = '';
// $XHEAD = '<?xml version="1.0" encoding="UTF-8" >'."\n";
$rgx_doctype = '/^\\s*<!DOCTYPE\\s([^>]+)>/s';
// INSERT de teste com as ~2mil amostras do SciELO-BR
$stmt = $db->prepare("INSERT INTO articles(repo,repos_pid,content_dtd,xcontent) VALUES (1,:pid,:doctype,:conteudo)");
foreach (scandir($pasta) as $file) {
if (strlen($file) > 5) {
// && $n<10
$n++;
print "\n -- {$file}";
$pid = str_replace('.xml', '', $file);
$cont = file_get_contents("{$pasta}/{$file}");
$stmt->bindParam(':pid', $pid, PDO::PARAM_STR);
$doctype = preg_match($rgx_doctype, $cont, $m) ? $m[1] : '';
if ($doctype) {
$cont = preg_replace($rgx_doctype, '', $cont);
}
$stmt->bindParam(':doctype', $doctype, PDO::PARAM_STR);
// $stmt->bindParam(':conteudo',$XHEAD.$cont,PDO::PARAM_STR);
$stmt->bindParam(':conteudo', $cont, PDO::PARAM_STR);
示例14: request_ws
/**
* Submit request (cmd with params) to the database. As webservice.
* @param $cmd string command
* @param $params array, params of the command.
* @param $degVers int openness degree version.
* @param $notRetJson int 0=JSON, 1=PHP ARRAY, 2=PHP OBJECTS.
*/
function request_ws($cmd, $params, $degVers = 2, $notRetJson = 0)
{
global $dsn;
global $PG_USER;
global $PG_PW;
$err_cod = 0;
try {
$jinfo = json_encode($params);
switch ($cmd) {
case 'licqts_calc':
$sql = "SELECT om.licqts_calc(:j_info::json,{$degVers})";
break;
case 'famqts_calc':
$sql = "SELECT om.famqts_calc(:j_info::json,{$degVers})";
break;
default:
throw new Exception("Comando '{$cmd}' desconhecido", 5);
}
$db = new pdo($dsn, $PG_USER, $PG_PW);
$stmt = $db->prepare($sql);
if ($stmt->bindParam(":j_info", $jinfo)) {
$ok = $stmt->execute();
} else {
throw new Exception("Falha no bindParam", 8);
}
if ($ok) {
$json = $stmt->fetchColumn();
return $notRetJson ? json_decode($json, $notRetJson == 2 ? false : true) : $json;
} else {
throw new Exception("Falha ao executar SQL, \n'''{$sql}'''\n", 20);
}
return null;
//never here
} catch (Exception $e) {
$r = array('error' => array('code' => $e->getCode(), 'message' => $e->getMessage()));
}
return $notRetJson ? $r : json_encode($r, true);
}
示例15: pdo
<?php
session_start();
if (isset($_POST['login'])) {
$email = $_POST['email'];
$password = $_POST['password'];
try {
$db = new pdo('mysql:host=localhost;dbname=users-fileupload', 'root', '');
$query = "SELECT * FROM users WHERE email = '{$email}'";
$statement = $db->prepare($query);
$statement->execute();
// Tel hoeveel rijen de query returnt
$results = $statement->rowCount();
if ($results != 0) {
// Als er een match is met de database
$resultsArray = array();
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$resultsArray[] = $row;
}
// Get database values
$salt = $resultsArray[0]['salt'];
$hashedDbPassword = $resultsArray[0]['hashed_password'];
// Get form values -> hash
$saltedPassword = $salt . $password;
$hashedPassword = hash('sha256', $saltedPassword);
if ($hashedPassword == $hashedDbPassword) {
$_SESSION['message'] = "U bent ingelogd.";
$updateTimeQuery = "UPDATE users SET last_login_time=NOW() WHERE email = '{$email}'";
$updateTime = $db->prepare($updateTimeQuery);
$updateTime->execute();
setcookie("login", $email . "," . $salt, time() + 86400 * 30);