本文整理汇总了PHP中CS50类的典型用法代码示例。如果您正苦于以下问题:PHP CS50类的具体用法?PHP CS50怎么用?PHP CS50使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了CS50类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: render_next
/**
* Renders the next profile to view.
*/
function render_next()
{
//find current viewnum
$viewNum = CS50::query("SELECT viewNum FROM users WHERE id = ?", $_SESSION["id"]);
$viewnum = $viewNum[0]["viewNum"];
//find id of last viable profile
$last = CS50::query("SELECT MAX(id) FROM users");
//increment viewnum to next viable profile
do {
CS50::query("UPDATE users SET viewNum = viewNum + 1 WHERE id = ?", $_SESSION["id"]);
$viewnum++;
if ($viewnum > $last[0]["MAX(id)"]) {
apologize("You've seen e'rybody!");
break;
}
} while (count(CS50::query("SELECT * FROM users WHERE id = ?", $viewnum)) == 0 || $viewnum == $_SESSION["id"]);
// render homepage; show new profile.
render("home.php", ["title" => "home", "profile" => prof_lookup($viewnum)]);
}
示例2: foreach
<?php
//configuration
require "../includes/config.php";
//query portfolio
$rows = CS50::query("SELECT * FROM portfolios WHERE user_id = ?", $_SESSION["id"]);
//new array to story portfolio contents
$positions = [];
//go through each row
foreach ($rows as $row) {
//look up symbol from row's stock on Yahoo
$stock = lookup($row["symbol"]);
//if look up was successful
if ($stock !== false) {
//fill information into array 'positions'
$positions[] = ["name" => $stock["name"], "symbol" => $row["symbol"], "price_per_stock" => $stock["price"], "shares" => $row["shares"], "total_price" => $stock["price"] * $row["shares"]];
}
}
//query user's cash
$cash = CS50::query("SELECT cash FROM users WHERE id = ?", $_SESSION["id"]);
//render portfolio
render("portfolio.php", ["positions" => $positions, "title" => "Portfolio", "cash" => $cash]);
示例3: user_events
<?php
// Mostly original code
// configuration
require "../startbootstrap-business-casual-1.0.4/config.php";
//query username from users and stock from recruiter_userss
$rows = CS50::query("SELECT company, event_date, event_time FROM events WHERE school = ? AND company= ?", $_POST["school"], $_POST["company"]);
if ($rows != false) {
$new_insertion = CS50::query("INSERT INTO user_events (company, event_time, event_date, user_id) \n VALUES (?, ?, ?, ?)", $_POST["company"], $rows[0]["event_time"], $rows[0]["event_date"], $_SESSION["id"]);
if ($new_insertion !== false) {
redirect("students.php");
}
} else {
apologize("sorry, there is no event for this company");
}
示例4: apologize
// validate inputs
if (empty($_POST["username"])) {
apologize("You must provide a username.");
} else {
if (empty($_POST["password"])) {
apologize("You must provide a password.");
} else {
if (empty($_POST["confirmation"]) || $_POST["password"] != $_POST["confirmation"]) {
apologize("Those passwords did not match.");
}
}
}
// try to register user
$rows = CS50::query("INSERT IGNORE INTO users (username, hash) VALUES(?, ?)", $_POST["username"], password_hash($_POST["password"], PASSWORD_DEFAULT));
if ($rows !== 1) {
apologize("That username appears to be taken.");
}
// get new user's ID
$rows = CS50::query("SELECT LAST_INSERT_ID() AS id");
if (count($rows) !== 1) {
apologize("Can't find your ID.");
}
$id = $rows[0]["id"];
// log user in
$_SESSION["id"] = $id;
// redirect to portfolio
redirect("/");
} else {
// else render form
render("register_form.php", ["title" => "Register"]);
}
示例5: init
/**
* Initializes library with JSON file at $path.
*/
public static function init($path)
{
// ensure library is not already initialized
if (isset(self::$config)) {
trigger_error("CS50 Library is already initialized", E_USER_ERROR);
}
// ensure configuration file exists
if (!is_file($path)) {
trigger_error("Could not find {$path}", E_USER_ERROR);
}
// read contents of configuration file
$contents = file_get_contents($path);
if ($contents === false) {
trigger_error("Could not read {$path}", E_USER_ERROR);
}
// decode contents of configuration file
$config = json_decode($contents, true);
if (is_null($config)) {
trigger_error("Could not decode {$path}", E_USER_ERROR);
}
// store configuration
self::$config = $config;
}
示例6: while
}
// check for negative service
for ($j = -3; $j <= 3; $j++) {
// check if i + j within array.
if ($i + $j >= 0 && $i + $j < $terms) {
// check up to three words before and after, as well as tracker[$i] itself.
if (strpos($tracker[$i + $j], 'service') !== false) {
// update service score if location given in comment
if ($info[0]["place_name"] != '') {
$updatefoodscore = CS50::query("UPDATE locations SET service_score = service_score - 1 WHERE place_name = ?", $info[0]["place_name"]);
} else {
$updatefoodscore = CS50::query("UPDATE locations SET service_score = service_score - 1 WHERE place_name = ''");
}
}
}
}
}
}
// mark comment as processed
$processed = CS50::query("UPDATE comments SET processed = true WHERE id = ?", $info[0]["id"]);
}
} while (count($info) !== 0);
// retrieve scores for all locations
$scores = CS50::query("SELECT place_name, comments_received, overall_score, food_score, service_score FROM locations");
// array to store scores
$locations = [];
foreach ($scores as $score) {
$locations[] = ["location" => $score["place_name"], "num_comments" => $score["comments_received"], "overall" => $score["overall_score"], "food" => $score["food_score"], "service" => $score["service_score"]];
}
// render analysis_view
render("analysis_view.php", ["locations" => $locations, "title" => "Analysis"]);
示例7: MATCH
<?php
// include functions in config.php
require __DIR__ . "/../includes/config.php";
// numerically indexed array of places
$places = [];
// Declare variable geo
$geo = $_GET["geo"];
// Query database for the search key to find places that match that and return a variable with that data
$places = CS50::query("SELECT * FROM places WHERE MATCH (country_code, postal_code, place_name, admin_name1, admin_code1) AGAINST (?)", $geo);
// output places as JSON (pretty-printed for debugging convenience)
header("Content-type: application/json");
print json_encode($places, JSON_PRETTY_PRINT);
示例8: lookup
$shares = $rows[0]["shares"];
// sell shares
$stock = lookup($_POST["symbol"]);
if ($stock !== false) {
// update portfolio
CS50::query("DELETE FROM portfolios WHERE user_id = ? AND symbol = ?", $_SESSION["id"], $_POST["symbol"]);
// update cash
CS50::query("UPDATE users SET cash = cash + ? WHERE id = ?", $shares * $stock["price"], $_SESSION["id"]);
// update history
CS50::query("INSERT INTO history (user_id, type, symbol, shares, price, datetime)\n VALUES(?, 'SELL', ?, ?, ?, NOW())", $_SESSION["id"], $stock["symbol"], $shares, $stock["price"]);
// redirect user
redirect("/");
}
} else {
// get user's portfolio
$symbols = [];
$rows = CS50::query("SELECT symbol FROM portfolios WHERE user_id = ? ORDER BY symbol", $_SESSION["id"]);
if ($rows === false) {
apologize("Could not find your portfolio.");
}
// get symbols in portfolio
foreach ($rows as $row) {
$symbols[] = $row["symbol"];
}
// render form
if (count($symbols) > 0) {
render("sell_form.php", ["symbols" => $symbols, "title" => "Sell"]);
} else {
apologize("Nothing to sell.");
}
}
示例9: apologize
apologize("Wasn't able to retreive shares to sell from database");
return;
}
//delete sold stock from database
$deleted = CS50::query("DELETE FROM portfolio WHERE user_id = ? AND symbol = ?", $_SESSION["id"], $_POST["symbol"]);
if (!$deleted) {
apologize("Wasn't able to delete shares from database");
return;
}
//lookup symbol for current price
$stock = lookup($_POST["symbol"]);
if (!$stock) {
apologize("Wasn't able to lookup symbol");
return;
}
//update cash with profit from sold stock
$updated = CS50::query("UPDATE users SET cash = cash + ? WHERE id = ?", $stock["price"] * $shares[0]["shares"], $_SESSION["id"]);
if (!$updated) {
apologize("Wasn't able to update cash in database");
return;
}
//insert this transaction into history
$updatedHistory = CS50::query("INSERT INTO history (user_id, symbol, transaction, shares, price, time) \n VALUES(?, ?, 'sell', 0, ?, NOW())", $_SESSION["id"], strtoupper($_POST["symbol"]), $stock["price"]);
if (!$updatedHistory) {
apologize("Wasn't able to update history will sell transaction");
return;
}
redirect("/");
} else {
render("sell_form.php");
}
示例10: VALUES
<?php
// configuration
require "../includes/config.php";
// if form was submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_POST['interest']) {
//This is to add an interest to the database
CS50::query("INSERT INTO `interests` (`user_id`, `interest`) VALUES (?,?)", $_SESSION["id"], $_POST['interest']);
}
redirect("index.php");
} else {
// render form
redirect("index.php");
}
?>
示例11: render
<!-- original code -->
<?php
// configuration
require "../startbootstrap-business-casual-1.0.4/config.php";
// if user reached page via GET (as by clicking a link or via redirect)
if ($_SERVER["REQUEST_METHOD"] == "GET") {
// else render form
render("students.html", ["title" => "buy"]);
} else {
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Record Input
CS50::query("INSERT INTO student_update (FirstName, LastName, Email, University) VALUES (?, ?, ?,?)", $_POST["FirstName"], $_POST["LastName"], $_POST["Email"], $_POST["University"]);
}
}
redirect("/");
示例12: apologize
} else {
if (empty($_POST["newpassword"])) {
apologize("You must produce a password");
} else {
if (empty($_POST["confirmation"])) {
apologize("You must produce a password");
} else {
if ($_POST["newpassword"] != $_POST["confirmation"]) {
apologize("Passwords must match");
} else {
$userstats = CS50::query("SELECT * FROM users WHERE id = ?", $_SESSION["id"]);
$username = $userstats[0]["username"];
// check username for correctnes
if ($username != $_POST["username"]) {
apologize("Wrong username");
} else {
if (!password_verify($_POST["oldpassword"], $userstats[0]["hash"])) {
apologize("Wrong original password");
} else {
// update password
CS50::query("UPDATE users SET hash=? where id =?", password_hash($_POST["newpassword"], PASSWORD_DEFAULT), $_SESSION["id"]);
redirect("index.php");
}
}
}
}
}
}
}
}
}
示例13: PostmarkClient
// Store id of article in variable
$article = $_POST["article_id"];
// update mySQL
CS50::query("UPDATE portfolio SET status = 3 WHERE id = ?", $article);
// set submission destination and subject
$email_to = "phillyfan362@gmail.com";
$email_subject = "Crimson Article Submission";
// Actual article text variable
$articles = $_POST['articles'];
// Start of email message
$email_message = "Form details below.\n\n";
// Get title of article
$pieces = CS50::query("SELECT title FROM portfolio WHERE id = ?", $article);
$piece = $pieces[0]["title"];
// Get name of comper
$compers = CS50::query("SELECT name, email FROM users WHERE userid = ?", $_SESSION["id"]);
$name = $compers[0]["name"];
$email = $compers[0]["email"];
// Craft e-mail message body
$email_message .= "Comper: " . $name . "\r\n";
$email_message .= "Article Title: " . $piece . "\r\n";
$email_message .= "Comments: " . $articles . "\r\n";
$client = new PostmarkClient("211bda55-ecef-447c-ba35-7b2ca54e802f");
// Send email
$sendResult = $client->sendEmail("manavkhandelwal@college.harvard.edu", "phillyfan362@gmail.com", "Comper Article Submissions", "{$email_message}");
// Redirect
redirect("/");
} else {
if ($_SERVER["REQUEST_METHOD"] == "GET") {
redirect("/");
}
示例14: ini_set
<?php
/**
* config.php
*
* Computer Science 50
* Veritalks
*
* Configures app.
*/
// display errors, warnings, and notices
ini_set("display_errors", true);
error_reporting(E_ALL);
// requirements
require "helpers.php";
// CS50 Library
require "../vendor/library50-php-5/CS50/CS50.php";
CS50::init(__DIR__ . "/../config.json");
// enable sessions
session_start();
// require authentication for certain pages except those listed below
if (!in_array($_SERVER["PHP_SELF"], ["/login.php", "/logout.php", "/register.php", "/main_page.php", "/about_us.php", "/ask_question.php", "/give_advice.php", "/upvote.php", "/user.php", "/academics.php", "/social_scene.php", "/student_life.php", "/real_world.php", "/prospective_students.php", "/financial_aid.php", "/academics_user.php", "/social_scene_user.php", "/student_life_user.php", "/real_world_user.php", "/prospective_students_user.php", "/financial_aid_user.php", "/academics_upvote.php", "/social_scene_upvote.php", "/student_life_upvote.php", "/real_world_upvote.php", "/prospective_students_upvote.php", "/financial_aid_upvote.php"])) {
if (empty($_SESSION["id"])) {
redirect("main_page.php");
}
}
示例15: apologize
<?php
//configuration
require "../includes/config.php";
//create new array to store history information
$history = CS50::query("SELECT * FROM history WHERE user_id = ?", $_SESSION["id"]);
if (count($history) == 0) {
apologize("No transactions recorded.");
}
// dump($history);
//render buy form
render("history_form.php", ["title" => "History", "history" => $history]);