/** * Processes the query and returns the data. * @param $query string The SQL query to process * @param null $return_type How to return the result (MYSQLI_ASSOC, MYSQLI_NUM, etc.) */ function process_query($query, $connection, $return_type = null) { // if the connection is broken, make a new one if (!$connection) { unset($connection); $connection = create_connection(); } // the name of the database to connect to $database_name = Constant::database_name; // select the database to process the query in mysqli_select_db($connection, $database_name); if (is_null($return_type)) { // return type is null, so just "run" the query return mysqli_query($connection, $query); } else { // the result when the query is processed $result = mysqli_query($connection, $query); while ($row = mysqli_fetch_array($result, $return_type)) { $row_results[] = $row; } mysqli_free_result($result); // return the row results if it is set (i.e. the while loop was executed), // else just return an empty array return isset($row_results) ? $row_results : array(); } }
function UserMailInfo($userid) { if (create_connection($connection)) { $userInfo = getUserInfo($connection, $userid); //0: id 1: username 2: mail 3: password 4: salt 5: apikey_write 6: apikey_read 7: lastlogin 8: admin 9: gravatar 10: name 11: location 12: timezone 13: language 14: bio if ($userInfo != null) { echo "Buscando alarmas para usuario: [" . $userInfo[0] . "] " . $userInfo[1] . " - " . $userInfo[10] . "<br>"; $userActiveAlarms = getUserActiveAlarms($connection, $userid); $userRadPowerAlarms = getUserRadPowerAlarms($connection, $userid); $userAlarms = array_merge($userActiveAlarms, $userRadPowerAlarms); if (count($userAlarms) > 0) { echo "Alarmas encontradas, enviando mensaje...<br>"; $bodyText = formatMailBody($userAlarms); $subject = "Alarmas detectadas - ISMSOLAR"; $mailbody = file_get_contents("/var/www/html/ewatcher-users/MailBody.html"); $mailbody = str_replace("[BODY]", $bodyText, $mailbody); $MailSentOk = sendMail($mailbody, $subject, $userInfo[2], $userInfo[10]); if ($MailSentOk) { echo "llamando a markAlarmsAsNotified<br>"; markAlarmsAsNotified($connection, $userAlarms); } } else { echo "No se encontraron alarmas activas para notificar.<br>"; } } } else { echo "Error de conexión a la base de datos...<br>"; } }
function username_is_free($username) { $connection = create_connection(); $query = 'SELECT * FROM User WHERE username = "******";'; $result = $connection->query($query); if ($result->num_rows > 0) { return false; } else { return true; } }
/** * Increments the number of times a profile has been viewed in the database. * Yay storing user data! */ public function increment_profile_view_counter() { $viewer_id = $this->viewer_user->user_row["UserID"]; $viewed_id = $this->viewed_user->user_row["UserID"]; // God I hate these sql queries $sql_query = 'INSERT INTO ' . Constant::profile_views_database_name . ' VALUES '; $sql_query .= '(' . $viewer_id . ', ' . $viewed_id . ', 1)'; $sql_query .= ' ON DUPLICATE KEY UPDATE `ProfileViews` = `ProfileViews` + 1;'; $connection = create_connection(); // process the query process_query($sql_query, $connection); close_connection($connection); }
function create_linked_user($username, $email, $password, $panelType) { // Global variables global $redis_enabled, $redis_server; // Connect to the DB $ret = create_connection($connection); if ($ret !== true) { return $ret; } // Connect to Redis if ($redis_enabled === true) { $redis = new Redis(); if (!$redis->connect($redis_server)) { $redis = false; } } else { $redis = false; } // Validate input $ret = validate_input($username, $email, $password, $panelType); if ($ret !== true) { end_connection(true, $connection); return $ret; } // Create user if (create_user($username, $email, $password, $userid, $apikey, $connection) !== true) { end_connection(true, $connection); return 'Username already exists'; } // Set the type of user profile $prefix = 'data/' . $panelType; // Create feeds if (create_feeds($prefix . '_feeds.json', $feeds, $apikey) !== true) { end_connection(true, $connection); return 'Error while creating the feeds'; } // Create inputs if (create_inputs($prefix . '_inputs.json', $userid, $inputs, $connection, $redis) !== true) { end_connection(true, $connection); return 'Error while creating the inputs'; } // Create processes if (create_processes($prefix . '_processes.json', $feeds, $inputs, $apikey) !== true) { end_connection(true, $connection); return 'Error while creating the processes'; } end_connection(false, $connection); return true; }
function delete_user($username) { // Connect to the DB $ret = create_connection($connection); if ($ret !== true) { return $ret; } // Validate input $ret = validate_input($username); if ($ret !== true) { $connection->close(); return $ret; } // Get user data $user_data = get_user_data($username, $connection); if ($user_data === false) { $connection->close(); return 'Username provided does not exist'; } // Delete feeds if (delete_feeds($user_data, $connection) !== true) { $connection->close(); return 'Error while deleting the feeds'; } // Delete inputs if (delete_inputs($user_data, $connection) !== true) { $connection->close(); return 'Error while deleting the inputs'; } // Delete EWatcher panels if (delete_ewatcher($user_data, $connection) !== true) { $connection->close(); return 'Error while deleting user configuration (EWatcher)'; } // Delete user if (delete_user_data($user_data, $connection) !== true) { $connection->close(); return 'Error while deleting user data'; } $connection->close(); return true; }
function session_login($username, $password) { $connection = create_connection(); $query = 'SELECT * FROM User WHERE username = "******";'; $result = $connection->query($query); if ($result->num_rows > 0) { $row = $result->fetch_assoc(); if ($password == $row['password']) { //this is for correct login if (!$_SESSION) { session_start(); } $_SESSION['username'] = $row['username']; determine_role($connection, $username); return true; } else { //this is for incorrect pass return false; } } else { //this is for username doesnt exist return false; } }
//釋放記憶體空間 mysql_free_result($result); mysql_close($link); ?> <hr> <form name="myForm" method="post" action="post_replyB.php"> <input type="hidden" name="reply_id" value="<?php echo $id; ?> "> <table border="0" width="800" align="center" cellspacing="0"> <tr bgcolor="#0084CA" align="center"> <td colspan="2"><font color="white">請在此輸入您的回覆</font></td> </tr> <?php $link = create_connection() or die("connecting fails!"); $username = $_SESSION['username']; $sql = "SELECT name FROM business Where account = '{$username}'"; $result = execute_sql("user", $sql, $link); mysql_close($link); ?> <tr bgcolor="#D9F2FF"> <td width="15%">使用者</td> <td width="85%"><input name="author" type="text" value="<?php echo mysql_result($result, 0, 0); ?> " size="50" readonly></td> </tr> <tr bgcolor="#D9F2FF"> <td width="15%">內容</td> <td width="85%"><textarea name="content" cols="50" rows="5"></textarea></td>
require_once "dbtools.inc.php"; header("Content-type:text/html;charset=utf-8"); //取得新增的使用者帳號與人數! $new_account = $_POST["new_account"]; $new_people = $_POST["new_people"]; $new_key = random(8); function random($length) { $key = ''; $pattern = "1234567890"; for ($i = 0; $i < $length; $i++) { $key .= $pattern[rand(0, 9)]; } return $key; } $link = create_connection(); $sql = "SELECT * FROM nfc Where account='{$new_account}'"; $result = execute_sql("nfc", $sql, $link); //若帳號已有人用 if (mysql_num_rows($result) != 0) { mysql_free_result($result); $check = false; echo "failed"; echo "<script type='text/javascript'>"; echo "alert('您所設定的帳號已有人使用,請更換其他帳號!')"; echo "history.back()"; echo "</script>"; } else { mysql_free_result($result); //執行SQL指令直接新增帳號與人數 $sql = "INSERT INTO nfc(account,people,keynumber)VALUES('{$new_account}','{$new_people}','{$new_key}')";
/** * @param $user_id int The id of the user whose user row to retrieve from the database. * @return array The array containing the row of the user, if it exists. */ public static function get_user_row_by_id($user_id) { $sql_query = 'SELECT * FROM `' . Constant::user_database_name . '` '; $sql_query .= 'WHERE UserID="' . $user_id . '";'; $connection = create_connection(); // the user row with the particular id; it could be empty $user_row = process_query($sql_query, $connection, MYSQLI_ASSOC); // close the connection before exiting the function close_connection($connection); // returns an empty array if the user row doesn't exists return empty($user_row) ? array() : $user_row; }
/** * Reset database */ function reset_database($con) { // Set number of results to zero $query = "UPDATE excerpts SET v1Results = 0, v2Results = 0, v3Results = 0, \n totalResults = 0"; my_exec_query($con, $query); // Delete all results $query = "DELETE FROM results"; my_exec_query($con, $query); // Delete all results $query = "DELETE FROM subjects"; my_exec_query($con, $query); // Close DB connection mysqli_close($con); $con = create_connection(); // Reset auto increment indeces $query = "ALTER TABLE results AUTO_INCREMENT = 0"; my_exec_query($con, $query); $query = "ALTER TABLE subjects AUTO_INCREMENT = 0"; my_exec_query($con, $query); return $con; }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- Oriol Nieto oriol -at- nyu -dot- edu MARL, NYU --> <?php require 'utils.php'; // Establish DB connection $con = create_connection(); // Sanitize strings before inserting into dataset $first_name = sanitize_str($con, $_POST['first_name']); $last_name = sanitize_str($con, $_POST['last_name']); $email = sanitize_str($con, $_POST['email']); $music_training = sanitize_str($con, $_POST['music_training']); $comments = sanitize_str($con, $_POST['comments']); // Update Subject update_subject($con, $first_name, $last_name, $email, $music_training, $comments, $_POST['subjectID']); // Send email $email_message = "You have a new result!"; $headers = 'From: ' . $first_name . "\r\n" . 'Reply-To: oriol@nyu.edu' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); @mail("*****@*****.**", "Boundaries Experiment", $email_message, $headers); // Close DB connection mysqli_close($con); ?> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" />
<?php create_connection('localhost', 1740); function create_connection($host, $port) { $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if (!is_resource($socket)) { echo 'Unable to create socket: ' . socket_strerror(socket_last_error()) . PHP_EOL; } else { echo "Socket created.\n"; } if (!socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1)) { echo 'Unable to set option on socket: ' . socket_strerror(socket_last_error()) . PHP_EOL; } else { echo "Set options on socket.\n"; } if (!socket_bind($socket, $host, $port)) { echo 'Unable to bind socket: ' . socket_strerror(socket_last_error()) . PHP_EOL; } else { echo "Socket bound to port {$port}.\n"; } if (!socket_listen($socket, SOMAXCONN)) { echo 'Unable to listen on socket: ' . socket_strerror(socket_last_error()); } else { echo "Listening on the socket.\n"; } while (true) { $connection = @socket_accept($socket); if ($connection) { echo "Client {$connection} connected!\n"; send_data($connection);
<?php set_time_limit(15); // Define uma informação para testes, apenas $config->test = true; // Cria uma conexão padrão if (is_localhost()) { create_connection('mysqli://root@127.0.0.1/core_project'); } // Cria uma conexão falsa, para testes create_connection('mysqli://*****:*****@servername:1234/dbname' . '?persistent=false&charset=latin1&connect=false', 'fake'); create_connection('mysqli://fakeserver', 'fake2'); create_connection('fakeserver', 'fake3'); // Inclui alguns arquivos que não vão para o commit if (CORE_DEBUG === true && is_file(dirname(__FILE__) . '/configs.extra.php')) { require dirname(__FILE__) . '/configs.extra.php'; }
function client_rate_coupon($coupon_id, $rating) { $connection = create_connection(); $coupon = search_coupon_by_id($coupon_id); $number_of_ratings = $coupon->number_of_ratings + 1; $avg_rating = ($coupon->rating * $coupon->number_of_ratings + $rating) / $number_of_ratings; $query = "UPDATE Coupon SET rating = '" . $avg_rating . "', number_of_ratings = '" . $number_of_ratings . "' WHERE coupon_id = '" . $coupon_id . "'"; $connection->query($query) or trigger_error($connection->error); }
<!DOCTYPE html> <html> <?php include 'header.php'; include 'db_functions.php'; print "<body>"; $db_connection = create_connection("localhost", "cs143", ""); print "<h2>Movies! <a href='movie_form.php'>(Add)</a></h2>"; $random_movies_query = "select * from Movie order by rand() limit 5"; $random_movies = run_query($random_movies_query, $db_connection); print "<ul>"; while ($random_movie_row = mysql_fetch_array($random_movies, MYSQL_ASSOC)) { $movie_id = $random_movie_row['id']; $movie_tag = $random_movie_row['title'] . " " . $random_movie_row['rating'] . " (" . $random_movie_row['year'] . ")"; $movie_link = "movie.php?movie_id={$movie_id}"; print "<li><a href={$movie_link}>{$movie_tag}</a></li>"; } print "</ul>"; print "<hr/>"; print "<h2>Actors! <a href='actor_form.php'>(Add)</a></h2>"; $random_actors_query = "select * from Actor order by rand() limit 5"; $random_actors = run_query($random_actors_query, $db_connection); print "<ul>"; while ($random_actor_row = mysql_fetch_array($random_actors, MYSQL_ASSOC)) { $actor_id = $random_actor_row['id']; $actor_tag = $random_actor_row['first'] . " " . $random_actor_row['last'] . " (" . $random_actor_row['dob'] . ")"; $actor_link = "actor.php?actor_id={$actor_id}"; print "<li><a href={$actor_link}>{$actor_tag}</a></li>"; } print "</ul>"; print "<hr/>";
function delete_manager($manager_username) { $connection = create_connection(); $query1 = "DELETE FROM Manager WHERE manager_username= '******'"; $query2 = "DELETE FROM User WHERE username= '******'"; $connection->query($query1) or trigger_error($connection->error); $connection->query($query2) or trigger_error($connection->error); }
/** * Increments the number of times the user has logged in. */ public function increment_login_counter() { $user_id = $this->user_row[0]["UserID"]; $sql_query = 'INSERT INTO `' . Constant::login_count_database_name . '`(`UserID`, `LoginTimes`) '; $sql_query .= 'VALUES (' . $user_id . ', 1) ON DUPLICATE KEY UPDATE '; $sql_query .= '`LoginTimes` = `LoginTimes` + 1;'; $connection = create_connection(); process_query($sql_query, $connection); close_connection($connection); return $sql_query; }