/** * @return Result */ public function execute($params = []) { $params = $params ?: $this->params; $sql = $this->sql; if ($params) { $emulatedNamedParameters = false; if (array_values($params) != $params) { $emulatedNamedParameters = true; } if ($emulatedNamedParameters) { $actualParameters = []; $sql = preg_replace_callback('`:(\\w+)`', function ($matches) use(&$actualParameters, $params) { $actualParameters[] = $params[$matches[1]]; return "?"; }, $sql); } else { $actualParameters = $params; } $this->statement = $this->mysqli->prepare($sql); if ($this->statement === false) { throw new \InvalidArgumentException($this->mysqli->error); } foreach ($actualParameters as $parameter) { if (is_int($parameter)) { $this->statement->bind_param('i', $parameter); } else { if (is_double($parameter) || is_float($parameter)) { $this->statement->bind_param('d', $parameter); } else { $this->statement->bind_param('s', $parameter); } } } } else { $this->statement = $this->mysqli->prepare($sql); if ($this->statement === false) { throw new \InvalidArgumentException($this->mysqli->error); } } $this->statement->execute(); }
private function doLoginWithPostData() { // check login form contents if (empty($_POST['email'])) { $this->errors[] = "Email field was empty."; } else { if (empty($_POST['password'])) { $this->errors[] = "Password field was empty."; } else { if (!empty($_POST['email']) && !empty($_POST['password'])) { $this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); // change character set to utf8 and check it if (!$this->db_connection->set_charset("utf8")) { $this->errors[] = $this->db_connection->error; } // if no connection errors (= working database connection) if (!$this->db_connection->connect_errno) { // escape the POST stuff $email = $this->db_connection->real_escape_string($_POST['email']); // database query, getting all the info of the selected user (allows login via email address in the // username field) $sql = new mysqli_stmt($this->db_connection, "SELECT id, first_name, last_name, email, password, privilege FROM users WHERE email = ?;"); $sql->bind_param("s", $_POST['email']); $sql->execute(); $result_of_login_check = $sql->get_result(); // if this user exists if ($result_of_login_check->num_rows == 1) { // get result row (as an object) $result_row = $result_of_login_check->fetch_object(); // using PHP 5.5's password_verify() function to check if the provided password fits // the hash of that user's password if (password_verify($_POST['password'], $result_row->password)) { // write user data into PHP SESSION (a file on your server) $_SESSION['id'] = $result_row->id; $_SESSION['first_name'] = $result_row->first_name; $_SESSION['last_name'] = $result_row->last_name; $_SESSION['email'] = $result_row->email; // $_SESSION['privilege'] = $result_row->privilege; $_SESSION['user_login_status'] = 1; $this->messages[] = "You have logged in successfully!"; } else { $this->errors[] = "Wrong password. Try again."; } } else { $this->errors[] = "This user does not exist."; } } else { $this->errors[] = "Database connection problem."; } } } } }
/** * Load all items from the database. * * Uses some code based on C4::Items GetItemsInfo in koha * * @param $recordId * @return array */ private function getHoldingsFromKohaDB($recordId) { $holdingsFromKoha = array(); $this->initDatabaseConnection(); if ($this->getHoldingsStmt == null) { $sql = "SELECT itemnumber, barcode, itype, holdingbranch, location, itemcallnumber, onloan, ccode, itemnotes, enumchron, damaged, itemlost, wthdrawn, restricted FROM items where biblionumber = ? AND suppress = 0"; $this->getHoldingsStmt = mysqli_prepare($this->dbConnection, $sql); } $this->getHoldingsStmt->bind_param("i", $recordId); if (!$this->getHoldingsStmt->execute()) { global $logger; $logger->log("Unable to load holdings from Koha ({$this->getHoldingsStmt->errno}) {$this->getHoldingsStmt->error}", PEAR_LOG_ERR); } else { //Read the information $results = $this->getHoldingsStmt->get_result(); while ($curRow = $results->fetch_assoc()) { if ($curRow['itype'] == 'EAUDIO' || $curRow['itype'] == 'EBOOK' || $curRow['itype'] == 'ONLINE') { continue; } $curItem = array(); $curItem['type'] = 'holding'; $curItem['id'] = $curRow['itemnumber']; $curItem['barcode'] = $curRow['barcode']; $curItem['itemType'] = mapValue('itype', $curRow['itype']); $curItem['locationCode'] = $curRow['location']; $curItem['library'] = mapValue('location', $curRow['holdingbranch']); $curItem['location'] = $curRow['location']; $curItem['collection'] = mapValue('ccode', $curRow['ccode']); $curItem['callnumber'] = $curRow['itemcallnumber']; $curItem['volInfo'] = $curRow['enumchron']; $curItem['copy'] = $curRow['itemcallnumber']; $curItem['notes'] = $curRow['itemnotes']; $curItem['dueDate'] = $curRow['onloan']; //Figure out status based on all of the fields that make up the status if ($curRow['damaged'] == 1) { $curItem['status'] = "Damaged"; } else { if ($curRow['itemlost'] != null) { if ($curRow['itemlost'] == 'longoverdue') { $curItem['status'] = "Long Overdue"; } elseif ($curRow['itemlost'] == 'missing') { $curItem['status'] = "Missing"; } elseif ($curRow['itemlost'] == 'lost') { $curItem['status'] = "Lost"; } elseif ($curRow['itemlost'] == 'trace') { $curItem['status'] = "Trace"; } } else { if ($curRow['restricted'] == 1) { $curItem['status'] = "Not For Loan"; } else { if ($curRow['wthdrawn'] == 1) { $curItem['status'] = "Withdrawn"; } else { if ($curItem['dueDate'] == null) { $curItem['status'] = "On Shelf"; } else { $curItem['status'] = "Due {$curItem['dueDate']}"; } } } } } $holdingsFromKoha[] = $curItem; } $results->close(); } return $holdingsFromKoha; }
/** * Rende persistenti le modifiche all'anagrafica di un docente sul db * @param Docente $d il docente considerato * @param mysqli_stmt $stmt un prepared statement * @return int il numero di righe modificate */ private function salvaDocente(Docente $d, mysqli_stmt $stmt) { $query = " update docenti set \n password = ?,\n nome = ?,\n cognome = ?,\n email = ?,\n citta = ?,\n provincia = ?,\n cap = ?,\n via = ?,\n ricevimento = ?,\n numero_civico = ?,\n dipartimento_id = ?\n where docenti.id = ?\n "; $stmt->prepare($query); if (!$stmt) { error_log("[salvaStudente] impossibile" . " inizializzare il prepared statement"); return 0; } if (!$stmt->bind_param('sssssssssiii', $d->getPassword(), $d->getNome(), $d->getCognome(), $d->getEmail(), $d->getCitta(), $d->getProvincia(), $d->getCap(), $d->getVia(), $d->getRicevimento(), $d->getNumeroCivico(), $d->getDipartimento()->getId(), $d->getId())) { error_log("[salvaStudente] impossibile" . " effettuare il binding in input"); return 0; } if (!$stmt->execute()) { error_log("[caricaIscritti] impossibile" . " eseguire lo statement"); return 0; } return $stmt->affected_rows; }
require_once "../../resources/config.php"; require_once "./db_connect.php"; require_once "../../resources/library/functions.php"; // prepare result array $result = array("success" => FALSE, "errors" => NULL); if ($_POST['adminId']) { // get POST data (ids) $adminId = $_POST['adminId']; $userToVerifyId = $_POST['userToVerifyId']; // check if the admin is really the admin if (privilegeCheck($mysqli, $adminId) == 0) { // prepare stmt $stmt = new mysqli_stmt($mysqli, "UPDATE users SET verified=? WHERE id = ?"); if ($stmt) { $verified = 1; $stmt->bind_param("ii", $verified, $userToVerifyId); if ($stmt->execute()) { $result['success'] = TRUE; } else { $result["errors"] = "user is not an admin"; } } } else { $result["errors"] = "user is not an admin"; } } else { $result["errors"] = "no variable passed"; } // returns JSON echo json_encode($result); $mysqli->close();
/** * Prepare a statement, but in a way that checks the result, and errors out when it fails. * @param mysqli $db * @param mysqli_stmt $stmt * @param string $types * @param mixed $vars * */ function checkBindParam($db, $stmt, $types, &$var1, &$var2 = NULL, &$var3 = NULL, &$var4 = NULL) { $num = func_num_args(); if ($num == 4) { $result = $stmt->bind_param($types, $var1); } else { if ($num == 5) { $result = $stmt->bind_param($types, $var1, $var2); } else { if ($num == 6) { $result = $stmt->bind_param($types, $var1, $var2, $var3); } } } if ($result === FALSE) { stmtError($db, $stmt); } }
/** * Rende persistenti le modifiche all'anagrafica di un docente sul db * @param Admin $d il docente considerato * @param mysqli_stmt $stmt un prepared statement * @return int il numero di righe modificate */ private function salvaAdmin(admin $d, mysqli_stmt $stmt) { $query = " update admin set \n password = ?,\n nome = ?,\n cognome = ?,\n via = ?,\n civico = ?,\n citta = ?,\n cap = ?,\n telefono = ?,\n where admin.id = ?\n "; $stmt->prepare($query); if (!$stmt) { error_log("[salvaCliente] impossibile" . " inizializzare il prepared statement"); return 0; } if (!$stmt->bind_param('ssssissii', $d->getPassword(), $d->getNome(), $d->getCognome(), $d->getVia(), $d->getCivico(), $d->getCitta(), $d->getCap(), $d->getTelefono(), $d->getId())) { error_log("[salvaCliente] impossibile" . " effettuare il binding in input"); return 0; } if (!$stmt->execute()) { error_log("[caricaIscritti] impossibile" . " eseguire lo statement"); return 0; } return $stmt->affected_rows; }
<?php require_once "../resources/config.php"; require_once "./php/db_connect.php"; $adventureName = $mysqli->real_escape_string($_POST["adventureName"]); $country = $mysqli->real_escape_string($_POST["country"]); $city = $mysqli->real_escape_string($_POST["city"]); $description = $mysqli->real_escape_string($_POST["description"]); $adventure_id = $mysqli->real_escape_string($_POST["adventureID"]); $keywords = $mysqli->real_escape_string($_POST["keywords"]); $stmt = new mysqli_stmt($mysqli, "UPDATE adventures\n SET name = ?, country = ?, city = ?, description = ?, keywords = ? WHERE id= ?"); if ($stmt) { $stmt->bind_param("sssssi", $adventureName, $country, $city, $description, $keywords, $adventure_id); $stmt->execute(); } $mysqli->close(); $str = 'Location: ./adventure.php?id=' . $adventure_id; header($str);
<?php require_once "../resources/config.php"; require_once "./php/db_connect.php"; $advId = $_POST['adv_id']; $commentId = $_POST['id']; //echo "dump: " . var_dump($_POST) . "<br><br>"; $stmt = new mysqli_stmt($mysqli, "DELETE FROM comments WHERE id= ?"); if ($stmt) { $stmt->bind_param("i", $commentId); $stmt->execute(); } $mysqli->close(); header("location: ./adventure.php?id={$advId}");
$bindType = 's'; $search = "%" . $search . "%"; break; case "author": $query = "SELECT A.id, A.name FROM adventures A, users U WHERE A.user_id = U.id AND (CONCAT(first_name, ' ', last_name) LIKE ?)"; $bindType = 's'; $search = "%" . $search . "%"; break; case "votes": $query = "SELECT a.id, a.name\n FROM adventures a\n LEFT JOIN (\n SELECT id, COUNT(*) as rate, v.date\n FROM adventures a, votes v\n WHERE a.id = v.adv_id GROUP BY id\n ) v\n ON a.id = v.id\n WHERE (IFNULL(v.rate,0)+a.admin_vote) >= ?"; $bindType = 'i'; $search = (int) $search; break; } $stmt = new mysqli_stmt($mysqli, $query); if ($stmt->bind_param($bindType, $search)) { $stmt->execute(); $stmt->bind_result($id, $name); while ($stmt->fetch()) { $search_results["data"][] = array("id" => $id, "name" => $name); } } } } } // PRINT SEARCH RESULTS echo "<ul class='list-group'>"; foreach ($search_results["data"] as $key => $val) { ?> <li> <a href="./<?php
mysqli_stmt_store_result($stmtUser); // save variables if (mysqli_stmt_num_rows($stmtUser) == 1) { mysqli_stmt_fetch($stmtUser); $author['first_name'] = $fisrt_name; $author['last_name'] = $last_name; } } } // preapre adventure data $adventure = array(); $total_progress = 0; // adventure $stmtAdventure = new mysqli_stmt($mysqli, "SELECT a.id, a.name, a.description, rate.total_rate, p.id, p.file_ext\nFROM adventures a, photos p, users u, (\n\tSELECT a.id, (IFNULL(v.rate,0)+a.admin_vote) as total_rate\n\tFROM adventures a\n\tLEFT JOIN (\n\t\tSELECT id, COUNT(*) as rate, v.date\n\t\tFROM adventures a, votes v\n\t\tWHERE a.id = v.adv_id\n\t\tGROUP BY id\n\t) v\n\tON a.id = v.id\n) rate\nWHERE a.user_id = u.id\nAND u.id = ?\nAND a.id = rate.id\nAND (p.adv_id = a.id\nAND p.is_cover = 1)\nORDER BY rate.total_rate"); if ($stmtAdventure) { $stmtAdventure->bind_param("i", $author['id']); if ($stmtAdventure->execute()) { $stmtAdventure->bind_result($ad_id, $name, $ad_description, $rate, $photoid, $photoext); while ($stmtAdventure->fetch()) { $adventure[] = array('id' => $ad_id, 'description' => $ad_description, 'name' => $name, 'pid' => $photoid, 'rate' => $rate, 'pext' => $photoext); } } } //$ad_total = $total_progress; foreach ($adventure as $stone) { ?> <div id="top1" class="container"> <div class="row"> <div class="col-md-3"> <img
} } } } } } } ?> <?php $commentArray[] = array(); $sql = "SELECT * FROM comments WHERE adv_id = {$adv_id}"; $res = $mysqli->query($sql) or trigger_error($mysqli->error . "[{$sql}]"); while ($row = $res->fetch_assoc()) { $stmt3 = new mysqli_stmt($mysqli, "SELECT first_name, last_name FROM users WHERE id = ?"); $stmt3->bind_param("i", $row['user_id']); $stmt3->execute(); $stmt3->bind_result($commentFirstName, $commentLastName); $stmt3->store_result(); if ($stmt3->num_rows() == 1) { while ($stmt3->fetch()) { ?> <div class="row"> <div class="col-md-6 col-md-offset-1 comments-section"> <section> <div class="">
<?php require_once "../resources/config.php"; require_once "./php/db_connect.php"; $advId = $_POST['adv_id']; $userId = $_POST['user_id']; $date = date("Y-m-d H:i:s"); $stmt = new mysqli_stmt($mysqli, "INSERT INTO votes (user_id, adv_id, date) VALUES (?, ?, ?)"); if ($stmt) { $stmt->bind_param("iis", $userId, $advId, $date); $stmt->execute(); } $mysqli->close(); header("location: ./adventure.php?id={$advId}");
/** * Связывает параметр с заданным значением * * @param \mysqli_stmt $stmt * Экземпляр запроса * @param string|array $values * Значение или массив значений * которые нужно привязать к запросу * * @return bool * Возвращает TRUE в случае успешного завершения * или FALSE в случае возникновения ошибки. */ private function bindValue($stmt, $values) { if (is_string($values) || is_numeric($values)) { $stmt->bind_param('s', $values); } elseif (is_array($values)) { foreach ($values as $value) { if (is_int($value)) { $stmt->bind_param('i', $value); } else { $stmt->bind_param('s', $value); } } } return true; }
<?php require_once "../resources/config.php"; require_once "./php/db_connect.php"; $advId = $_POST['adv_id']; $commentId = $_POST['id']; $editedComment = $mysqli->real_escape_string($_POST['editComment']); $date = date("Y-m-d H:i:s"); //echo "dump: " . var_dump($_POST) . "<br><br>"; $stmt = new mysqli_stmt($mysqli, "UPDATE comments\n SET comment = ?, date = ? WHERE id= ?"); if ($stmt) { $stmt->bind_param("ssi", $editedComment, $date, $commentId); $stmt->execute(); } $mysqli->close(); header("location: ./adventure.php?id={$advId}");
<?php require_once "../resources/config.php"; require_once "./php/db_connect.php"; $id = $_POST['id']; $adventure_id = $_POST['adv_id']; //echo "dump: " . var_dump($_POST) . "<br><br>"; $stmt = new mysqli_stmt($mysqli, "DELETE FROM photos WHERE id= ?"); if ($stmt) { $stmt->bind_param("i", $id); $stmt->execute(); } $mysqli->close(); $str = 'Location: ./adventure.php?id=' . $adventure_id; header($str);
<?php require_once "../resources/config.php"; require_once "./php/db_connect.php"; $advId = $mysqli->real_escape_string($_POST['adv_id']); $userId = $mysqli->real_escape_string($_POST['user_id']); $comment = $mysqli->real_escape_string($_POST['comment']); $date = date("Y-m-d H:i:s"); $stmt = new mysqli_stmt($mysqli, "INSERT INTO comments (user_id, adv_id, comment, date) VALUES (?, ?, ?, ?)"); if ($stmt) { $stmt->bind_param("iiss", $userId, $advId, $comment, $date); $stmt->execute(); } else { echo "stmt error"; } echo "eror: " . $mysqli->error; $mysqli->close(); header("location: ./adventure.php?id={$advId}");
<?php require_once "../resources/config.php"; require_once "./php/db_connect.php"; $adventureID = $_POST["test"]; echo $adventureID; $stmt = new mysqli_stmt($mysqli, "DELETE FROM adventures WHERE id = ?"); if ($stmt) { $stmt->bind_param("i", $adventureID); $stmt->execute(); } $str = 'Location: ./index '; header($str); $mysqli->close(); header("location: ./index.php"); ?>
<?php require_once "../resources/config.php"; require_once "./php/db_connect.php"; $advId = $_POST['adv_id']; $adminVote = $_POST['admin_votes']; $stmt = new mysqli_stmt($mysqli, "UPDATE adventures SET admin_vote = ? WHERE id = ?"); if ($stmt) { $stmt->bind_param("ii", $adminVote, $advId); $stmt->execute(); } $mysqli->close(); header("location: ./adventure.php?id={$advId}");
if ($stmt) { $cov = 1; $stmt->bind_param("iissi", $userID, $adventure_id, $ext, $dateNow, $cov); if ($stmt->execute()) { $id = $stmt->insert_id; $success = TRUE; } } // On this example, obtain safe unique name from its binary data. if ($success) { if (!move_uploaded_file($photoFile['tmp_name'], sprintf('./img/contents/%s.%s', $id, $ext))) { throw new RuntimeException('Failed to move uploaded file.'); } } else { echo "nothing inserted into db"; } echo 'File is uploaded successfully.'; } catch (RuntimeException $e) { echo $e->getMessage(); } } if (privilegeCheck($mysqli, $userID) != 0) { $stmt = new mysqli_stmt($mysqli, "UPDATE users SET privilege = ? WHERE id = ? "); if ($stmt) { $priv = 1; $stmt->bind_param("ii", $priv, $userID); $stmt->execute(); } } $str = 'Location: ./adventure.php?id=' . $adventure_id; header($str);
function isUserVerified($mysqli, $userID) { $stmt = new mysqli_stmt($mysqli, "SELECT verified FROM users WHERE id = ?"); if ($stmt) { $stmt->bind_param('i', $userID); $stmt->execute(); $result = $stmt->get_result()->fetch_object(); if ($result->verified == TRUE) { return TRUE; } else { return FALSE; } } else { return FALSE; } }
private function _addErrorToDbLog($message, $stackTraceAsString) { $this->_insertToErrorLogStatement->bind_param("ss", $message, $stackTraceAsString); $this->_insertToErrorLogStatement->execute(); }
} // You should also check filesize here. if ($photoFile['size'] > 5242880) { throw new RuntimeException('Exceeded filesize limit.'); } // Check MIME Type by yourself. $finfo = new finfo(FILEINFO_MIME_TYPE); if (false === ($ext = array_search($finfo->file($photoFile['tmp_name']), array('jpg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif'), true))) { throw new RuntimeException('Invalid file format.'); } $id = -1; $dateNow = date("Y-m-d H:i:s"); $stmt = new mysqli_stmt($mysqli, "INSERT INTO photos (user_id, adv_id, file_ext, date) VALUES (?, ?, ?, ?) "); $success = FALSE; if ($stmt) { $stmt->bind_param("iiss", $_POST['user_id'], $_POST['adv_id'], $ext, $dateNow); if ($stmt->execute()) { $id = $stmt->insert_id; $success = TRUE; } } // On this example, obtain safe unique name from its binary data. if ($success) { if (!move_uploaded_file($photoFile['tmp_name'], sprintf('../img/contents/%s.%s', $id, $ext))) { throw new RuntimeException('Failed to move uploaded file.'); } } else { echo "nothing inserted into db"; } echo 'File is uploaded successfully.'; } catch (RuntimeException $e) {
throw new RuntimeException('Exceeded filesize limit.'); default: throw new RuntimeException('Unknown errors.'); } // You should also check filesize here. if ($photoFile['size'] > 5242880) { throw new RuntimeException('Exceeded filesize limit.'); } // Check MIME Type by yourself. $finfo = new finfo(FILEINFO_MIME_TYPE); if (false === ($ext = array_search($finfo->file($photoFile['tmp_name']), array('jpg' => 'image/jpeg', 'png' => 'image/png', 'gif' => 'image/gif'), true))) { throw new RuntimeException('Invalid file format.'); } $dateNow = date("Y-m-d H:i:s"); $success = FALSE; // On this example, obtain safe unique name from its binary data. if (!move_uploaded_file($photoFile['tmp_name'], sprintf('./img/profile/%s.%s', $user_id, $ext))) { throw new RuntimeException('Failed to move uploaded file.'); } else { $stmt = new mysqli_stmt($mysqli, "UPDATE users SET file_ext = ? WHERE id = ?"); if ($stmt) { $stmt->bind_param("si", $ext, $user_id); $stmt->execute(); } } echo 'File is uploaded successfully.'; } catch (RuntimeException $e) { echo $e->getMessage(); } $str = 'Location: ./author.php?id=' . $user_id; header($str);
/** * Rende persistenti le modifiche all'anagrafica di un admin sul db * @param Admin $a l'admin considerato * @param mysqli_stmt $stmt un prepared statement * @return int il numero di righe modificate */ private function salvaAdmin(Admin $a, mysqli_stmt $stmt) { $query = " update admins set \n password = ?,\n nome = ?,\n cognome = ?,\n email = ?,\n where admins.id = ?\n "; $stmt->prepare($query); if (!$stmt) { error_log("[salvaAdmin] impossibile" . " inizializzare il prepared statement"); return 0; } if (!$stmt->bind_param('ssssi', $a->getPassword(), $a->getNome(), $a->getCognome(), $a->getEmail(), $a->getId())) { error_log("[salvaAdmin] impossibile" . " effettuare il binding in input"); return 0; } if (!$stmt->execute()) { error_log("[caricaRegistrati] impossibile" . " eseguire lo statement"); return 0; } return $stmt->affected_rows; }
/** * Binds the given parameters to the given statement. * * @param \mysqli_stmt $statement * @param mixed[] $parameters * * @return \mysqli_stmt */ private function bindParameters($statement, array $parameters) { $variables = []; foreach (array_keys($parameters) as $key) { if (!is_array($parameters[$key])) { $variables[] =& $parameters[$key]; } else { foreach (array_keys($parameters[$key]) as $k) { $variables[] =& $parameters[$key][$k]; } } } $statement->bind_param($this->buildTypes($parameters), ...$variables); }