blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
116
path
stringlengths
2
241
src_encoding
stringclasses
31 values
length_bytes
int64
14
3.6M
score
float64
2.52
5.13
int_score
int64
3
5
detected_licenses
listlengths
0
41
license_type
stringclasses
2 values
text
stringlengths
14
3.57M
download_success
bool
1 class
fa5f74c1c740e347cee70e40512ebd37082f2bb1
PHP
mawmaw15/SecProg
/NIM/controller/doLogin.php
UTF-8
1,248
2.59375
3
[]
no_license
<?php include "./../database/db.php"; if($_SERVER["REQUEST_METHOD"] == 'POST') { $username = $_POST['txtUsername']; $password = $_POST['txtPassword']; $hash_password = sha1($password); $sql = "SELECT * FROM users WHERE username = '$username' AND password = '$hash_password'"; $result = $conn->query($sql); session_start(); if($result->num_rows > 0) { // login success session_regenerate_id(); $_SESSION['username'] = $username; if(isset($_POST['chkRemember'])) { setcookie( "username", $username, time() + 3600 * 24 * 3, "/", null, false, true ); setcookie( "password", $password, time() + 3600 * 24 * 3, "/", null, false, true ); } header("location: ./../index.php"); } else { // login failed $_SESSION['error'] = "Wrong username or password"; header("location: ./../login.php"); } }
true
c815da4adfe2f62ddd17c47ef2f9b2d01efaca2e
PHP
shemarlaurent/helyos-backend
/app/Console/Commands/WeeklyDraw.php
UTF-8
1,642
2.96875
3
[]
no_license
<?php namespace App\Console\Commands; use App\AbyssForum; use Illuminate\Console\Command; class WeeklyDraw extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'raffle:draw'; /** * The console command description. * * @var string */ protected $description = 'Raffle draw to get the winner of a forum'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { // get all active forums $forums = (new AbyssForum)->getActiveForums(); foreach($forums as $forum) { // check if a forum has users registered to it if ($forum->hasUsers()) { // get all the users for the forum that are qualified for the draw $users = collect($forum->users)->filter(function ($user) { return $user->isQualifiedForDraw(); }); // get the winner for the draw $winner = $users->random(1)->first(); $forum->assignWinner($winner); } } return true; } // get all users that have qualified for the draw private function getQualifiedUsers($users) : array { return array_filter($users->toArray(), function($user) { return (bool) $user['address'] && $user['city'] && $user['country'] && $user['state'] && $user['zip_code']; }); } }
true
7ad677496001e96c3c9f74f34a3c2ce9be0045d2
PHP
alxrdk/php-mvc
/App/Model.php
UTF-8
335
2.609375
3
[]
no_license
<?php namespace App; use \App\Database; use \App\Config; class Model { protected static function db() : \App\Database { static $dbh = null; if ($dbh === null) { $dbh = new Database(Config::DB_HOST, Config::DB_USER, Config::DB_PASSWORD, Config::DB_NAME); } return $dbh; } }
true
c800f5e6e7a4225444a7d03a110103e64ae429de
PHP
devboard/thesting-data-source
/src/JsonReader.php
UTF-8
2,921
2.828125
3
[]
no_license
<?php declare(strict_types=1); namespace DevboardLib\Thesting\Source; use Symfony\Component\Finder\Finder; /** * @see JsonReaderSpec * @see JsonReaderTest */ class JsonReader { /** @var string */ private $basePath; public function __construct(string $basePath) { $this->basePath = $basePath; } public function loadRepoContent(string $repo): string { return file_get_contents($this->getBasePath().$repo.'/repo.json'); } public function loadBranchContent(string $repo, string $branchName): string { return file_get_contents($this->getBasePath().$repo.'/branches/'.$branchName.'.json'); } public function loadTagContent(string $repo, string $tagName): string { return file_get_contents($this->getBasePath().$repo.'/tags/'.$tagName.'.json'); } public function loadCommitContent(string $repo, string $commitSha): string { return file_get_contents($this->getBasePath().$repo.'/commits/'.$commitSha.'.json'); } public function loadCommitStatusContent(string $repo, string $commitSha): string { return file_get_contents($this->getBasePath().$repo.'/commit-statuses/'.$commitSha.'.json'); } public function loadPullRequestContent(string $repo, string $prNumber): string { return file_get_contents($this->getBasePath().$repo.'/pr/'.$prNumber.'.json'); } public function getBranchFiles(string $repo): array { return $this->getFilesIn($repo, 'branches'); } public function getTagFiles(string $repo): array { return $this->getFilesIn($repo, 'tags'); } public function getCommitFiles(string $repo): array { return $this->getFilesIn($repo, 'commits'); } public function getCommitStatusFiles(string $repo): array { return $this->getFilesIn($repo, 'commit-statuses'); } public function getPushEventFiles(string $repo): array { return $this->getFilesIn($repo, 'push'); } public function getPushEventBranchFiles(string $repo): array { return $this->getFilesIn($repo, 'push/branch'); } public function getPushEventTagFiles(string $repo): array { return $this->getFilesIn($repo, 'push/tag'); } public function getPullRequestFiles(string $repo): array { return $this->getFilesIn($repo, 'pr'); } private function getFilesIn(string $repo, string $folderName): array { $path = sprintf('%s/%s/%s/', $this->getBasePath(), $repo, $folderName); $finder = new Finder(); if (false === is_dir($path)) { return []; } $data = []; foreach ($finder->files()->in($path)->getIterator() as $item) { $data[] = $item; } return $data; } private function getBasePath(): string { return $this->basePath; } }
true
92aa9b1c70bc4270965ccae1d0feb55028f6f2fd
PHP
sergiocast97/cm3108
/rguevent/database/migrations/2019_10_12_192530_create_eventstaff_table.php
UTF-8
743
2.59375
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateEventstaffTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('eventstaff', function (Blueprint $table) { $table->integer('user_id'); $table->integer('event_id'); $table->string('user_role'); $table->timestamps(); $table->primary(array('user_id','event_id')); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('eventstaff'); } }
true
6ca6865dd1c988a5892acfb3e315edd46d6ca93c
PHP
ortizmas/www.psi.devs
/app/Http/Requests/Universities/UpdateUniversityRequest.php
UTF-8
1,099
2.6875
3
[]
no_license
<?php namespace App\Http\Requests\Universities; use Illuminate\Foundation\Http\FormRequest; class UpdateUniversityRequest extends FormRequest { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { return [ 'initials' => 'required|unique:universities,initials,' . $this->university->id, 'title' => 'required|unique:universities,title,' . $this->university->id, 'description' => 'required', ]; } public function messages() { return [ 'initials.required' => 'O campo sigla é obrigatorio', 'initials.unique' => 'A siglas já existe', 'title.required' => 'O titulo é obrigatorio', 'title.unique' => 'Esta universidade já existe', 'description.required' => 'A descrição é obrigatorio', ]; } }
true
d748fc6d3cdcbfed815acb09ebc55a568ad9084b
PHP
Felidaeblackblue/php_new
/users.php
UTF-8
965
3.390625
3
[]
no_license
<?php $users = [ ['Paul', 'bleu', 27], ['Camille', 'rouge', 38], ['Virgil', 'jaune', 42] ]; //var_dump($users); ?> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Utilisateurs</title> </head> <body> <table> <tr> <th>Nom</th> <th>Couleur</th> <th>Age</th> </tr> <tr> <td> <?php foreach ($users as $key=> $user) { echo "<p>$user[0]</p>"; } ?> </td> <td> <?php foreach ($users as $key=> $user) { echo "<p>$user[1]</p>"; } ?> </td> <td> <?php foreach ($users as $key=> $user) { echo "<p>$user[2]</p>"; } ?></td> </tr> </table> </body> </html>
true
93735583840509305500902b11db7ead994e9c45
PHP
renzcerico/bais-chaya
/class/Customer.php
UTF-8
29,996
2.921875
3
[]
no_license
<?php class Customer { public $conn; public function __construct($conn) { $this->conn = $conn; } public function counter($id) { $sql = 'SELECT count(ch.id) as total_child, count(cu.id) as total_custodian, count(h.id) as family_application FROM tbl_child ch LEFT JOIN tbl_custodian cu ON cu.child_id = ch.id LEFT JOIN tbl_household h ON h.parent_id = ch.parent_id WHERE ch.parent_id = :id'; $stmt = $this->conn->prepare($sql); $stmt->bindParam(':id', $id); $stmt->execute(); return $stmt->fetch(PDO::FETCH_ASSOC); } public function login($data) { $email_address = strtolower(htmlspecialchars($data['email_address'])); $password = md5(htmlspecialchars($data['password'])); $sql = "SELECT id, first_name, status FROM tbl_parents WHERE email_address = :email_address AND password = :password"; $stmt = $this->conn->prepare($sql); $stmt->bindParam(':email_address', $email_address); $stmt->bindParam(':password', $password); $stmt->execute(); $count = $stmt->rowCount(); if ($count > 0) { $row = $stmt->fetch(PDO::FETCH_ASSOC); extract($row); $result = []; $result = ['id' => $id, 'status' => $status, 'first_name' => $first_name]; return json_encode($result); } else { return false; } } public function email($email) { $email_address = strtolower(htmlspecialchars($email)); $sql = "SELECT * FROM tbl_parents WHERE email_address = :email_address"; $stmt = $this->conn->prepare($sql); $stmt->bindParam(':email_address', $email_address); $stmt->execute(); $count = $stmt->rowCount(); if ($count > 0) { return true; } else { return false; } } public function forgot($data) { $email_address = strtolower(htmlspecialchars($data['email'])); $sec_ques = strtolower(htmlspecialchars($data['sec_ques'])); $sec_ans = strtolower(htmlspecialchars($data['sec_ans'])); $sql = "SELECT * FROM tbl_parents WHERE email_address = :email_address AND security_question = :sec_ques AND security_answer = :sec_ans"; $stmt = $this->conn->prepare($sql); $stmt->bindParam(':email_address', $email_address); $stmt->bindParam(':sec_ques', $sec_ques); $stmt->bindParam(':sec_ans', $sec_ans); $stmt->execute(); $count = $stmt->rowCount(); if ($count > 0) { $random = $this->random_secret(); // mailForgot($email_address, $random); $this->resetPassword($email_address, $random); return true; } else { return false; } } public function mailForgot($email, $random) { $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; $headers .= "From: Bais Chaya Academy"; $to = $email; $subject = 'Password Reset'; $message = 'Your new password is ' . $random; mail($to, $subject, $html, $headers); } public function resetPassword($email, $code) { $email = $email; $code = md5($code); $sql = "UPDATE tbl_parents SET password = :code WHERE email_address = :email"; $stmt = $this->conn->prepare($sql); $stmt->bindParam(':email', $email); $stmt->bindParam(':code', $code); $stmt->execute(); } public function adminlogin($data) { $email_address = strtolower(htmlspecialchars($data['email_address'])); $password = md5(htmlspecialchars($data['password'])); $sql = "SELECT id, first_name, status FROM tbl_admin WHERE email_address = :email_address AND password = :password"; $stmt = $this->conn->prepare($sql); $stmt->bindParam(':email_address', $email_address); $stmt->bindParam(':password', $password); $stmt->execute(); $count = $stmt->rowCount(); if ($count > 0) { $row = $stmt->fetch(PDO::FETCH_ASSOC); extract($row); $result = []; $result = ['id' => $id, 'status' => $status, 'first_name' => $first_name]; return json_encode($result); } else { return false; } } public function getEmail($id) { $sql = 'SELECT email_address FROM tbl_parents WHERE id = :id'; $stmt = $this->conn->prepare($sql); $stmt->bindParam(':id', $id); $stmt->execute(); if ($stmt->rowCount() > 0) { $row = $stmt->fetch(PDO::FETCH_ASSOC); extract($row); return $email_address; } else { return false; } } public function resendVerification($id) { $email = $this->getEmail($id); if ($email) { $random = $this->random_secret(); $randomHash = md5($random); $sql = 'UPDATE tbl_parents SET secret = :secret WHERE id = :id'; $stmt = $this->conn->prepare($sql); $stmt->bindParam(':secret', $randomHash); $stmt->bindParam(':id', $id); $stmt->execute(); $this->mail($email, $random); return 200; } else { return false; } } public function random_secret() { $random = rand(1,100000); return $random; } // public function mail($email, $random) { // $from = 'Bais Chaya Academy'; // $to = $email; // $subject = 'Email Confirmation'; // $message = 'Please verify your email address. Verification code is ' . $random; // mail($subject, $from, $to, $message); // } public function mail($email, $random) { $headers = "MIME-Version: 1.0" . "\r\n"; $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; $headers .= "From: Bais Chaya Academy"; $to = $email; $subject = 'Email Confirmation'; $message = 'Please verify your email address. Verification code is ' . $random; mail($to, $subject, $html, $headers); } public function insert($data) { try { $secret = $this->random_secret(); $last_name = ucwords(htmlspecialchars($data['last_name'])); $first_name = ucwords(htmlspecialchars($data['first_name'])); $middle_name = ucwords(htmlspecialchars($data['middle_name'])) || ''; $email_address = strtolower(htmlspecialchars($data['email_address'])); $sec_ques = strtolower(htmlspecialchars($data['sec_ques'])); $sec_ans = strtolower(htmlspecialchars($data['sec_ans'])); $password = md5($data['password']); $secret = '12345'; $secret_md5 = md5($secret); $sql = "INSERT INTO tbl_parents SET last_name = :last_name, first_name = :first_name, middle_name = :middle_name, email_address = :email_address, password = :password, secret = :secret, security_question = :sec_ques, security_answer = :sec_ans, status = 'pending'"; $stmt = $this->conn->prepare($sql); $stmt->bindParam(':last_name', $last_name); $stmt->bindParam(':first_name', $first_name); $stmt->bindParam(':middle_name', $middle_name); $stmt->bindParam(':email_address', $email_address); $stmt->bindParam(':password', $password); $stmt->bindParam(':secret', $secret_md5); $stmt->bindParam(':sec_ques', $sec_ques); $stmt->bindParam(':sec_ans', $sec_ans); $stmt->execute(); $this->mail($email_address, $secret); return 200; } catch (PDOException $ex) { return $ex->getMessage(); } } public function secret($id) { $sql = "SELECT secret FROM tbl_parents WHERE id = :id"; $stmt = $this->conn->prepare($sql); $stmt->bindParam(':id', $id); $stmt->execute(); $count = $stmt->rowCount(); if ($count > 0) { $row = $stmt->fetch(PDO::FETCH_ASSOC); extract($row); return $secret; } else { return 422; } } public function verify($id, $code) { $id = $id; $code = md5($code); $secret = $this->secret($id); if ($secret == $code) { $sql = "UPDATE tbl_parents SET status = 'verified' WHERE id = :id"; $stmt = $this->conn->prepare($sql); $stmt->bindParam(':id', $id); $stmt->execute(); return 200; } else { return 422; } } public function insertFamilyApplication($data, $id) { try { // PART 1. All household members // $child_id = $data['to_array'][4]['child_id']; if (count($data['to_array'][0]) > 0) { $sqlMeal = "INSERT INTO tbl_meal SET parent_id = :id"; $stmtMeal = $this->conn->prepare($sqlMeal); $stmtMeal->bindParam(':id', $id); $stmtMeal->execute(); $mealID = $this->conn->lastInsertId(); foreach($data['to_array'][0] as $household) { $household_name = $household['name']; $household_student_id = $household['student_id']; $household_foster = $household['household_foster']; $household_homeless = $household['household_homeless']; $household_migrant = $household['household_migrant']; $household_runaway = $household['household_runaway']; $household_headstart = $household['household_headstart']; $household_no_income = $household['household_no_income']; $sql = "INSERT INTO tbl_household SET name = :household_name, student_id = :household_student_id, foster = :household_foster, homeless = :household_homeless, migrant = :household_migrant, runaway = :household_runaway, headstart = :household_headstart, no_income = :household_no_income, meal_id = :id "; $stmt = $this->conn->prepare($sql); $stmt->bindParam(':household_name', $household_name); $stmt->bindParam(':household_student_id', $household_student_id); $stmt->bindParam(':household_foster', $household_foster); $stmt->bindParam(':household_homeless', $household_homeless); $stmt->bindParam(':household_migrant', $household_migrant); $stmt->bindParam(':household_runaway', $household_runaway); $stmt->bindParam(':household_headstart', $household_headstart); $stmt->bindParam(':household_no_income', $household_no_income); $stmt->bindParam(':id', $mealID); // $stmt->bindParam(':child_id', $child_id); $stmt->execute(); } } // Part 2. Benefits $benefits_name = $data['to_array'][1][0]['benefits_name'] || ''; $benefits_program_name = $data['to_array'][1][0]['benefits_program_name'] || ''; $benefits_card_number = $data['to_array'][1][0]['benefits_card_number'] || ''; $sql_benefits = "INSERT INTO tbl_benefits SET name = :benefits_name, program_name = :benefits_program_name, card_number = :benefits_card_number, meal_id = :id "; $stmt_benefits = $this->conn->prepare($sql_benefits); $stmt_benefits->bindParam(':benefits_name', $benefits_name); $stmt_benefits->bindParam(':benefits_program_name', $benefits_program_name); $stmt_benefits->bindParam(':benefits_card_number', $benefits_card_number); $stmt_benefits->bindParam(':id', $mealID); // $stmt_benefits->bindParam(':child_id', $child_id); if ($benefits_name) { $stmt_benefits->execute(); } // Part 3. Total Income foreach($data['to_array'][2] as $total_income) { $total_name = $total_income['total_name']; $total_deductions = $total_income['total_deductions']; $total_deductions_weekly = $total_income['total_deductions_weekly']; $total_deductions_2_weeks = $total_income['total_deductions_2_weeks']; $total_deductions_twice_monthly = $total_income['total_deductions_twice_monthly']; $total_deductions_monthly = $total_income['total_deductions_monthly']; $total_walfare = $total_income['total_walfare'] || ''; $total_walfare_weekly = $total_income['total_walfare_weekly']; $total_walfare_2_weeks = $total_income['total_walfare_2_weeks']; $total_walfare_twice_monthly = $total_income['total_walfare_twice_monthly']; $total_walfare_monthly = $total_income['total_walfare_monthly']; $total_social = $total_income['total_social'] || ''; $total_social_weekly = $total_income['total_social_weekly']; $total_social_2_weeks = $total_income['total_social_2_weeks']; $total_social_twice_monthly = $total_income['total_social_twice_monthly']; $total_social_monthly = $total_income['total_social_monthly']; $total_other = $total_income['total_other'] || ''; $total_other_weekly = $total_income['total_other_weekly']; $total_other_2_weeks = $total_income['total_other_2_weeks']; $total_other_twice_monthly = $total_income['total_other_twice_monthly']; $total_other_monthly = $total_income['total_other_monthly']; $sql_total_income = "INSERT INTO tbl_total_income SET name = :total_name, earnings = :total_deductions, weekly_earnings = :total_deductions_weekly, two_weeks_earnings = :total_deductions_2_weeks, twice_monthly_earnings = :total_deductions_twice_monthly, monthly_earnings = :total_deductions_monthly, welfare = :total_walfare, weekly_welfare = :total_walfare_weekly, two_weeks_welfare = :total_walfare_2_weeks, twice_monthly_welfare = :total_walfare_twice_monthly, monthly_welfare = :total_walfare_monthly, sss = :total_social, weekly_sss = :total_social_weekly, two_weeks_sss = :total_social_2_weeks, twice_monthly_sss = :total_social_twice_monthly, monthly_sss = :total_social_monthly, other = :total_other, weekly_other = :total_other_weekly, two_weeks_other = :total_other_2_weeks, twice_monthly_other = :total_other_twice_monthly, monthly_other = :total_other_monthly, meal_id = :id "; $stmt_total_income = $this->conn->prepare($sql_total_income); $stmt_total_income->bindParam(':total_name', $total_name); $stmt_total_income->bindParam(':total_deductions', $total_deductions); $stmt_total_income->bindParam(':total_deductions_weekly', $total_deductions_weekly); $stmt_total_income->bindParam(':total_deductions_2_weeks', $total_deductions_2_weeks); $stmt_total_income->bindParam(':total_deductions_twice_monthly', $total_deductions_twice_monthly); $stmt_total_income->bindParam(':total_deductions_monthly', $total_deductions_monthly); $stmt_total_income->bindParam(':total_walfare', $total_walfare); $stmt_total_income->bindParam(':total_walfare_weekly', $total_walfare_weekly); $stmt_total_income->bindParam(':total_walfare_2_weeks', $total_walfare_2_weeks); $stmt_total_income->bindParam(':total_walfare_twice_monthly', $total_walfare_twice_monthly); $stmt_total_income->bindParam(':total_walfare_monthly', $total_walfare_monthly); $stmt_total_income->bindParam(':total_social', $total_social); $stmt_total_income->bindParam(':total_social_weekly', $total_social_weekly); $stmt_total_income->bindParam(':total_social_2_weeks', $total_social_2_weeks); $stmt_total_income->bindParam(':total_social_twice_monthly', $total_social_twice_monthly); $stmt_total_income->bindParam(':total_social_monthly', $total_social_monthly); $stmt_total_income->bindParam(':total_other', $total_other); $stmt_total_income->bindParam(':total_other_weekly', $total_other_weekly); $stmt_total_income->bindParam(':total_other_2_weeks', $total_other_2_weeks); $stmt_total_income->bindParam(':total_other_twice_monthly', $total_other_twice_monthly); $stmt_total_income->bindParam(':total_other_monthly', $total_other_monthly); $stmt_total_income->bindParam(':id', $mealID); // $stmt_total_income->bindParam(':child_id', $child_id); $stmt_total_income->execute(); } // Part 4. Adult Signature $adult_signature = $data['to_array'][3][0]['adult_signature'] || ''; $adult_name = $data['to_array'][3][0]['adult_name']; $adult_date = $data['to_array'][3][0]['adult_date']; $adult_address = $data['to_array'][3][0]['adult_address']; $adult_phone_number = $data['to_array'][3][0]['adult_phone_number']; $adult_email = $data['to_array'][3][0]['adult_email']; $adult_city = $data['to_array'][3][0]['adult_city']; $adult_state = $data['to_array'][3][0]['adult_state']; $adult_zip = $data['to_array'][3][0]['adult_zip']; $adult_social_security = $data['to_array'][3][0]['adult_social_security']; $adult_no_social_security = $data['to_array'][3][0]['adult_no_social_security']; $share_information = $data['to_array'][3][0]['share_information']; $ethnicity = $data['to_array'][3][0]['ethnicity']; $ethnicity_asian = $data['to_array'][3][0]['ethnicity_asian']; $ethnicity_indian = $data['to_array'][3][0]['ethnicity_indian']; $ethnicity_african = $data['to_array'][3][0]['ethnicity_african']; $ethnicity_white = $data['to_array'][3][0]['ethnicity_white']; $ethnicity_hawaiian = $data['to_array'][3][0]['ethnicity_hawaiian']; $sql_adult_signature = "INSERT INTO tbl_adult_signature SET signature = :adult_signature, name = :adult_name, date_applicant = :adult_date, address = :adult_address, phone_number = :adult_phone_number, email_address = :adult_email, city = :adult_city, state = :adult_state, zip_code = :adult_zip, sss = :adult_social_security, sss_none = :adult_no_social_security, share_info = :share_information, ethnicity = :ethnicity, ethnicity_asian = :ethnicity_asian, ethnicity_white = :ethnicity_indian, ethnicity_american = :ethnicity_african, ethnicity_native = :ethnicity_white, ethnicity_black = :ethnicity_hawaiian, meal_id = :id "; $stmt_adult_signature = $this->conn->prepare($sql_adult_signature); $stmt_adult_signature->bindParam(':adult_signature', $adult_signature); $stmt_adult_signature->bindParam(':adult_name', $adult_name); $stmt_adult_signature->bindParam(':adult_date', $adult_date); $stmt_adult_signature->bindParam(':adult_address', $adult_address); $stmt_adult_signature->bindParam(':adult_phone_number', $adult_phone_number); $stmt_adult_signature->bindParam(':adult_email', $adult_email); $stmt_adult_signature->bindParam(':adult_city', $adult_city); $stmt_adult_signature->bindParam(':adult_state', $adult_state); $stmt_adult_signature->bindParam(':adult_zip', $adult_zip); $stmt_adult_signature->bindParam(':adult_social_security', $adult_social_security); $stmt_adult_signature->bindParam(':adult_no_social_security', $adult_no_social_security); $stmt_adult_signature->bindParam(':share_information', $share_information); $stmt_adult_signature->bindParam(':ethnicity', $ethnicity); $stmt_adult_signature->bindParam(':ethnicity_asian', $ethnicity_asian); $stmt_adult_signature->bindParam(':ethnicity_indian', $ethnicity_indian); $stmt_adult_signature->bindParam(':ethnicity_african', $ethnicity_african); $stmt_adult_signature->bindParam(':ethnicity_white', $ethnicity_white); $stmt_adult_signature->bindParam(':ethnicity_hawaiian', $ethnicity_hawaiian); $stmt_adult_signature->bindParam(':id', $mealID); // $stmt_adult_signature->bindParam(':child_id', $child_id); if ($adult_name) { $stmt_adult_signature->execute(); } return 200; } catch(PDOException $ex) { return $ex->getMessage(); die(); } } public function getAllParents() { $sql = "SELECT id, CONCAT(last_name, ', ', first_name, ' ', LEFT(middle_name, 1)) as parent_name, email_address, status, created_at FROM tbl_parents "; $stmt = $this->conn->prepare($sql); $stmt->execute(); return $stmt; } public function getAllParentsArchives($year) { if ($year == 'ALL'){ $sql = "SELECT p.id, CONCAT(p.last_name, ', ', p.first_name, ' ', LEFT(p.middle_name, 1)) as parent_name, p.email_address, p.status, m.id as meal_id, ma.year, p.created_at FROM tbl_parents p LEFT JOIN tbl_meal m ON m.parent_id = p.id RIGHT JOIN tbl_meal_archives ma ON ma.meal_id = m.id ORDER BY ma.year DESC "; } else{ $sql = "SELECT p.id, CONCAT(p.last_name, ', ', p.first_name, ' ', LEFT(p.middle_name, 1)) as parent_name, p.email_address, p.status, m.id as meal_id, ma.year, p.created_at FROM tbl_parents p LEFT JOIN tbl_meal m ON m.parent_id = p.id RIGHT JOIN tbl_meal_archives ma ON ma.meal_id = m.id WHERE ma.year = :year ORDER BY ma.year DESC "; } $stmt = $this->conn->prepare($sql); $stmt->bindParam(':year', $year); $stmt->execute(); return $stmt; } public function getFamilyApplication($id) { $sql = "SELECT parents.id, CONCAT(parents.last_name, ', ', parents.first_name, ' ', LEFT(parents.middle_name, 1)) as parent_name, parents.email_address, GROUP_CONCAT()adult.*, benefits.*, household.*, income.* FROM tbl_parents parents LEFT JOIN tbl_meal meal ON meal.parent_id = parents.id LEFT JOIN tbl_adult_signature adult ON adult.meal_id = meal.id LEFT JOIN tbl_benefits benefits ON benefits.meal_id = meal.id LEFT JOIN tbl_household household ON household.meal_id = meal.id LEFT JOIN tbl_total_income income ON income.meal_id = meal.id"; $stmt = $this->conn->prepare($sql); $stmtParents->bindParam(':id', $id); $stmt->execute(); return $stmt; } public function familyApplication($id) { // $sql = "SELECT // parents.id, // CONCAT(parents.last_name, ', ', parents.first_name, ' ', LEFT(parents.middle_name, 1)) as parent_name, // parents.email_address, // adult.*, // benefits.*, // household.*, // income.* // FROM tbl_parents parents // LEFT JOIN tbl_adult_signature adult ON adult.parent_id = parents.id // LEFT JOIN tbl_benefits benefits ON benefits.parent_id = parents.id // LEFT JOIN tbl_household household ON household.parent_id = parents.id // LEFT JOIN tbl_total_income income ON income.parent_id = parents.id // WHERE parents.id = :id"; // $sqlParents = "SELECT parents.id, // CONCAT(parents.last_name, ', ', parents.first_name, ' ', LEFT(parents.middle_name, 1)) as parent_name, // parents.email_address // FROM tbl_parents parents"; // $stmtParents = $this->conn->prepare($sqlParents); // $stmtParents->bindParam(':id', $id); // $stmtParents->execute(); // $stmtParents = $stmtParents->fetchAll(PDO::FETCH_ASSOC); $sqlMeal = "SELECT id FROM tbl_meal WHERE parent_id = :id LIMIT 1"; $stmtMeal = $this->conn->prepare($sqlMeal); $stmtMeal->bindParam(':id', $id); $stmtMeal->execute(); $row = $stmtMeal->fetch(PDO::FETCH_ASSOC); $mealID = $row['id']; $sqlAdult = "SELECT * FROM tbl_adult_signature WHERE meal_id = :id"; $stmtAdult = $this->conn->prepare($sqlAdult); $stmtAdult->bindParam(':id', $mealID); $stmtAdult->execute(); $stmtAdult = $stmtAdult->fetch(PDO::FETCH_ASSOC); $sqlBenefits = "SELECT * FROM tbl_benefits WHERE meal_id = :id"; $stmtBenefits = $this->conn->prepare($sqlBenefits); $stmtBenefits->bindParam(':id', $mealID); $stmtBenefits->execute(); $stmtBenefits = $stmtBenefits->fetchAll(PDO::FETCH_ASSOC); $sqlHousehold = "SELECT * FROM tbl_household WHERE meal_id = :id"; $stmtHousehold = $this->conn->prepare($sqlHousehold); $stmtHousehold->bindParam(':id', $mealID); $stmtHousehold->execute(); $stmtHousehold = $stmtHousehold->fetchAll(PDO::FETCH_ASSOC); $sqlIncome = "SELECT * FROM tbl_total_income WHERE meal_id = :id"; $stmtIncome = $this->conn->prepare($sqlIncome); $stmtIncome->bindParam(':id', $mealID); $stmtIncome->execute(); $stmtIncome = $stmtIncome->fetchAll(PDO::FETCH_ASSOC); $array = [ // 'parents' => ($stmtParents), 'adult' => ($stmtAdult), 'benefits' => ($stmtBenefits), 'household' => ($stmtHousehold), 'income' => ($stmtIncome), ]; return $array; } public function familyApplicationArchives($id) { // $sql = "SELECT // parents.id, // CONCAT(parents.last_name, ', ', parents.first_name, ' ', LEFT(parents.middle_name, 1)) as parent_name, // parents.email_address, // adult.*, // benefits.*, // household.*, // income.* // FROM tbl_parents parents // LEFT JOIN tbl_adult_signature adult ON adult.parent_id = parents.id // LEFT JOIN tbl_benefits benefits ON benefits.parent_id = parents.id // LEFT JOIN tbl_household household ON household.parent_id = parents.id // LEFT JOIN tbl_total_income income ON income.parent_id = parents.id // WHERE parents.id = :id"; // $sqlParents = "SELECT parents.id, // CONCAT(parents.last_name, ', ', parents.first_name, ' ', LEFT(parents.middle_name, 1)) as parent_name, // parents.email_address // FROM tbl_parents parents"; // $stmtParents = $this->conn->prepare($sqlParents); // $stmtParents->bindParam(':id', $id); // $stmtParents->execute(); // $stmtParents = $stmtParents->fetchAll(PDO::FETCH_ASSOC); // $sqlMeal = "SELECT id FROM tbl_meal WHERE parent_id = :id LIMIT 1"; // $stmtMeal = $this->conn->prepare($sqlMeal); // $stmtMeal->bindParam(':id', $id); // $stmtMeal->execute(); // $row = $stmtMeal->fetch(PDO::FETCH_ASSOC); // $mealID = $row['id']; $mealID = $id; $sqlAdult = "SELECT * FROM tbl_adult_signature WHERE meal_id = :id"; $stmtAdult = $this->conn->prepare($sqlAdult); $stmtAdult->bindParam(':id', $mealID); $stmtAdult->execute(); $stmtAdult = $stmtAdult->fetch(PDO::FETCH_ASSOC); $sqlBenefits = "SELECT * FROM tbl_benefits WHERE meal_id = :id"; $stmtBenefits = $this->conn->prepare($sqlBenefits); $stmtBenefits->bindParam(':id', $mealID); $stmtBenefits->execute(); $stmtBenefits = $stmtBenefits->fetchAll(PDO::FETCH_ASSOC); $sqlHousehold = "SELECT * FROM tbl_household WHERE meal_id = :id"; $stmtHousehold = $this->conn->prepare($sqlHousehold); $stmtHousehold->bindParam(':id', $mealID); $stmtHousehold->execute(); $stmtHousehold = $stmtHousehold->fetchAll(PDO::FETCH_ASSOC); $sqlIncome = "SELECT * FROM tbl_total_income WHERE meal_id = :id"; $stmtIncome = $this->conn->prepare($sqlIncome); $stmtIncome->bindParam(':id', $mealID); $stmtIncome->execute(); $stmtIncome = $stmtIncome->fetchAll(PDO::FETCH_ASSOC); $array = [ // 'parents' => ($stmtParents), 'adult' => ($stmtAdult), 'benefits' => ($stmtBenefits), 'household' => ($stmtHousehold), 'income' => ($stmtIncome), ]; return $array; } public function getAllChild() { $sql = "SELECT c.id, p.id parent_id, CONCAT(c.last_name, ', ', c.first_name, ' ', LEFT(c.middle_name, 1), '.') as child_name, CONCAT(p.last_name, ', ', p.first_name, ' ', LEFT(p.middle_name, 1), '.') as parent_name, c.created_at FROM tbl_child c LEFT JOIN tbl_parents p ON p.id = c.parent_id WHERE c.id NOT IN (SELECT child_id FROM tbl_child_archives) "; $stmt = $this->conn->prepare($sql); $stmt->execute(); return $stmt; } public function getAllChildArchives($year) { if ($year == 'ALL'){ $sql = "SELECT c.id, p.id parent_id, CONCAT(c.last_name, ', ', c.first_name, ' ', LEFT(c.middle_name, 1), '.') as child_name, CONCAT(p.last_name, ', ', p.first_name, ' ', LEFT(p.middle_name, 1), '.') as parent_name, ca.year, c.created_at FROM tbl_child c LEFT JOIN tbl_parents p ON p.id = c.parent_id RIGHT JOIN tbl_child_archives ca ON ca.child_id = c.id ORDER BY ca.year DESC "; } else{ $sql = "SELECT c.id, p.id parent_id, CONCAT(c.last_name, ', ', c.first_name, ' ', LEFT(c.middle_name, 1), '.') as child_name, CONCAT(p.last_name, ', ', p.first_name, ' ', LEFT(p.middle_name, 1), '.') as parent_name, ca.year, c.created_at FROM tbl_child c LEFT JOIN tbl_parents p ON p.id = c.parent_id RIGHT JOIN tbl_child_archives ca ON ca.child_id = c.id WHERE ca.year = :year ORDER BY ca.year DESC "; } $stmt = $this->conn->prepare($sql); $stmt->bindParam(':year', $year); $stmt->execute(); return $stmt; } public function getMyProfile($id, $userLevel) { if ($userLevel === 'admin') { $sql = 'SELECT last_name, first_name, middle_name, email_address FROM tbl_admin WHERE id = :id'; } else { $sql = 'SELECT last_name, first_name, middle_name, email_address FROM tbl_parents WHERE id = :id'; } $stmt = $this->conn->prepare($sql); $stmt->bindParam(':id', $id); $stmt->execute(); return $stmt; } public function updateMyProfile($data) { if ($data['userLevel'] === 'admin') { $sql = 'UPDATE tbl_admin SET last_name = :last_name, first_name = :first_name, middle_name = :middle_name, email_address = :email_address WHERE id = :id'; } else { $sql = 'UPDATE tbl_parents SET last_name = :last_name, first_name = :first_name, middle_name = :middle_name, email_address = :email_address WHERE id = :id'; } $stmt = $this->conn->prepare($sql); $stmt->bindParam(':id', $data['id']); $stmt->bindParam(':last_name', $data['lastname']); $stmt->bindParam(':first_name', $data['firstname']); $stmt->bindParam(':middle_name', $data['middlename']); $stmt->bindParam(':email_address', $data['email']); $stmt->execute(); return 200; } public function changePassword($data) { $password = md5(htmlspecialchars($data['password'])); if ($data['userLevel'] === 'admin') { $sql = 'UPDATE tbl_admin SET password = :password WHERE id = :id'; } else { $sql = 'UPDATE tbl_parents SET password = :password WHERE id = :id'; } $stmt = $this->conn->prepare($sql); $stmt->bindParam(':id', $data['id']); $stmt->bindParam(':password', $password); $stmt->execute(); return 200; } public function isCheck($data) { $password = md5($data['password']); if ($data['userLevel'] === 'admin') { $sql = 'SELECT * FROM tbl_admin WHERE id = :id AND password = :password'; } else { $sql = 'SELECT * FROM tbl_parents WHERE id = :id AND password = :password'; } $stmt = $this->conn->prepare($sql); $stmt->bindParam(':id', $data['id']); $stmt->bindParam(':password', $password); $stmt->execute(); if ($stmt->rowCount() > 0) { return 200; } else { return 401; } } } ?>
true
e41b7764f8cc0db9a3e6e19b37a45c7ccfb03d32
PHP
linepogl/oxygen
/src/TypeSystem/MetaTypes/InternalTypes/Arrays/MetaIDArrayOrNull.php
UTF-8
441
2.609375
3
[ "MIT" ]
permissive
<?php class MetaIDArrayOrNull extends XNullableArrayType { private static $instance; public static function Init(){ self::$instance = new self(); } /** @return MetaIDArrayOrNull */ public static function Type(){ return self::$instance; } protected static function Encode($array){ return MetaIDArray::Encode($array); } protected static function Decode($string){ return MetaIDArray::Decode($string); } } MetaIDArrayOrNull::Init();
true
798db70b5ab7fb31d315c73d37a8761e31650a21
PHP
slavokozar/CodeTutor
/app/Models/Assignments/Solution.php
UTF-8
1,166
2.59375
3
[ "MIT" ]
permissive
<?php namespace App\Models\Assignments; use App\Models\Users\User; use Illuminate\Database\Eloquent\Model; class Solution extends Model { protected $table = 'assignment_solutions'; protected $fillable = [ 'assignment_id', 'code', 'user_id', 'lang_id', 'filename', 'review', 'review_points' ]; public function user(){ return $this->belongsTo(User::class, 'user_id'); } public function score(){ } public function icon(){ if($this->filename != "" && pathinfo($this->filename)['extension'] == 'zip'){ return '<i class="fa fa-file-archive-o"></i>'; }else{ return '<i class="fa fa-file-o"></i>'; } } public function assignment(){ return $this->belongsTo(Assignment::class, 'assignment_id'); } public function scores(){ return $this->hasMany(Score::class, 'solution_id'); } public function reviews(){ return $this->hasMany(Review::class, 'solution_id'); } public function files(){ return $this->hasMany(SolutionFile::class, 'solution_id'); } }
true
7ee4c10e5bc252b3d6e0b2062bab03d34d696180
PHP
bersanots/FEUP-LBAW
/app/Media.php
UTF-8
440
2.515625
3
[]
no_license
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Media extends Model { // Don't add create and update timestamps in database. public $timestamps = false; protected $primaryKey = 'media_id'; protected $table = 'media'; /** * The users that have this media as their favourite */ public function favourite() { return $this->belongsToMany('App\User', 'favourite', 'media_id', 'user_id'); } }
true
ebc75db31e84a5e25958357a57bf8504e82814ab
PHP
cuthbert/izzum-statemachine
/src/statemachine/persistence/Tooling.php
UTF-8
3,877
2.875
3
[ "MIT" ]
permissive
<?php namespace izzum\statemachine\persistence; /** * this Tooling interface can be implemented by creating a subclass of Adapter or by * creating a subclass from one of the existing Adapter subclasses. * * The Adapter subclass (a data access object) will then allow you to gather * data related to the statemachine so you can build and use tooling to manipulate * your statemachine. * * Your application specific Adapter subclass can ofcourse implement a lot more methods * more tailored to your information/manipulation needs. * * @author Rolf Vreijdenberger * */ Interface Tooling { /** * returns machine information for machines. * * This method allows you to get the factory name(s) for machines which in turn * allows you to polymorphically build all associated objects for your application. * This is very powerful since it lets you build tooling that acts generically on * all statemachines in your application. * * @param string $machine optional the machine to get the info for * @return array an array containing machine names and fully qualifed factory classes and description */ public function getMachineInformation($machine = null); /** * returns state information for machines. * * This method allows you to get all state information. This allows you to build * tooling where you can access all exit and entry logic and execute that (commands) * on an domain object (which you can build via a factory and a custom entity builder). * * This is highly useful if you have failed transitions (eg: because a 3d party service * was temporarily down) and only want to execute a specific piece of logic independently. * Just instantiate the command associated with the state logic with the domain object * injected in the constructor. * * @param string $machine optional the machine to get the info for * @return array an array containing state names, exit and entry logic, machine name etc) */ public function getStateInformation($machine = null); /** * returns transition information for machines. * * This method allows you to get all transition information. This allows you to build * tooling where you can access all guard and transition logic and check that (via a rule) * or execute that (via commands) on an domain object (which you can build via a factory and a custom entity builder). * * This is highly useful if you have failed transitions (eg: because a 3d party service * was temporarily down) and only want to execute a specific piece of logic independently. * Just instantiate the rule or command associated with the state logic with the domain object * injected in the constructor. You can then check if a domain object/statemachine is allowed * to transition (via the rule, with optional output from the rule via Rule::addResult) or execute a command * associated with that transition. * * @param string $machine optional the machine to get the info for * @return array an array containing transition info (guards, logic, source and sink states, event names etc) */ public function getTransitionInformation($machine = null); /** * returns transition history information. * * Useful to build textual or visual (plantuml) output related to transitions * for a specific machine or entity in a machine. * * @param string $machine optional the machine to get the info for * @param $entity_id optional the entity id to get the history info for * @return array an array containing transition history info (machine, entity_id, timestamp, message etc) */ public function getTransitionHistoryInformation($machine = null, $entity_id = null); }
true
5093772d73de0bb40a8659f8782d314681d647fc
PHP
fernandoobarbosa/TestePhp
/cadastrar_cidade.php
UTF-8
395
2.6875
3
[]
no_license
<?php require_once('classes/cidade.php') ?> <form method="post"> Nome : <input type="text" name="Cidade" required></br></br> <input type="submit" name="submit" value="Cadastrar"></br> <?php if (isset($_POST['submit'])) { $function = new Cidade(); $cidade = $_POST['Cidade']; $function->insereCidade($cidade); } ?> </form>
true
949a8e4cecf645b5339b5942f0643c3bb017fecc
PHP
FIT-Cool/pw2-assignment01-20191-avinash322
/function/pasien_function.php
UTF-8
1,551
2.609375
3
[]
no_license
<?php function getPasien(){ $link = new PDO("mysql:host=localhost;dbname=prakpw220191", "root", ""); $link->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE); $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $query = "SELECT p.med_record_number,p.citizen_id_number,p.name,p.address,p.birth_place,p.phone_number,p.photo,p.birth_date,i.id,i.name_class FROM patient p JOIN insurance i ON p.insurance_id = i.id"; $result = $link->query($query); return $result; } function addPasien($nomor, $id, $nama, $alamat, $kota, $tanggal, $jenis){ $link = new PDO("mysql:host=localhost;dbname=prakpw220191", "root", ""); $link->setAttribute(PDO::ATTR_AUTOCOMMIT, FALSE); $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $link->beginTransaction(); $query = "INSERT INTO patient (med_record_number,citizen_id_number,name,address,birth_place,birth_date,insurance_id) VALUES (?,?,?,?,?,?,?)"; $statement = $link->prepare($query);; $statement->bindParam(1, $nomor, PDO::PARAM_STR); $statement->bindParam(2, $id, PDO::PARAM_INT); $statement->bindParam(3, $nama, PDO::PARAM_STR); $statement->bindParam(4, $alamat, PDO::PARAM_STR); $statement->bindParam(5, $kota, PDO::PARAM_STR); $statement->bindParam(6, $tanggal, PDO::PARAM_STR); $statement->bindParam(7, $jenis, PDO::PARAM_INT); if ($statement->execute()) { $link->commit(); } else { $link->rollBack(); } $link = null; header("location:index.php?menu=pasien"); } ?>
true
032a76d6d33a902aa26d3dac7a5d2b98fa39ab78
PHP
odhier/eraport-prod
/database/migrations/2020_12_27_100715_create_kkm_table.php
UTF-8
1,000
2.515625
3
[]
no_license
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateKkmTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('kkm', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('course_id')->unsigned(); $table->string('tingkat_kelas'); $table->unsignedBigInteger('tahun_ajaran_id')->unsigned(); $table->float('value', 8, 3)->nullable(); $table->integer('ki'); $table->timestamps(); $table->foreign('course_id')->references('id')->on('courses'); $table->foreign('tahun_ajaran_id')->references('id')->on('tahun_ajaran'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('kkm'); } }
true
3fde8572edfb2d15a95fc608202ab427fe286498
PHP
fendy3002/QzPhp
/src/QzPhp/Logs/StringLog.php
UTF-8
378
3.03125
3
[ "MIT" ]
permissive
<?php namespace QzPhp\Logs; class StringLog implements ILog { public $data = ''; public function message($message){ $this->data .= $this->data . $message; } public function messageln($message = NULL){ $this->data .= $this->data . $message. "\n"; } public function object ($object){ $this->data .= print_r($object, true); } }
true
43b19120974ac1b34e0f5cc594c7990031c33df9
PHP
br-g/CLP-Website
/admin/model/GalleryImage.php
UTF-8
1,647
2.671875
3
[]
no_license
<?php class GalleryImage extends Elem { var $galleryId; var $upload; function __construct() { parent::__construct(); $this->galleryId = -1; $this->upload = null; } function loadFromDB($tuple) { parent::loadFromDB($tuple); $this->galleryId = $tuple['galleryId']; $this->upload = new Upload(); $this->upload->loadFromDB($tuple['uploadId']); } function createFromForm($galleryId, $uploadId, $rank) { $this->galleryId = $galleryId; $this->upload = new Upload(); $this->upload->loadFromDB($uploadId); $this->rank = $rank; } function toSectionForm() { $content = file_get_contents('../view/asset/curGalery_image.html'); $content = str_replace('<RANKMARKER>', 'curGalleryIm_rankMarker' . rand(1, 1e9), $content); $content = str_replace('<IMAGENAME>', $this->upload->initialName, $content); $content = str_replace('<UPLOADID>', $this->upload->id, $content); return $content; } function toSQL() { $q = ""; if ($this->upload != null) $q .= $this->upload->toSQL(); $q .= "INSERT INTO adm_galleryimage(id, galleryId, uploadId, rank)" . "VALUES('" . $this->id . "', '" . $this->galleryId . "', '" . $this->upload->id . "', '" . $this->rank . "'); "; return $q; } function toWebsite() { $content = file_get_contents('../../assets/html_chuncks/galleryImage.html'); $content = str_replace('<SRC>', $this->upload->path, $content); return $content; } function delete($removeUploads) { if ($removeUploads) { $this->upload->delete(); } $q = "DELETE FROM adm_galleryimage WHERE id = '" . $this->id . "'; "; executeQuery($q); } } ?>
true
09ddd828a2cf9e19e215381bac40c120fc8677fd
PHP
icchiy/survey
/check.php
UTF-8
2,517
2.71875
3
[]
no_license
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>PHP基礎</title> </head> <body> <?php $dsn='mysql:dbname=phpkiso;host=localhost'; $user='root'; $password=''; $dbh=new PDO($dsn,$user,$password); $dbh->query('SET NAMES utf8'); $nickname=$_POST['nickname']; $email=$_POST['email']; $goiken=$_POST['goiken']; $nickname=htmlspecialchars($nickname); $email=htmlspecialchars($email); $goiken=htmlspecialchars($goiken); if($nickname==''){ echo'<span style="color:red;">'; echo'ニックネームが入力されていません。<br>'; echo '</span>'; echo'<br>'; } else{ echo 'ようこそ'; echo $nickname; echo'様'; echo '』<br>'; } if($email==''){ echo '<span style="color:red;">'; echo'メールアドレスが入力されていません。<br>'; echo '</span>'; echo'<br>'; } else{ echo 'メールアドレス:'; echo $email; echo '<br>'; } if($goiken==''){ echo '<span style="color:red;">'; echo'ご意見が入力されていません。<br>'; echo '</span>'; echo'<br>'; } else{ echo 'ご意見『'; echo $goiken; echo '』<br>'; echo '<br>'; } // echo '<a href="index.html">戻る</a>';これを試用すると『戻る』ボタンを押すと入力したデータも消える。 if($nickname==''||$email==''||$goilen='') { echo'<form>'; echo'<input type="button" onclick="history.back()" value="戻る">'; echo'</form>'; } else { echo'<form method="post" action="thanks.php">'; echo'<input name="nickname" type="hidden" value="'.$nickname.'">'; echo'<input name="email" type="hidden" value="'.$email.'">'; echo'<input name="goiken" type="hidden" value="'.$goiken.'">'; echo'<input type="button" onclick="history.back()" value="戻る">'; echo'<input type="submit" value="OK">'; echo'</form>'; } $sql='INSERT INTO anketo2(nickname,email,goiken)VALUES("'.$nickname.'","'.$email.'","'.$goiken.'")'; $stmt=$dbh->prepare($sql); $stmt->execute(); $dbh=null; ?> </body> </html>
true
c1f228db345c5651ddcd5ccbb93043fc597b9044
PHP
webmania2014/mvhdev
/application/modules/acceptance/models/acceptance_model.php
UTF-8
6,961
2.515625
3
[]
no_license
<?php if( !defined( 'BASEPATH' ) ) exit( 'No direct script access allowed' ); class Acceptance_model extends CI_Model{ function get_workers() { $workers = array(); $query = $this->db->query('SELECT id, first_name, last_name FROM ltno_workers'); foreach ($query->result() as $row) { $workers[$row->id] = $row->first_name . ' ' . $row->last_name; } return $workers; } function get_work_types() { $work_type = array(); $query = $this->db->query('SELECT * FROM ltno_work_types'); foreach ($query->result() as $row) { $work_type[$row->id] = $row->title; } return $work_type; } function get_time_sheet($worker_id, $start_date, $end_date) { $work_type_list = $this->get_work_types(); $work_type_options = ''; foreach ($work_type_list as $id => $title) { $work_type_options .= ' <option value="' . $id . '">' . $title . '</option> '; } $sql = 'SELECT * FROM ltno_works_hours'; $sql .= ' WHERE 1'; $sql .= ' AND worker_id=\'' . $worker_id . '\''; $sql .= ' AND work_date >= \'' . $start_date . '\''; $sql .= ' AND work_date <= \'' . $end_date . '\''; $sql .= ' ORDER BY work_date ASC'; $query = $this->db->query($sql); $result = array(); foreach ($query->result() as $row) { $unit_array = array(); $unit_array['work_date'] = $row->work_date; $work_query = $this->db->query('SELECT * FROM ltno_works WHERE id=\'' . $row->work_id . '\''); $work_info_from_db = $work_query->row(); $unit_array['id'] = $row->id; $query = $this->db->query('SELECT client_name FROM ltno_clients WHERE id=\'' . $work_info_from_db->client_id . '\''); $unit_array['client_name'] = $query->row()->client_name; $query = $this->db->query('SELECT name FROM ltno_house WHERE id=\'' . $work_info_from_db->house_id . '\''); $house_name = isset($query->row()->name) ? $query->row()->name : ''; $query = $this->db->query('SELECT name FROM ltno_house WHERE id=\'' . $work_info_from_db->room_id . '\''); $room_name = isset($query->row()->name) ? $query->row()->name : ''; $unit_array['area'] = $house_name . ' ' . $room_name; $unit_array['work_number'] = $work_info_from_db->work_number; $work_type_query = $this->db->query('SELECT title FROM ltno_work_types WHERE id=\'' . $work_info_from_db->work_type_id . '\''); $unit_array['work_type'] = $work_type_query->row()->title; $unit_array['work_norm'] = $row->work_norm; $unit_array['work_50'] = $row->work_50; $unit_array['work_100'] = $row->work_100; $unit_array['work_150'] = $row->work_150; $unit_array['work_300'] = $row->work_300; $query = $this->db->query('SELECT * FROM ltno_works_hours_client WHERE work_hour_id=\'' . $row->id . '\''); $unit_array['work_norm_client'] = isset($query->row()->work_norm) ? $query->row()->work_norm : ''; $unit_array['work_50_client'] = isset($query->row()->work_50) ? $query->row()->work_50 : ''; $unit_array['work_100_client'] = isset($query->row()->work_100) ? $query->row()->work_100 : ''; $unit_array['work_150_client'] = isset($query->row()->work_150) ? $query->row()->work_150 : ''; $unit_array['work_300_client'] = isset($query->row()->work_300) ? $query->row()->work_300 : ''; $unit_array['status'] = $row->accepted; $unit_array['work_type_options'] = $work_type_options; $result[$row->work_date][] = $unit_array; } return $result; } function save_work_hour($work_hours_list, $work_accepted) { foreach ($work_hours_list as $work_hour_info) { $work_hour_id = $work_hour_info['id']; $work_activity = $work_hour_info['work_activity']; $work_norm = $work_hour_info['work_norm']; $work_50 = $work_hour_info['work_50']; $work_100 = $work_hour_info['work_100']; $work_150 = $work_hour_info['work_150']; $work_300 = $work_hour_info['work_300']; $work_norm_client = $work_hour_info['work_norm_client']; $work_50_client = $work_hour_info['work_50_client']; $work_100_client = $work_hour_info['work_100_client']; $work_150_client = $work_hour_info['work_150_client']; $work_300_client = $work_hour_info['work_300_client']; $sql = 'UPDATE ltno_works_hours SET'; $sql .= ' work_norm=\'' . $work_norm . '\''; $sql .= ', work_50=\'' . $work_50 . '\''; $sql .= ', work_100=\'' . $work_100 . '\''; $sql .= ', work_150=\'' . $work_150 . '\''; $sql .= ', work_300=\'' . $work_300 . '\''; $sql .= ', accepted=\'' . $work_accepted . '\''; $sql .= ' WHERE id=\'' . $work_hour_id . '\''; $query = $this->db->query($sql); $sql = 'SELECT id FROM ltno_works_hours_client WHERE work_hour_id=\'' . $work_hour_id . '\''; $query = $this->db->query($sql); $exist = $query->num_rows(); if ($exist) { $sql = 'UPDATE ltno_works_hours_client SET '; $sql .= ' work_norm=\'' . $work_norm_client . '\''; $sql .= ', work_50=\'' . $work_50_client . '\''; $sql .= ', work_100=\'' . $work_100_client . '\''; $sql .= ', work_150=\'' . $work_150_client . '\''; $sql .= ', work_300=\'' . $work_300_client . '\''; $sql .= ' WHERE work_hour_id=\'' . $work_hour_id . '\''; $query = $this->db->query($sql); } else { $sql = 'INSERT INTO ltno_works_hours_client SET '; $sql .= ' work_hour_id=\'' . $work_hour_id . '\''; $sql .= ', work_norm=\'' . $work_norm_client . '\''; $sql .= ', work_50=\'' . $work_50_client . '\''; $sql .= ', work_100=\'' . $work_100_client . '\''; $sql .= ', work_150=\'' . $work_150_client . '\''; $sql .= ', work_300=\'' . $work_300_client . '\''; $query = $this->db->query($sql); } $query = $this->db->query('SELECT work_id FROM ltno_works_hours WHERE id=\'' . $work_hour_id . '\''); $work_id = $query->row()->work_id; $sql = 'UPDATE ltno_works SET'; $sql .= ' work_type_id=\'' . $work_activity . '\''; $sql .= ' WHERE id=\'' . $work_id . '\''; $query = $this->db->query($sql); } } }
true
44b2af2c2b0ce7922d984302a7ba754d8fc18ef1
PHP
danis24/wsa-panel
/app/Http/Traits/ClientTrait.php
UTF-8
425
2.53125
3
[ "MIT" ]
permissive
<?php namespace App\Http\Traits; use GuzzleHttp\Exception\GuzzleException; use GuzzleHttp\Client; trait ClientTrait { protected function postData($data) { $client = new Client(); return $client->request("POST", env("DICE_SITE").env("DICE_API_URL"), $data); } public function getData() { $client = new Client(); return $client->request("GET", env("DICE_SITE")); } }
true
4b66d5335be5bc6e5cfee1cc1430c2261e0299c7
PHP
assuncaovictor/Design-Patterns-em-PHP
/src/Descontos/DescontoMaisDe5Itens.php
UTF-8
414
2.6875
3
[]
no_license
<?php namespace Assuncaovictor\DesignPattern\Descontos; use Assuncaovictor\DesignPattern\Orcamento; final class DescontoMaisDe5Itens extends VerificaDesconto { protected function conficaoDoDesconto(Orcamento $orcamento): bool { return $orcamento->quantidadeItens > 5; } protected function valorDesconto(Orcamento $orcamento): float { return $orcamento->valor * 0.1; } }
true
8831db35f2b9365f539c04da590b2c9f173fb3c6
PHP
jorgegarces/bikelog
/tests/unit/Domain/Model/Bike/BikeDTOBuilder.php
UTF-8
1,348
2.875
3
[]
no_license
<?php namespace App\Tests\unit\Domain\Model\Bike; use App\Domain\Model\Bike\BikeDTO; class BikeDTOBuilder { private $id; private $brand; private $model; private $year; private $plateNumber; private function __construct() { $this->id = '83da585c-5788-4a39-a2ee-3fc568397b3f'; $this->plateNumber = '0000AAA'; $this->brand = 'Honda'; $this->model = 'Fireblade'; $this->year = 2000; } public static function aBike(): self { return new self(); } public function withId(string $id): self { $this->id = $id; return $this; } public function withBrand(string $brand): self { $this->brand = $brand; return $this; } public function withModel(string $model): self { $this->model = $model; return $this; } public function withYear(int $year): self { $this->year = $year; return $this; } public function withPlateNumber(string $plateNumber): self { $this->plateNumber = $plateNumber; return $this; } public function build(): BikeDTO { return new BikeDTO( $this->id, $this->plateNumber, $this->brand, $this->model, $this->year ); } }
true
91433d50b49ba8022ec55bfc0a5c26a8e0720003
PHP
chuck-cp/bjyltf
/cms/modules/sign/models/SignImage.php
UTF-8
1,266
2.78125
3
[]
no_license
<?php namespace cms\modules\sign\models; use Yii; /** * This is the model class for table "yl_sign_image". * * @property string $sign_id 签到表的ID * @property int $sign_type 签到类型(1、业务员签到 2、维护人员签到到) * @property string $image_url 店铺图片(多个图片以逗号分割) */ class SignImage extends \yii\db\ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return 'yl_sign_image'; } /** * {@inheritdoc} */ public function rules() { return [ [['sign_id', 'image_url'], 'required'], [['sign_id', 'sign_type'], 'integer'], [['image_url'], 'string'], [['sign_id'], 'unique'], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'sign_id' => 'Sign ID', 'sign_type' => 'Sign Type', 'image_url' => 'Image Url', ]; } /** * 获取拍照图片 */ public static function signImg($id,$type){ $imges=self::find()->where(['sign_id'=>$id,'sign_type'=>$type])->select('image_url')->asArray()->one()['image_url']; return explode(',',$imges); } }
true
66be019f21154ea6ff0103824ea7d9bdbd551c36
PHP
wowrainyman/Sarfejoo
/catalog/model/provider/pu_attribute.php
UTF-8
10,924
2.515625
3
[]
no_license
<?php require_once "provider.php"; require_once "settings.php"; class ModelProviderPuAttribute extends Model { public function addAttribute($data) { $this->db->query("INSERT INTO " . DB_PREFIX . "attribute SET attribute_group_id = '" . (int)$data['attribute_group_id'] . "', sort_order = '" . (int)$data['sort_order'] . "'"); $attribute_id = $this->db->getLastId(); foreach ($data['attribute_description'] as $language_id => $value) { $this->db->query("INSERT INTO " . DB_PREFIX . "attribute_description SET attribute_id = '" . (int)$attribute_id . "', language_id = '" . (int)$language_id . "', name = '" . $this->db->escape($value['name']) . "'"); } } public function editAttribute($attribute_id, $data) { $this->db->query("UPDATE " . DB_PREFIX . "attribute SET attribute_group_id = '" . (int)$data['attribute_group_id'] . "', sort_order = '" . (int)$data['sort_order'] . "' WHERE attribute_id = '" . (int)$attribute_id . "'"); $this->db->query("DELETE FROM " . DB_PREFIX . "attribute_description WHERE attribute_id = '" . (int)$attribute_id . "'"); foreach ($data['attribute_description'] as $language_id => $value) { $this->db->query("INSERT INTO " . DB_PREFIX . "attribute_description SET attribute_id = '" . (int)$attribute_id . "', language_id = '" . (int)$language_id . "', name = '" . $this->db->escape($value['name']) . "'"); } } public function deleteAttribute($attribute_id) { $this->db->query("DELETE FROM " . DB_PREFIX . "attribute WHERE attribute_id = '" . (int)$attribute_id . "'"); $this->db->query("DELETE FROM " . DB_PREFIX . "attribute_description WHERE attribute_id = '" . (int)$attribute_id . "'"); } public function getAttribute($attribute_id) { $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "attribute a LEFT JOIN " . DB_PREFIX . "attribute_description ad ON (a.attribute_id = ad.attribute_id) WHERE a.attribute_id = '" . (int)$attribute_id . "' AND ad.language_id = '" . (int)$this->config->get('config_language_id') . "'"); return $query->row; } public function getAttributes($data = array()) { $sql = "SELECT *, (SELECT agd.name FROM " . DB_PREFIX . "attribute_group_description agd WHERE agd.attribute_group_id = a.attribute_group_id AND agd.language_id = '" . (int)$this->config->get('config_language_id') . "') AS attribute_group FROM " . DB_PREFIX . "attribute a LEFT JOIN " . DB_PREFIX . "attribute_description ad ON (a.attribute_id = ad.attribute_id) WHERE ad.language_id = '" . (int)$this->config->get('config_language_id') . "'"; if (!empty($data['filter_name'])) { $sql .= " AND ad.name LIKE '" . $this->db->escape($data['filter_name']) . "%'"; } if (!empty($data['filter_attribute_group_id'])) { $sql .= " AND a.attribute_group_id = '" . $this->db->escape($data['filter_attribute_group_id']) . "'"; } $sort_data = array( 'ad.name', 'attribute_group', 'a.sort_order' ); if (isset($data['sort']) && in_array($data['sort'], $sort_data)) { $sql .= " ORDER BY " . $data['sort']; } else { $sql .= " ORDER BY attribute_group, ad.name"; } if (isset($data['order']) && ($data['order'] == 'DESC')) { $sql .= " DESC"; } else { $sql .= " ASC"; } if (isset($data['start']) || isset($data['limit'])) { if ($data['start'] < 0) { $data['start'] = 0; } if ($data['limit'] < 1) { $data['limit'] = 20; } $sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit']; } $query = $this->db->query($sql); return $query->rows; } public function getAttributeDescriptions($attribute_id) { $attribute_data = array(); $query = $this->db->query("SELECT * FROM " . DB_PREFIX . "attribute_description WHERE attribute_id = '" . (int)$attribute_id . "'"); foreach ($query->rows as $result) { $attribute_data[$result['language_id']] = array('name' => $result['name']); } return $attribute_data; } public function getAttributesByAttributeGroupId($data = array()) { $sql = "SELECT *, (SELECT agd.name FROM " . DB_PREFIX . "attribute_group_description agd WHERE agd.attribute_group_id = a.attribute_group_id AND agd.language_id = '" . (int)$this->config->get('config_language_id') . "') AS attribute_group FROM " . DB_PREFIX . "attribute a LEFT JOIN " . DB_PREFIX . "attribute_description ad ON (a.attribute_id = ad.attribute_id) WHERE ad.language_id = '" . (int)$this->config->get('config_language_id') . "'"; if (!empty($data['filter_name'])) { $sql .= " AND ad.name LIKE '" . $this->db->escape($data['filter_name']) . "%'"; } if (!empty($data['filter_attribute_group_id'])) { $sql .= " AND a.attribute_group_id = '" . $this->db->escape($data['filter_attribute_group_id']) . "'"; } $sort_data = array( 'ad.name', 'attribute_group', 'a.sort_order' ); if (isset($data['sort']) && in_array($data['sort'], $sort_data)) { $sql .= " ORDER BY " . $data['sort']; } else { $sql .= " ORDER BY ad.name"; } if (isset($data['order']) && ($data['order'] == 'DESC')) { $sql .= " DESC"; } else { $sql .= " ASC"; } if (isset($data['start']) || isset($data['limit'])) { if ($data['start'] < 0) { $data['start'] = 0; } if ($data['limit'] < 1) { $data['limit'] = 20; } $sql .= " LIMIT " . (int)$data['start'] . "," . (int)$data['limit']; } $query = $this->db->query($sql); return $query->rows; } public function getTotalAttributes() { $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "attribute"); return $query->row['total']; } public function getTotalAttributesByAttributeGroupId($attribute_group_id) { $query = $this->db->query("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "attribute WHERE attribute_group_id = '" . (int)$attribute_group_id . "'"); return $query->row['total']; } public function isCustomProduct($product_id) { $con_PU_db = $GLOBALS['con_PU_db']; $exist = false; $attribute_type = 0; $result = array(); $sql_select_string = "SELECT attribute_type FROM `pu_product_attributetype` WHERE `product_id` = $product_id"; $result_select = mysqli_query($con_PU_db, $sql_select_string) or die(mysqli_error()); while ($row = mysqli_fetch_assoc($result_select)) { $attribute_type = $row['attribute_type']; } return $attribute_type; } public function getCustomAttributes($category_id) { $con_PU_db = $GLOBALS['con_PU_db']; $sql_select_string = "SELECT * FROM `pu_category_attribute` WHERE `category_id` = $category_id"; $result_select = mysqli_query($con_PU_db, $sql_select_string) or die(mysqli_error()); if ($result_select) return $result_select; else return false; } public function getCustomAttribute($attribute_id) { $pu_database_name = $GLOBALS['pu_database_name']; $oc_database_name = $GLOBALS['oc_database_name']; $query = "SELECT * FROM $oc_database_name." . DB_PREFIX . "attribute a ,$oc_database_name." . DB_PREFIX . "attribute_description ad, $pu_database_name.pu_attributetype ac WHERE a.attribute_id = '" . (int)$attribute_id . "' AND a.attribute_id = ad.attribute_id AND a.attribute_id = ac.attribute_id"; $con_PU_db = $GLOBALS['con_PU_db']; $result_select = mysqli_query($con_PU_db, $query) or die(mysqli_error()); foreach ($result_select as $result) { return $result; } return false; } public function getCustomAttributeValues($attribute_id) { $query = "SELECT * FROM pu_attribute_value WHERE attribute_id = $attribute_id"; $con_PU_db = $GLOBALS['con_PU_db']; $result_select = mysqli_query($con_PU_db, $query) or die(mysqli_error()); if ($result_select) return $result_select; else return false; } public function addCustomAttribute($subprofile_id, $product_id, $attribute_id, $value) { $con_PU_db = $GLOBALS['con_PU_db']; $sql_insert_string = "INSERT INTO `pu_subprofile_product_attribute`" . "(`subprofile_id`, `product_id`, `attribute_id`, `value`)" . "VALUES ('$subprofile_id', '$product_id', '$attribute_id', '$value');"; $result_test_mod = mysqli_query($con_PU_db, $sql_insert_string) or die(mysqli_error()); $id = mysqli_insert_id($con_PU_db); return $id; } public function getAttributeValue($subprofile_id, $product_id, $attribute_id) { $query = "SELECT id,value FROM pu_subprofile_product_attribute WHERE subprofile_id = $subprofile_id AND product_id = $product_id AND attribute_id = $attribute_id"; $con_PU_db = $GLOBALS['con_PU_db']; $result_select = mysqli_query($con_PU_db, $query) or die(mysqli_error()); foreach ($result_select as $result) { return $result; } return false; } public function getImportantAttribute($product_id) { $query = "SELECT attribute_id FROM pu_attribute_important WHERE product_id = $product_id"; $con_PU_db = $GLOBALS['con_PU_db']; $result_select = mysqli_query($con_PU_db, $query) or die(mysqli_error()); $result = array(); foreach ($result_select as $row) { $result[] = $row; } return $result; } public function UpdateCustomAttribute($id, $value) { $con_PU_db = $GLOBALS['con_PU_db']; $exist = false; $sql_select_string = "SELECT * FROM `pu_subprofile_product_attribute` WHERE `id` = $id"; $result_select = mysqli_query($con_PU_db, $sql_select_string) or die(mysqli_error()); while ($row = mysqli_fetch_assoc($result_select)) { $exist = true; break; } if ($exist) { $sql_update_string = "UPDATE `pu_subprofile_product_attribute` SET " . "`value`='$value'" . " WHERE `id` = $id"; echo $sql_update_string; $result_test_mod = mysqli_query($con_PU_db, $sql_update_string) or die(mysqli_error()); return true; } else { return true; } } } ?>
true
8db2b932198855cbadfd6870610335f33290da7a
PHP
GoelVaibhav009/Laravel-Food-Delivery-API
/app/Http/Controllers/OrderItemController.php
UTF-8
1,546
2.515625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use App\Models\OrderItem; use Illuminate\Http\Request; use Illuminate\Support\Facades\Validator; class OrderItemController extends Controller { public function index() { return OrderItem::all(); } public function store(Request $request) { // $validator = Validator::make($request->all(), [ 'product_id' => 'required', 'price' => 'required', 'quantity'=>'required' ]); if ($validator->fails()) { return response(['errors' => $validator->errors()]); } $orderIem = $request->isMethod('put') ? OrderItem::findOrFail($request->orderIem_id) : new OrderItem; $orderIem->id = $request->input('order_item_id'); $orderIem->product_id = $request->input('product_id'); $orderIem->price = $request->input('price'); $orderIem->quantity = $request->input('quantity'); if ($orderIem->save()) { return $orderIem; } } public function show($id) { $orderIem = OrderItem::findOrFail($id); return $orderIem; } public function update(Request $request,$id) { $orderIem = OrderItem::findOrFail($id); $orderIem->update($request->all()); if ($orderIem->save()) { return $orderIem; } } public function destroy($id) { $orderIem = OrderItem::destroy($id); return $orderIem; } }
true
fbe698ccc47d49df4ad60c407be381a2993a1078
PHP
imran420/Dynamic_Slider
/dis.php
UTF-8
682
2.65625
3
[]
no_license
<?php include_once 'dbconnect.php'; //Create connection and select DB $db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName); //Check connection if($db->connect_error){ die("Connection failed: " . $db->connect_error); } //Get image data from database $result = $db->query("SELECT id, created FROM images order by created DESC limit 4"); $delete="update"; While($imgData = $result->fetch_assoc()){ echo "<div> <img data-u='image' src='display.php?id=". $imgData['id'] . "' ></div>"; echo "<div><tr><td>".$imgData['id']."</td><td><a href='update.php?id=".$imgData['id']."'>".$delete."</a></td></tr></div>"; } ?>
true
01743a2bdd435d71290d039bae166901f9a776a4
PHP
willyestrada81/RecruTECH
/helpers/system_helper.php
UTF-8
5,378
3.15625
3
[ "MIT" ]
permissive
<?php function redirect($page = FALSE, $message = NULL, $message_type = NULL) { if (is_string ($page)) { $location = $page; } else { $location = $_SERVER['SCRIPT_NAME']; } // Check for message if ($message != NULL) { // Set message $_SESSION['message'] = $message; } // Check for Type if ($message_type != NULL) { // Set message $_SESSION['message_type'] = $message_type; } // Redirect header('Location:'.$location); exit; } // Display Messages function displayMessage() { if (!empty($_SESSION['message'])) { // Assign message variable $message = $_SESSION['message']; if (!empty($_SESSION['message_type'])) { // Assign type variable $message_type = $_SESSION['message_type']; if ($message_type == 'error') { echo '<div class="container" id="alert-msg">'; echo '<div class="row justify-content-md-center">'; echo '<div class="col col-lg-6">'; echo '<div class="alert alert-danger" role="alert">' . $message .'</div>'; echo '</div>'; echo '</div>'; echo '</div>'; } elseif ($message_type == 'success') { echo '<div class="container" id="alert-msg">'; echo '<div class="row justify-content-md-center">'; echo '<div class="col col-lg-6">'; echo '<div class="alert alert-success" role="alert">' . $message .'</div>'; echo '</div>'; echo '</div>'; echo '</div>'; } } // Unset message unset($_SESSION['message']); unset($_SESSION['message_type']); } else { echo ''; } } function displayErrors() { if (!empty($_SESSION)) { foreach(array_values($_SESSION) as $values) { echo '<div class="container" id="alert-warning">'; echo '<div class="row justify-content-md-center">'; echo '<div class="col col-lg-6">'; echo '<div class="alert alert-warning" role="alert"><em>' . $values .'</em></div>'; echo '</div>'; echo '</div>'; echo '</div>'; } // Unset message unset($_SESSION['fname_errors']); unset($_SESSION['lname_errors']); unset($_SESSION['email_errors']); unset($_SESSION['pass_errors']); } else { echo ''; } } function isLoggedIn() { if (!empty($_SESSION['user'])) { return true; } else { return false; } } function isAdmin() { if (!empty($_SESSION['isAdmin']) && $_SESSION['isAdmin']) { return true; } else { return false; } } function check_user($user_data, &$user) { $result = $user->getUser($user_data); if ($result) { return true; } else { return false; } } function validate_fname($fname) { if ($fname == "") { $_SESSION['fname_errors'] = 'First name is required'; } else { return $fname; } } function validate_lname($lname) { if ($lname == "") { $_SESSION['lname_errors'] = 'Last name is required'; } else { return $lname; } } function validate_email($email) { if ($email == "") { $_SESSION['email_errors'] = "Email is Required"; } else if (!((strpos($email, ".") > 0) && (strpos($email, "@") > 0)) || preg_match("/[^a-zA-Z0-9.@_-]/", $email)) { $_SESSION['email_errors'] = "The Email address is invalid"; } else { return $email; } } function validate_password($password) { if ($password == "") { $_SESSION['pass_errors'] = "No Password was entered"; } else if (strlen($password) < 6) { $_SESSION['pass_errors'] = "Passwords must be at least 6 characters"; } else if (!preg_match("/[a-z]/", $password) || !preg_match("/[A-Z]/", $password) || !preg_match("/[0-9]/", $password)) { $_SESSION['pass_errors'] = "Passwords require 1 each of a-z, A-Z and 0-9"; } else { return password_hash($password, PASSWORD_DEFAULT); } } function validate_job_input($field) { if ($field == '') { $_SESSION['add_errors'] = "Please check required fields and try again."; } else { return $field; } } function validate_category($field) { if ($field == 0) { $_SESSION['add_errors'] = "Please check required fields and try again."; } else { return $field; } }
true
334f8e360b9479f42f323a618f40bd06332c851d
PHP
kmelo/myHealthHub
/public/removemed.php
UTF-8
682
2.609375
3
[]
no_license
<?php // configuration require("../includes/config.php"); if ($_SERVER["REQUEST_METHOD"] == "GET") { //retrieve user's current list of medications $drugs = CS50::query("SELECT drugName FROM medication WHERE userId=?",$_SESSION["id"]); // render user's current medication list render("remove_med.php", ["title" => "Remove Medication", "drugs" => $drugs]); } if ($_SERVER["REQUEST_METHOD"] == "POST") { CS50::query("DELETE FROM medication WHERE userId=? AND drugName=?",$_SESSION["id"], $_POST["drug"]); //redirect user to portfolio page header("Location: medications.php"); // stop running this script exit; } ?>
true
b90085f9dec8764a2f3822b509e186c0f5ce60c9
PHP
welcomedcoffee/dcoffee
/src/frontend/models/store/Preferential.php
UTF-8
1,455
2.546875
3
[ "BSD-3-Clause" ]
permissive
<?php namespace frontend\models\store; use Yii; /** * This is the model class for table "fin_preferential". * * @property integer $preferential_id * @property integer $merchant_id * @property integer $preferential_type * @property string $preferential_content * @property integer $preferential_start * @property integer $preferential_end * @property integer $addtime */ class Preferential extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'fin_preferential'; } /** * @inheritdoc */ public function rules() { return [ [['merchant_id', 'preferential_type', 'preferential_content', 'preferential_start', 'preferential_end', 'addtime'], 'required'], [['merchant_id', 'preferential_type', 'preferential_start', 'preferential_end', 'addtime'], 'integer'], [['preferential_content'], 'string', 'max' => 20] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'preferential_id' => 'Preferential ID', 'merchant_id' => 'Merchant ID', 'preferential_type' => 'Preferential Type', 'preferential_content' => 'Preferential Content', 'preferential_start' => 'Preferential Start', 'preferential_end' => 'Preferential End', 'addtime' => 'Addtime', ]; } }
true
f4ad25619c06a6940d20be7e3a689a61b2949ce6
PHP
AnaHolgado/DWES
/CapituloIV/ej13.php
UTF-8
3,519
2.84375
3
[]
no_license
<!DOCTYPE html> <!--Ejercicio 13. Escribe un programa que lea una lista de diez números y determine cuántos son positivos, y cuántos son negativos. --> <html> <head> <meta charset="UTF-8"> <meta name="keywords" content="Ejercicios PHP"> <meta name="author" content="Ana Holgado"> <title>Aprende PHP - Capitulo IV</title> <link href="../css/style.css" rel="stylesheet" type="text/css"/> </head> <body> <header id = "header"> <h1>APRENDE PHP CON EJERCICIOS</h1> <h2><a href= ../index.php>CAPITULO IV </a></h2> </header> <nav> <ul> <li><a href="ej7.php">Ejercicio 7</a></li> <li><a href="ej10.php">Ejercicio 10</a></li> <li><a href="ej13.php">Ejercicio 13</a></li> <li><a href="ej16.php">Ejercicio 16</a></li> <li><a href="ej20.php">Ejercicio 20</a></li> <li><a href="ej23.php">Ejercicio 23</a></li> <li><a href="ej28.php">Ejercicio 28</a></li> </ul> </nav> <section> <article> <h3>Ejercicio 13</h3> <p>Escribe un programa que lea una lista de diez números y determine cuántos son positivos, y cuántos son negativos.</p> </article> <article> <h3>Números Positivos y Negativos</h3> <?php if (!isset($_REQUEST['enviar'])){ $positivos = 0; $negativos = 0; $contador = 0; }else { $positivos = $_GET['positivos']; $negativos = $_GET['negativos']; $contador = $_GET['contador']; $contador++; $numero = $_GET['numero']; if($numero >= 0){ $positivos++; }else { $negativos++; } } ?> <form action="ej13.php" method="get"> <label>Numero:</label><input type="number" name="numero"> <input type="hidden" name="positivos" value="<?=$positivos?>"> <input type="hidden" name="negativos" value=<?=$negativos?>> <input type="hidden" name="contador" value=<?=$contador?>> <br> <?php if ($contador <10){ echo '<input type="submit" name="enviar" value ="Enviar">'; } ?> </form> </article> <article> <h3>Solución</h3> <p> <?php if ($contador == 10){ echo "Positivos: ".$positivos."<br>Negativos: ".$negativos; } ?> </p> </article> </section> <nav> <a href="ej10.php" id="anterior">Anterior</a> <a href="index.php" id="home">Home</a> <a href="ej16.php" id="siguiente">Siguiente</a> </nav> <footer> <p align="center" class="texto"> Página realizada por Ana Holgado Infante. <br>I.E.S. Campanillas. Desarrollo Web en Entorno Servidor.</p> </footer> </body> </html>
true
7450749aec0f7e03f68b9af4e002c4fe0dfd8847
PHP
jaydson/Kactoos-API
/tests/KactoosAPITest.php
UTF-8
5,472
2.5625
3
[ "MIT" ]
permissive
<?php require_once 'PHPUnit/Framework.php'; require_once dirname(__FILE__) . '/../kactoos-api.php'; /** * Test class for KactoosAPI. * Generated by PHPUnit on 2011-06-14 at 18:08:16. */ class KactoosAPITest extends PHPUnit_Framework_TestCase { /** * @var KactoosAPI */ protected $object; /** * Sets up the fixture, for example, opens a network connection. * This method is called before a test is executed. */ protected function setUp() { $this->object = new KactoosAPI; $this->object->apikey('8f14e45fceea167a5a36dedd4bea2543') ->country('br') ->module('products') ->appname('jaydson') ->format('xml'); } /** * Tears down the fixture, for example, closes a network connection. * This method is called after a test is executed */ protected function tearDown() { } /** * Test available formats */ public function testIsValidFormat() { $this->assertTrue($this->object->isValidFormat('xml')); $this->assertTrue($this->object->isValidFormat('json')); $this->assertFalse($this->object->isValidFormat(null)); $this->assertFalse($this->object->isValidFormat('')); $this->assertFalse($this->object->isValidFormat(array('a','b'))); } /** * Test parse of params to build a well formatted string to concat with URL */ public function testParseParams(){ $this->assertEquals($this->object->parseParams(array( 'type'=>'categorie-name', 'search'=>'android' )),'/type/categorie-name/search/android'); $this->assertEquals($this->object->parseParams(array( 'type'=>'categorie-id', 'search'=>76 )),'/type/categorie-id/search/76'); } /** * Test an well formatted URL to be passed to Kactoos API */ public function testBuildURL(){ $this->assertEquals($this->object ->buildURL('get-product-categories', array( 'type'=>'categorie-name', 'search'=>'android' )),'http://api.kactoos.com/br/api/products/get-product-categories/format/xml/appname/jaydson/apikey/8f14e45fceea167a5a36dedd4bea2543/type/categorie-name/search/android'); } /** * Test requests for Kactoos API */ public function testRequest() { $params = array('type'=>'categorie-name', 'search'=>'android'); $this->assertType(PHPUnit_Framework_Constraint_IsType::TYPE_OBJECT, $this->object->request('get-product-categories', $params)); } /** * Test valid country */ public function testCountry() { $this->assertNotNull($this->object->country('br')); } /** * Test valid module */ public function testModule() { $this->assertNotNull($this->object->module('products')); } /** * Test valid API KEY */ public function testApikey() { $this->assertNotNull($this->object->apikey('8f14e45fceea167a5a36dedd4bea2543')); } /** * Test valid App Name */ public function testAppname() { $this->assertNotNull($this->object->appname('jaydson')); } /** * Test valid Format */ public function testFormat() { $this->assertNotNull($this->object->format('xml')); } /** * Test GetProductCategories, must return an ProductCategories object */ public function testGetProductCategories() { } /** * @todo Implement testGetProductsByRange(). */ public function testGetProductsByRange() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * @todo Implement testGetProductsCountry(). */ public function testGetProductsCountry() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * @todo Implement testGetProductsMostBought(). */ public function testGetProductsMostBought() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * @todo Implement testGetProductsMostViewed(). */ public function testGetProductsMostViewed() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } /** * @todo Implement testGetProductList(). */ public function testGetProductList() { // Remove the following lines when you implement this test. $this->markTestIncomplete( 'This test has not been implemented yet.' ); } } ?>
true
ee7834b0dd84be51837d689f8a8ad377574652ed
PHP
nabilelmoudden/2015
/anaconda-project/businessCore/components/Business/GoogleAnalytics.php
UTF-8
689
2.65625
3
[]
no_license
<?php namespace Business; /** * Description of GoogleAnalytics * * @author JalalB * @package Business.GoogleAnalytics */ class GoogleAnalytics extends \GoogleAnalytics { // *********************** STATIC *********************** // static function model($className=__CLASS__) { return parent::model($className); } /** * * @param int $id * @return \Business\GoogleAnalytics */ static public function load( $id ) { return self::model()->findByPk( $id ); } /** * * @param string $key * @return \Business\GoogleAnalytics */ static public function loadByKey( $key ) { return self::model()->findByAttributes( array( 'code' => $key ) ); } } ?>
true
fd53845baf4a5e49f7f7a547ee9e0fce4b628351
PHP
wangyuesong/RateMyProfessor
/protected/models/User.php
UTF-8
4,446
2.59375
3
[]
no_license
<?php /** * This is the model class for table "User". * * The followings are the available columns in table 'User': * @property string $account * @property string $academy * @property string $password * @property string $name * @property integer $gender * @property string $email * @property string $phone * @property string $photo * @property integer $visibility * @property string $question * @property string $answer * * The followings are the available model relations: * @property Coursecomment[] $coursecomments * @property Friend[] $friends * @property Friend[] $friends1 * @property Friendapply[] $friendapplies * @property Friendapply[] $friendapplies1 * @property Teachercomment[] $teachercomments * @property Topic[] $topics * @property Topiccollection[] $topiccollections * @property Topicreply[] $topicreplies * @property Academy $academy0 */ class User extends CActiveRecord { /** * Returns the static model of the specified AR class. * @param string $className active record class name. * @return User the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } /** * @return string the associated database table name */ public function tableName() { return 'User'; } /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('account, password, name, gender, email', 'required'), array('gender, visibility', 'numerical', 'integerOnly'=>true), array('account, academy, password, name, phone', 'length', 'max'=>20), array('email', 'length', 'max'=>100), array('photo, question, answer', 'length', 'max'=>500), // The following rule is used by search(). // Please remove those attributes that should not be searched. array('account, academy, password, name, gender, email, phone, photo, visibility, question, answer', 'safe', 'on'=>'search'), ); } /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( 'coursecomments' => array(self::HAS_MANY, 'Coursecomment', 'account'), 'friends' => array(self::HAS_MANY, 'Friend', 'second_account'), 'friends1' => array(self::HAS_MANY, 'Friend', 'first_account'), 'friendapplies' => array(self::HAS_MANY, 'Friendapply', 'receive_account'), 'friendapplies1' => array(self::HAS_MANY, 'Friendapply', 'apply_account'), 'teachercomments' => array(self::HAS_MANY, 'Teachercomment', 'account'), 'topics' => array(self::HAS_MANY, 'Topic', 'account'), 'topiccollections' => array(self::HAS_MANY, 'Topiccollection', 'account'), 'topicreplies' => array(self::HAS_MANY, 'Topicreply', 'account'), 'academy0' => array(self::BELONGS_TO, 'Academy', 'academy'), ); } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'account' => '账号', 'academy' => '所属学院', 'password' => '密码', 'name' => '姓名', 'gender' => '性别', 'email' => 'Email', 'phone' => '手机', 'photo' => '照片', 'visibility' => '可见性', 'question' => '密码提示问题', 'answer' => '答案', ); } /** * Retrieves a list of models based on the current search/filter conditions. * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions. */ public function search() { // Warning: Please modify the following code to remove attributes that // should not be searched. $criteria=new CDbCriteria; $criteria->compare('account',$this->account,true); $criteria->compare('academy',$this->academy,true); $criteria->compare('password',$this->password,true); $criteria->compare('name',$this->name,true); $criteria->compare('gender',$this->gender); $criteria->compare('email',$this->email,true); $criteria->compare('phone',$this->phone,true); $criteria->compare('photo',$this->photo,true); $criteria->compare('visibility',$this->visibility); $criteria->compare('question',$this->question,true); $criteria->compare('answer',$this->answer,true); return new CActiveDataProvider($this, array( 'criteria'=>$criteria, )); } }
true
c98256d6866f0a0d1ba7d604b194e42a27c4ae91
PHP
darfio/weather
/app/Http/Controllers/WeatherController.php
UTF-8
774
2.75
3
[]
no_license
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Weather\YahooWeatherServiceProvider; use App\Weather\WeatherService; class WeatherController extends Controller { public function index(){ $yahooWeather = new YahooWeatherServiceProvider(); $weather_service = new WeatherService($yahooWeather); $temperature_farenheito = $weather_service->getTemperature(); $temperature_celsius = $this->farenheito_to_celsius($temperature_farenheito); $data = [ 'temperature_farenheito' => $temperature_farenheito, 'temperature_celsius' => $temperature_celsius, ]; return view('weather', $data); } private function farenheito_to_celsius($farenheito){ $celsius = ($farenheito - 32) * 5 / 9; return round($celsius); } }
true
2200bca4374286838d7f170db77364dd05eba90b
PHP
Saima1977/hotspot
/admin/test.php
UTF-8
660
2.671875
3
[ "MIT" ]
permissive
<?php function debugLogger($stmt) { $dir = "/var/www/hotspot/log/"; $dir_path = $dir."HS_ADMIN_DEVICE.log"; if (!file_exists($dir) ) { $oldmask = umask(0); // helpful when used in linux server mkdir($dir, 0744); } else { echo $dir_path." File Exists!<br/>"; } $logLine = "\n".date("Y-m-d H:i:s")."\tDEBUG\t".print_r($stmt, true)."\n\r"; $size = file_put_contents($dir_path, $logLine, FILE_APPEND |LOCK_EX); if ($size == FALSE) { return "Error writing file<br/>"; } else { return 1; } } $return = debugLogger("HELLO THERE"); echo $return; ?>
true
180f896b9e126b0d5c18c62bf301e8bb1f14ad57
PHP
aminerahmouni/anchour
/src/jubianchi/Output/Symfony/Adapter/ConsoleOutputAdapter.php
UTF-8
396
2.765625
3
[ "MIT" ]
permissive
<?php namespace jubianchi\Output; use Symfony\Component\Console\Output\ConsoleOutput; class ConsoleOutputAdapter implements OutputInterface { private $output; public function __construct(ConsoleOutput $output) { $this->output = $output; } public function __call($name, $args) { return call_user_func_array(array($this->output, $name), $args); } }
true
f058896a2e6500aa8ef2fc368bd7e514668232ab
PHP
juancitowillyr46/php-pet-hotel-web
/Backend/src/BackOffice/Pets/Domain/Entities/PetEntity.php
UTF-8
7,688
2.53125
3
[]
no_license
<?php namespace App\BackOffice\Pets\Domain\Entities; use App\BackOffice\Pets\Domain\Exceptions\PetActionRequestSchema; use App\Shared\Domain\Entities\Audit; use App\Shared\Utility\SecurityPassword; use Exception; use Ramsey\Uuid\Uuid; class PetEntity extends Audit { public string $name; public string $age; public string $age_type; public string $gender; public string $race; public string $image; public string $customer_id; public string $weight; public string $size; public string $diseases; public string $veterinary; public string $veterinary_phone; public string $treatments; public string $last_vaccine; public int $is_agressive; public string $observation; public string $init_zeal; public string $last_zeal; public string $other; /** * @return string */ public function getName(): string { return $this->name; } /** * @param string $name */ public function setName(string $name): void { $this->name = $name; } /** * @return string */ public function getAge(): string { return $this->age; } /** * @param string $age */ public function setAge(string $age): void { $this->age = $age; } /** * @return string */ public function getGender(): string { return $this->gender; } /** * @param string $gender */ public function setGender(string $gender): void { $this->gender = $gender; } /** * @return string */ public function getRace(): string { return $this->race; } /** * @param string $race */ public function setRace(string $race): void { $this->race = $race; } /** * @return string */ public function getImage(): string { return $this->image; } /** * @param string $image */ public function setImage(string $image): void { $this->image = $image; } /** * @return string */ public function getCustomerId(): string { return $this->customer_id; } /** * @param string $customer_id */ public function setCustomerId(string $customer_id): void { $this->customer_id = $customer_id; } /** * @return string */ public function getWeight(): string { return $this->weight; } /** * @param string $weight */ public function setWeight(string $weight): void { $this->weight = $weight; } /** * @return string */ public function getSize(): string { return $this->size; } /** * @param string $size */ public function setSize(string $size): void { $this->size = $size; } /** * @return string */ public function getDiseases(): string { return $this->diseases; } /** * @param string $diseases */ public function setDiseases(string $diseases): void { $this->diseases = $diseases; } /** * @return string */ public function getVeterinary(): string { return $this->veterinary; } /** * @param string $veterinary */ public function setVeterinary(string $veterinary): void { $this->veterinary = $veterinary; } /** * @return string */ public function getVeterinaryPhone(): string { return $this->veterinary_phone; } /** * @param string $veterinary_phone */ public function setVeterinaryPhone(string $veterinary_phone): void { $this->veterinary_phone = $veterinary_phone; } /** * @return string */ public function getTreatments(): string { return $this->treatments; } /** * @param string $treatments */ public function setTreatments(string $treatments): void { $this->treatments = $treatments; } /** * @return string */ public function getLastVaccine(): string { return $this->last_vaccine; } /** * @param string $last_vaccine */ public function setLastVaccine(string $last_vaccine): void { $this->last_vaccine = $last_vaccine; } /** * @return int */ public function getIsAgressive(): int { return $this->is_agressive; } /** * @param int $is_agressive */ public function setIsAgressive(int $is_agressive): void { $this->is_agressive = $is_agressive; } /** * @return string */ public function getAgeType(): string { return $this->age_type; } /** * @param string $age_type */ public function setAgeType(string $age_type): void { $this->age_type = $age_type; } // /** // * @return bool // */ // public function isIsAgressive(): bool // { // return $this->is_agressive; // } // // /** // * @param bool $is_agressive // */ // public function setIsAgressive(bool $is_agressive): void // { // $this->is_agressive = $is_agressive; // } /** * @return string */ public function getObservation(): string { return $this->observation; } /** * @param string $observation */ public function setObservation(string $observation): void { $this->observation = $observation; } /** * @return string */ public function getInitZeal(): string { return $this->init_zeal; } /** * @param string $init_zeal */ public function setInitZeal(string $init_zeal): void { $this->init_zeal = $init_zeal; } /** * @return string */ public function getLastZeal(): string { return $this->last_zeal; } /** * @param string $last_zeal */ public function setLastZeal(string $last_zeal): void { $this->last_zeal = $last_zeal; } /** * @return string */ public function getOther(): string { return $this->other; } /** * @param string $other */ public function setOther(string $other): void { $this->other = $other; } public function payload(object $formData): void { try { $validate = new PetActionRequestSchema(); $validate->getMessages((array)$formData); $this->identifiedResource($formData); $this->setName($formData->name); $this->setAge($formData->age); $this->setAgeType($formData->ageType); $this->setGender($formData->gender); $this->setRace($formData->race); $this->setImage($formData->image); $this->setWeight($formData->weight); $this->setSize($formData->size); $this->setDiseases($formData->diseases); $this->setVeterinary($formData->veterinary); $this->setVeterinaryPhone($formData->veterinaryPhone); $this->setTreatments($formData->treatments); $this->setLastVaccine($formData->lastVaccine); $this->setObservation($formData->observation); $this->setInitZeal($formData->initZeal); $this->setLastZeal($formData->lastZeal); $this->setOther($formData->other); $this->setActive($formData->active); } catch(Exception $ex) { throw new Exception($ex->getMessage(), $ex->getCode()); } } }
true
a5a1ffb8b81afa0aba96e9b26c226be72d17a4ab
PHP
theOstrich952/PersonalSite
/View/Projects/Modify/ajax/homeAjax.php
UTF-8
547
2.515625
3
[]
no_license
<?php require_once '../include/databaseConnection.php'; $type = $_POST['type']; $query = "SELECT * FROM products where type LIKE %'$type'%"; $result = mysqli_query($con, $query); $resultArr = array(); $x = 0; while($row = mysqli_fetch_assoc($result)) { $resultArr[$x][0] = [$row['title']]; $resultArr[$x][1] = [$row['stock']]; $resultArr[$x][2] = [$row['details']]; $resultArr[$x][3] = [$row['type']]; $x++; } echo json_encode($resultArr); ?>
true
72a1c51c5180c21efaf45dda8e9ca8baebc82361
PHP
Ekimik/image-share
/app/model/Adapters/AdapterFactory.php
UTF-8
1,884
2.796875
3
[ "Unlicense" ]
permissive
<?php namespace App\Model\Adapters; use \Nette\Object, \Nette\Utils\Strings, \App\Model\Exceptions\InvalidArgumentException, \App\Strategies\Notification\EmailNotification, \App\Strategies\Notification\NullNotification, \App\Model\Services\ConfigParams; /** * @author Jan Jíša <j.jisa@seznam.cz> * @package ImageShare */ class AdapterFactory extends Object { /** * @var ConfigParams */ protected $cfg; public function __construct(ConfigParams $cfg) { $this->cfg = $cfg; } public function create($name) { $name = Strings::lower($name); $adapter = NULL; if ($name === 'filesystemuploadadapter') { $adapter = new FileSystemUploadAdapter(); } else { throw new InvalidArgumentException(sprintf('Unknown adapter %s', $name)); } $this->configureNotifications($adapter); return $adapter; } /** * @param IAdapter $adapterInstance */ protected function configureNotifications($adapterInstance) { $notificationSettings = $this->cfg->get('notifications'); $codeName = $this->cfg->get('appCodeName'); $adapterName = $adapterInstance->getAdapterName(); if (!empty($notificationSettings) && !is_null($codeName) && isset($notificationSettings[$codeName][$adapterName])) { $from = $notificationSettings[$codeName][$adapterName]['from']; $to = $notificationSettings[$codeName][$adapterName]['to']; $subject = $notificationSettings[$codeName][$adapterName]['subject']; $message = $notificationSettings[$codeName][$adapterName]['message']; $adapterInstance->setNotificationAbility(new EmailNotification($from, $to, $subject, $message)); } else { $adapterInstance->setNotificationAbility(new NullNotification()); } } }
true
764b805ddae4fdf8ee2f57a6938c93d2c94202c3
PHP
adehikmatiana/materi-laravel-haltev
/Week 2/Day1/code/variabel.php
UTF-8
659
3.609375
4
[]
no_license
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>belajar variabel</title> <?php $nama = "Tiana"; $umur = 21; $pesan = "Saya sedang belajar PHP"; ?> </head> <body> <h1>Halo, nama saya <?= $nama; ?>, kemudian usia saya saat ini adalah <?= $umur ?> </h1> <h2>ini adalah pesan wasiat saya $pesan </h2> <? $tempat_lahir = array("bekasi", "jayapura"); $siswa = array("tiana", "hikma", "ade", "raden", "sangunda"); echo "nama sayaa $siswa[0] dan saya lahir di $tempat_lahir[1]"; ?> </body> </html>
true
2b776294344b98f1b0ce5523b817085c9930cec0
PHP
beniwal-devika/IIT-Courses-CS430
/dijkstrasAlgorithm.php
UTF-8
1,061
3.484375
3
[]
no_license
<?php class dijkstrasAlgorithm { function __construct() { } function findMinimumKey($key, $mset) { $min = INF; foreach ($key as $index => $value) { if ($mset[$index] == 'false' && $min >= $value) { $min = $value; $minIndex = $index; } } return $minIndex; } function dijkstras($graph, $vertex, $mset, $key, $source) { for ($i = 0; $i < $vertex; $i++) { $row = $this->findMinimumKey($key, $mset); $mset[$row] = 'true'; for ($col = 0; $col < $vertex; $col++) { if ($graph[$row][$col] && $mset[$col] == 'false' && $key[$row] != INF && $key[$col] > $graph[$row][$col] + $key[$row]) { $key[$col] = $graph[$row][$col] + $key[$row]; } } } echo "Shortest Path from source to vertex : \n"; foreach ($key as $index => $value) { echo $source. " to ".$index . " ->" . $value . "\n"; } } } ?>
true
d7e05880d30b0c926c2b7d4dc10a5869494b3dfb
PHP
dragostinova/php7-design-patterns
/Tests/Creational/SimpleFactoryTest.php
UTF-8
1,439
2.890625
3
[]
no_license
<?php namespace DesignPatterns\Tests\Creational; use DesignPatterns\Creational\SimpleFactory\CsvReport; use DesignPatterns\Creational\SimpleFactory\JsonReport; use DesignPatterns\Creational\SimpleFactory\ReportFactory; use DesignPatterns\Creational\SimpleFactory\ReportInterface; use PHPUnit\Framework\TestCase; final class SimpleFactoryTest extends TestCase { public function testFactoryCreateJsonReport() { $reportFactory = new ReportFactory(); $jsonReport = $reportFactory->create('json'); $this->assertInstanceOf(JsonReport::class, $jsonReport); $this->assertInstanceOf(ReportInterface::class, $jsonReport); } public function testJsonReportData() { $reportFactory = new ReportFactory(); $jsonReport = $reportFactory->create('json'); $data = [ 'Bradley Cooper' => 'A Star Is Born', 'Peter Farrelly' => 'Green Book', 'Sean Anders' => 'Instant Family', ]; $expectedString = json_encode($data); $jsonString = $jsonReport->export($data); $this->assertJsonStringEqualsJsonString($expectedString, $jsonString); } public function testFactoryCreateCsvReport() { $reportFactory = new ReportFactory(); $csvReport = $reportFactory->create('csv'); $this->assertInstanceOf(CsvReport::class, $csvReport); $this->assertInstanceOf(ReportInterface::class, $csvReport); } }
true
ab20d9bfc7a35d4f7d780ffbb83a36eab254e9e8
PHP
CodiumTeam/legacy-training-php
/print-date/src/Calendar.php
UTF-8
121
2.71875
3
[]
no_license
<?php namespace PrintDate; class Calendar { public function now() { return date("Y-m-d H:i:s"); } }
true
2814e9dc8fdc3941a39edcf934273d8d296d6d7c
PHP
valmayaki/countryapp
/app/Core/Http/Response.php
UTF-8
2,529
2.796875
3
[ "MIT" ]
permissive
<?php namespace App\Core\Http; class Response { protected $body; protected $status; protected $headers; function __construct($content='', $status = 200, $headers = []) { $this->body = $content; $this->status = $status; $this->headers = $headers; } public function setHeader($header, $value) { $this->headers[$header] = $value; } public function getHeaders() { return $this->headers; } public function send() { $this->sendHeaders(); $this->sendBody(); } /** * Send header to client * * @return void */ protected function sendHeaders() { foreach($this->headers as $header => $value){ if (strpos($header, '-') !== false){ $headerParts = explode('-', $header); $headerParts = array_map('\ucfirst', $headerParts); $header = \implode('-', $headerParts); } header(sprintf('%s: %s', ucfirst($header), $value)); } } /** * Displays the body of the request * * @return void */ public function sendBody() { echo $this->body; } public function render($viewFile, $data = []) { extract($data); if ($viewFile[0] !== '/'){ $viewFile = '/'.$viewFile; } ob_start(); require VIEW_PATH. $viewFile; $this->body = \ob_get_clean(); return $this; } public function withHeader($name, $value) { $this->setHeader($name, $value); return $this; } public function withHeaders(array $headers) { $this->headers = array_merge($this->headers, $headers); return $this; } public function withBody($content) { $this->body = $content; return $this; } public function json($data = [], $status = 200, $headers = []) { $this->body = json_encode($data); $this->status = $status; $this->withHeaders($headers); $this->withHeader('content-type', 'application/json'); return $this; } public function sendStatusCode() { http_response_code($this->status); } public function redirect($url) { $this->withHeader('location', $url); $this->withStatusCode(304); return $this; } public function withStatusCode($code) { $this->status = $code; return $this; } }
true
eb0f7ca3142858441a6340af389117d8023dc27a
PHP
omar-farooq/duffa
/php/models/Database.php
UTF-8
781
3.03125
3
[]
no_license
<?php class Database extends PDO { const PDO_HOST = ''; const PDO_DATABASE = ''; const PDO_USERNAME = ''; const PDO_PASSWORD = ''; const PDO_OPTIONS = [PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"]; public function __construct () { try { parent::__construct( "mysql:host=" . self::PDO_HOST . ";dbname=" . self::PDO_DATABASE, self::PDO_USERNAME, self::PDO_PASSWORD, self::PDO_OPTIONS ); $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); } catch ( PDOException $Exception ) { echo $Exception->getMessage(); } } } ?>
true
a5bcc7c12647451188d9df81efb2a112d4f67e93
PHP
xepps/jollymagic
/app/tests/Sitemap/SitemapBuilderTest.php
UTF-8
1,853
2.71875
3
[ "Apache-2.0" ]
permissive
<?php namespace Jollymagic\Sitemap; class SitemapBuilderTest extends \PHPUnit_Framework_TestCase { public function testThatGivenASiteMapItGeneratesAListOfSitemapUrlObjects() { // $sitemapBuilder = new SitemapBuilder('http://test.com', $this->getMockSiteConfig()); // $expectedSitemap = // '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"' . // 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"' . // 'xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9' . // 'http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd">' . // '<url>' . // '<loc>http://test.com/</loc>' . // '<changefreq>monthly</changefreq>' . // '<priority>1.00</priority>' . // '</url>' . // '<url>' . // '<loc>http://test.com/test</loc>' . // '<changefreq>hourly</changefreq>' . // '<priority>0.80</priority>' . // '</url>' . // '</urlset>'; // $this->assertXmlStringEqualsXmlString( // $expectedSitemap, // $sitemapBuilder->build() // ); } private function getMockSiteConfig() { return (object)array( 'index' => (object)array( 'url' => '/', 'changeFrequency' => 'monthly', 'priority' => '1.00' ), 'not-wanted' => (object)array( 'doNotSitemap' => true ), 'test' => (object)array( 'url' => '/test', 'changeFrequency' => 'hourly', 'priority' => '0.80' ), ); } }
true
96b91c7fcddf0b908442af98f3f0f62d78d3c169
PHP
DoubleLift3/Assignment3
/FW_Assignment3/framework/Data_Mapper.php
UTF-8
1,204
2.78125
3
[]
no_license
<?php namespace Quwi\framework; abstract class Data_Mapper{ //protected $pdo; public function __construct() { //$reg = Registry::instance(); //$this->pdo = $reg->getPdo(); } abstract protected function findAll(); abstract protected function find(string $id); abstract protected function insert(); /* { $this->selectstmt()->execute(); $row = $this->selectstmt()->fetch(); $this->selectstmt()->closeCursor(); if (! is_array($row)) { return null; } if (! isset($row['id'])) { return null; } $object = $this->createObject($row); return $object;}*/ // abstract protected function createObject(array $raw): DomainObject; // { // $obj = $this->doCreateObject($raw); //return $obj; // } // abstract protected function insert(DomainObject $obj); //{ // $this->doInsert($obj); // } // abstract protected function selectStmt(); //abstract protected function doInsert(DomainObject $object); // abstract protected function doCreateObject(array $raw): DomainObject; }
true
26d90229a0fca460ba18f5674a5dbcb717f89234
PHP
signifly/travy-schema
/src/Sidebar.php
UTF-8
1,220
3.015625
3
[ "MIT" ]
permissive
<?php namespace Signifly\Travy\Schema; use JsonSerializable; use Signifly\Travy\Schema\Concerns\Instantiable; /** @method static static make($name, array $groups) */ class Sidebar implements JsonSerializable { use Instantiable; /** * The displayable name of the tab. * * @var string */ protected $name; /** * The sidebar groups. * * @var array */ protected $groups; /** * Create a new tab. * * @param string $name */ public function __construct($name, array $groups) { $this->name = $name; $this->groups = $groups; } /** * Prepare the groups for JSON serialization. * * @return array */ protected function preparedGroups(): array { return collect($this->groups) ->map(function (Group $group) { return $group->jsonSerialize(); }) ->all(); } /** * Prepare the sidebar for JSON serialization. * * @return array */ public function jsonSerialize(): array { return [ 'name' => $this->name, 'groups' => $this->preparedGroups(), ]; } }
true
a6d13579f566ba72d7a8284a1c56841f87190e4c
PHP
astratow/easy_steps
/forloop.php
UTF-8
464
3.765625
4
[]
no_license
<!DOCTYPE HTML> <html lang="en"> <head> <meta charset="utf-8"> <title> Basic PHP template - Performing for loops</title> </head> <body> <?php #write traditional greetings; echo '<h1>Performing for loops</h1>'; for($i=1; $i<4; $i++){ echo "<dt>Outer loop iteration $i"; #nested loop to go here for($j=1; $j<4; $j++){ echo "<dd>Inner loop iteration $j"; } } ?> </body> </html>
true
bd16df4d79fe64ef26f536946a1365ab7b057d7e
PHP
ishikhir/gsworkphp
/php03/functions.php
UTF-8
614
2.984375
3
[]
no_license
<?php /** 共通で使うものを別ファイルにしておきましょう。*/ //DB接続関数(PDO) function pdoLocalhost(){ try { return $pdo = new PDO('mysql:dbname=myHome;charset=utf8;host=localhost','root',''); }catch (PDOException $e) { exit('DbConnectError:'.$e->getMessage()); } } //SQL処理エラー function qerror($stmt){ $error = $stmt->errorInfo(); exit("ErrorQuery:".$error[2]); } /** * XSS * @Param: $str(string) 表示する文字列 * @Return: (string) サニタイジングした文字列 */ function xss($val){ return htmlspecialchars($val,ENT_QUOTES,"UTF-8"); } ?>
true
fc6a36e195e778997a3b938e8f3883a0f70ac98e
PHP
nextras/orm
/src/Collection/Helpers/ArrayCollectionHelper.php
UTF-8
5,456
2.578125
3
[ "MIT" ]
permissive
<?php declare(strict_types = 1); namespace Nextras\Orm\Collection\Helpers; use Closure; use DateTimeImmutable; use DateTimeInterface; use Nette\Utils\Arrays; use Nextras\Orm\Collection\Aggregations\IArrayAggregator; use Nextras\Orm\Collection\Functions\CollectionFunction; use Nextras\Orm\Collection\Functions\FetchPropertyFunction; use Nextras\Orm\Collection\Functions\Result\ArrayExpressionResult; use Nextras\Orm\Collection\ICollection; use Nextras\Orm\Entity\IEntity; use Nextras\Orm\Entity\Reflection\PropertyMetadata; use Nextras\Orm\Exception\InvalidArgumentException; use Nextras\Orm\Repository\IRepository; use function array_map; use function array_shift; use function is_array; class ArrayCollectionHelper { /** * @param IRepository<IEntity> $repository */ public function __construct( private readonly IRepository $repository, ) { } /** * @phpstan-param array<mixed> $expr * @phpstan-param IArrayAggregator<mixed>|null $aggregator * @phpstan-return Closure(IEntity): ArrayExpressionResult */ public function createFilter(array $expr, ?IArrayAggregator $aggregator): Closure { $function = isset($expr[0]) ? array_shift($expr) : ICollection::AND; $customFunction = $this->repository->getCollectionFunction($function); return function (IEntity $entity) use ($customFunction, $expr, $aggregator) { return $customFunction->processArrayExpression($this, $entity, $expr, $aggregator); }; } /** * @phpstan-param array<array<string, mixed>|list<mixed>> $expressions * @phpstan-return Closure(IEntity, IEntity): int */ public function createSorter(array $expressions): Closure { /** @var list<array{CollectionFunction, string, array<mixed>}> $parsedExpressions */ $parsedExpressions = []; $fetchPropertyFunction = $this->repository->getCollectionFunction(FetchPropertyFunction::class); foreach ($expressions as $expression) { if (is_array($expression[0])) { if (!isset($expression[0][0])) { throw new InvalidArgumentException(); } $function = array_shift($expression[0]); $collectionFunction = $this->repository->getCollectionFunction($function); $parsedExpressions[] = [$collectionFunction, $expression[1], $expression[0]]; } else { $parsedExpressions[] = [$fetchPropertyFunction, $expression[1], [$expression[0]]]; } } return function ($a, $b) use ($parsedExpressions): int { foreach ($parsedExpressions as [$function, $ordering, $functionArgs]) { $_a = $function->processArrayExpression($this, $a, $functionArgs)->value; $_b = $function->processArrayExpression($this, $b, $functionArgs)->value; $descReverse = ($ordering === ICollection::ASC || $ordering === ICollection::ASC_NULLS_FIRST || $ordering === ICollection::ASC_NULLS_LAST) ? 1 : -1; if ($_a === null || $_b === null) { // By default, <=> sorts nulls at the beginning. $nullsReverse = $ordering === ICollection::ASC_NULLS_FIRST || $ordering === ICollection::DESC_NULLS_FIRST ? 1 : -1; $result = ($_a <=> $_b) * $nullsReverse; } elseif (is_int($_a) || is_float($_a) || is_int($_b) || is_float($_b)) { $result = ($_a <=> $_b) * $descReverse; } else { $result = ((string) $_a <=> (string) $_b) * $descReverse; } if ($result !== 0) { return $result; } } return 0; }; } /** * @phpstan-param string|array<string, mixed>|list<mixed> $expression * @phpstan-param IArrayAggregator<mixed>|null $aggregator */ public function getValue( IEntity $entity, array|string $expression, ?IArrayAggregator $aggregator, ): ArrayExpressionResult { if (is_string($expression)) { $function = FetchPropertyFunction::class; $collectionFunction = $this->repository->getCollectionFunction($function); $expression = [$expression]; } else { $function = isset($expression[0]) ? array_shift($expression) : ICollection::AND; $collectionFunction = $this->repository->getCollectionFunction($function); } return $collectionFunction->processArrayExpression($this, $entity, $expression, $aggregator); } public function normalizeValue( mixed $value, PropertyMetadata $propertyMetadata, bool $checkMultiDimension = true, ): mixed { if ($checkMultiDimension && isset($propertyMetadata->types['array'])) { if (is_array($value) && !is_array(reset($value))) { $value = [$value]; } if ($propertyMetadata->isPrimary) { foreach ($value as $subValue) { if (!Arrays::isList($subValue)) { throw new InvalidArgumentException('Composite primary value has to be passed as a list, without array keys.'); } } } } if ($propertyMetadata->wrapper !== null) { $property = $propertyMetadata->getWrapperPrototype(); if (is_array($value)) { $value = array_map(function ($subValue) use ($property) { return $property->convertToRawValue($subValue); }, $value); } else { $value = $property->convertToRawValue($value); } } elseif ( (isset($propertyMetadata->types[DateTimeImmutable::class]) || isset($propertyMetadata->types[\Nextras\Dbal\Utils\DateTimeImmutable::class])) && $value !== null ) { $converter = static function ($input): int { if (!$input instanceof DateTimeInterface) { $input = new DateTimeImmutable($input); } return $input->getTimestamp(); }; if (is_array($value)) { $value = array_map($converter, $value); } else { $value = $converter($value); } } return $value; } }
true
d07f0bde3b2f0dfb60162c1cbfb5d0d73111a1c2
PHP
boy-luo/fancy
/dataforrand.php
UTF-8
23,193
2.578125
3
[]
no_license
<?php session_start(); ?> <!DOCTYPE html> <!-- 如果没有此声明,IE低版本将不能解释固定在两边的盒子 --> <html> <head> <title>处理我的数据</title> <!-- 使页面的编码是utf-8,避免在浏览器输出的是乱码 --> <meta http-equiv="Content-type" content="text/html;charset=utf-8"> <!-- 包含css文件 --> <link rel = "stylesheet" type = "text/css" href = "data.css"> <?php include ("config.php"); include ("functions.php"); ?> </head> <body> <div id="bodyface"> 实现功能: 1:输入文件名,或文章进行分析词频 ---文件内可以存在中文,系统会自动踢出中文 2:可以自动分析文章内所有词汇的词频,也可以设置自己需要的词汇进行词频收索 ..... ---缺点:输出词频时若还有和最后一个排名单词同排名的单词,不能输出,因为设定了输出个数 ---改进方法:在末尾进行继续比较,若相同则输出,若不同则停止。 运用到的知识: 1:提供表单:进行自定义的各种操作 2:文件的打开与关闭,存取, 3:正则表达式的运用,提取英文单词 ..... 缺点: 1:代码重复严重,如果数据重要性不高,可以改成函数操作 若数据重要,可以改成对象操作实现封装 感想与收获: 工作之前没有准备,没有书写计划书,过程沿着思路去实现 缺乏工程思想,思路和实现顺序,实现方式等没有清晰计划 收获:1:开始工作之前书写概要计划书,再写详细计划书很有必要, 它可以帮助理清思路,详细功能,详细实现步骤,明确每步工作 2:发现需要用到的知识,计划选择好需要的方式,如对象或函数,或直接实现 2:设计好需要实现的具体功能,各个功能实现的先后顺序, 3:各个功能之间会有数据交叉现象,需要事前有清晰的计划他们之间的协作, 否则后期多次修改会增加数倍工作量 4:过程中会出现很多错误,修改时一定要记下修改的地方和修改的内容, 不然后面难以恢复,从而反复修改,增加工作量,甚至难以恢复 5:遇到问题时,出去走走,清理思路,冷静思考是很好的方法, 对于找出解决方案,找出错误原因有极大帮助 6:过程中多多间断的休息,可以保持头脑清醒 但是此次任务留到下次处理,将会忘记上次的思路,基本你需要从新开工计划。。。。 表单:按钮添加数据 进行各种操作: 1:自己分析总结方案 添加方案元素 选择方案元素 删除数据 查看数据 查询某一组 查询多组数据 推算 总结 分析 颜色标记 勾选或拉选,或输入开始结尾的下标,选择分析数组个数 查看各种方案分别的总结结果 2维数组 尾部写入文件 读出数据---匹配数组---写入总结得出的方案 每行5个数据 每行颜色不同 选择颜色 函数实现 横纵距离 单双比 出现的时间间隔,出现间隔时间的长久 与上一组 ,和上几组的前后临近数据的差距 周期性聚集 聚集或分散 对结果进行再综合进一步分析 循环对结果的结果进行分析,选择循环次数 写出每次的总结结果 结果一排名形式显示 第一步:直接复制数据到文件中 第二部:读出数据,正则匹配,形成数组 3,把数据组分成周期请聚拢,离散, 4,把单个数据分成周期性出现, 5,吧数据组单双比例得出周期性变化 进行方案选择,然后匹配总结 写总结结果到文件 写匹配成功率到文件 输出匹配结果 输出匹配成功率 4:匹配度,总结的成功率,效率 结果写入文件 //读出数据,正则匹配,形成数组的函数--参数为:文件名 //可以定义一个长度,选择性读取一定长度的内容,默认为全部读出 写入数据--参数:写入的文件名称, 写入方式a,w追加还是全部替换覆盖??需要写入的内容?? 本文件包含函数: 读取文件到字符串;把字符串正则匹配变成数组;清除文件的数据; 24法则及数据录入,历史重复? 还未出现过的数组,出现数组的集中性分析 <?php //知识总结结束 //》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》> ?> <?php //输出时间,用于计算运行时间 $timestart=microtime(); echo "<br>页面开始运行的详细时间是:".$timestart."!<br><br>"; echo $test; ?> <?php //session的判断建立 //《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《< //注册session数组,保存需要的各种信息 //注册session数组,保存第几次处理信息,用于创建每次的处理文件夹 if(!isset($_SESSION["data"]["orderFolder"])){ //注册session数组中的order,保存第几次处理信息,用于创建每次的处理文件夹 $_SESSION["data"]["orderFolder"]=1; //保存当前正在处理第几个文档 $_SESSION["data"]["orderTxt"]=1; //注册session数组中的folder,保存第几次处理信息,用于创建每次的处理文件夹 //保存文件夹存储路径--当前文件夹路径下的dataFolder文件夹。 $_SESSION["data"]["folderPath"]="./datafolder/"; //保存当前正在处理的第几个文件夹 $_SESSION["data"]["folder"]="No folder even now!"; //保存当前正在处理的第几个文档 $_SESSION["data"]["txt"]="No txt even now!"; echo "这是第".$_SESSION["data"]["orderFolder"]."次处理!"; }else{ //重置文件数据,用于增加新变量后,或者反复测试而使用 //unset($_SESSION["data"]["orderFolder"]); //$_SESSION["data"]["folderPath"]="./dataFolder/"; //unset($_SESSION["order"]); //当前文件夹的名称 $_SESSION["data"]["folder"]=$_SESSION["data"]["folderPath"].$_SESSION["data"]["orderFolder"]."time"; //当前处理文档的名称 $_SESSION["data"]["txt"]=$_SESSION["data"]["folder"]."/".$_SESSION["data"]["orderTxt"]."data.txt"; echo "<br>"; //#6a5acd #191970 echo "<font color='#4b0082' size='5px'><b>上次处理到文件夹:".$_SESSION["data"]["folder"]."了!<br>"; echo "这是第".$_SESSION["data"]["orderFolder"]."次处理!<br>"; echo "正在处理文件".$_SESSION["data"]["folder"]."中的".$_SESSION["data"]["txt"]."文档!<b></font><br>"; } //按钮操作结束 //》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》> ?> <div id="out"> <div id="topface"> <div id="topencourage"> 热情与激情,鼓励着生命:<br> <?php $promise[0]="加油!"; $promise[1]="只有努力,才能实现,只有坚持,才能做到!"; $promise[2]="继续坚持,不断改进,相信会有意料之外的收获的!"; $promise[3]="没有奢望就没有失望!"; $promise[4]="只有向前,"; $promise[5]="只有努力,才能实现,只有坚持,才能做到!"; //$rand=rand(0,5); $rand=rand(0,60)%6; //echo $rand; echo $promise[$rand]; ?> </div> <div id="hint"> 其他的提示信息栏:<br> <br> 所有session信息:<br> <br> <br> <?php //重置 //setSessions(); //查看成员 //sessions(); ?> <?php //按钮操作 //《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《< //点击进入下一次,重新开始处理 if(@ $_POST["nextTime"]){ echo "你点击了 创建下一个处理文件!<br>"; $_SESSION["data"]["orderFolder"]++; $path= $_SESSION["data"]["folderPath"].$_SESSION["data"]["orderFolder"]."time"; createFolder($path); //新的处理文档次序从0 开始计数。 $_SESSION["data"]["orderTxt"]=0; } //点击进行下一次数据处理 if(@ $_POST["nextDispose"]){ echo "你点击了 创建下一个处理文档!<br>"; $_SESSION["data"]["orderTxt"]++; $fileName= $_SESSION["data"]["folder"]."/".$_SESSION["data"]["orderTxt"]."data.txt"; //createFolder($fileName); createTxtDocument($fileName); } //点击随机数据,并验证历史未出现过 if(@ $_POST["randData"]){ echo "你点击了产生一组随机数据,并验证历史未出现过!<br>"; echo "产生的一组随机数据:"; //产生6个随机数 for($j=0; $j<6; $j++){ //产生1-33之间的随机数 $randArray[$j]=rand()%33+1; //验证避免重复(一组数据中的数据间有数据重复)---6个数各不相同。 for($i=0; $i<$j; $i++){ //如果一组数据中的数据间有数据重复了就重新生成随机数,直到不重复为止 while($randArray[$j] == $randArray[$i]){ $randArray[$j]=rand()%33+1; } } echo $randArray[$j]."\t"; } echo "<br>"; //参数:历史全部数据生成的数组,产生的随机数组,历史数据的详细信息形成的数组 $chek = have_or_no_this_array($nowArray,$randArray,$resulte); echo $chek."<br>"; /* $randArray = array(04,05,11,12,30,32); $chek = have_or_no_this_array($nowArray,$randArray,$resulte); echo $chek."<br>"; $randArray = array(10,11,12,13,26,28); $chek = have_or_no_this_array($nowArray,$randArray,$resulte); echo $chek."<br>"; */ echo "<br>"; } //按钮操作结束 //》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》 ?> </div> </div> <?php //数据显示区域 //《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《 ?> <div id="datas"> <div id="dataorigin"> 原始数据:<br> <br> 单个数据的统计结果:<br> </div> <div id="dataask"> 要求的数据:<br> 写入的换行符不能直接在txt中实现,认为写入的却不能读出,为什么??、 <br> 进行预处理,吧首字母相同的放到一个数组中,形成3维数组或更多维的数组 <br> 减少每次的比较量,如500,800组一次等还是的量 现在在处理更新后的历史全部数据(量很大,在config页面做了数据数组预处理) <br> <?php //已经运行得出结果证明,里面没有重复数据出现过 //声明一个数组,存储各个相同数组的相同次数---避免没有相同的,所以给了一个值 /* for($j=1; $j<40; $j++){ $sameCount[$j]=0; } */ //定义一个,避免在没有重复数据的时候后边的输出报错 $sameCount[1]=0; //循环N次比较,行数++就好了 //for($j=0; $j<count($nowArray); $j++){ echo "<br>循环次数即是数据总条数为:".count($nowArray)."----<br>"; /* //统计6个数据相同的数组count6 echo "统计有6个数据全部相同的数组.<br>"; $N=6; for($j=0; $j<count($nowArray); $j++){ //第几行的1-6个数据与后面所有行的1-6个数据比较 //$i=0; $k = $j+1; //为了避免首次计数时出现未定义情况,所以定义一个每次的公用计数器 //$sameCount[1] = 1; while($k<count($nowArray)){ //比较每个数组的$N个元素 for($i=0; $i<$N; $i++){ //if($k>=count($nowArray)){ if($k>=count($nowArray)){ //echo "总数据条数(即是数组数):".count($nowArray)."<br>"; break 1; } //先判断结束,或判断是否进行下一次 if($nowArray[$j][$i] != $nowArray[$k][$i]) { //echo "两组数据不等!<br>"; //因为for里面$i会++,所以$i此处赋值-1。 //$i=-1; $k++; //continue; //与下一组数据进行比较 break 1; }else if($i!=$N){ //echo $i."进行下一次比较!<br>"; $k++; continue; }else{ //统计出现相同的次数(缺点:会被反复统计,因为统计后没有没替换) if($sameCount[$j+1]){ ++$sameCount[$j+1]; }else{ $sameCount[$j+1] = 1; } //$sameCount[$j+1] += $sameCount[1]; //遍历输出整行的所有元素,即是详细信息 echo $arrayMesage[$j]."\t 和<br>".$arrayMesage[$k]."\t 是相同的<br><br>"; $i=-1; $k++; //continue; } } } } */ ///* //统计sameN个数据相同,$diffrentN个不同的数组count5 /* 思路: 准备工作: 定义要找与数组数据有 几个 以上相同个数的数组--个数 并说明要与数组的多少个数据比较 开始比较: 循环取出每组数据,与它后面的所有数据进行比较 初始化每组数据所找到的有相同个数满足要求的数据的数组 循环与它后面的所有数据进行比较: 如果不是在和最后一组数据进行比较 则与下一组数据进行比较 初始化与下一组数组有的相同数据个数为0 循环与数组的6个数据进行分别的比较 //如不相同的个数已经超出允许的个数 //----则(退出一层)退出与此组数据的每个数据的比较与下一组数据进行比较 //如果是 如果不相同 不相同数据的个数加1, 如不相同的个数已经超出允许的个数 ----则(退出一层)退出与此组数据的每个数据的比较 ----与下一组数据进行比较 如果没有超出个数 如果不是最后一个数据 则与下一个数据进行比较 否则 判断是输出第几次找到合理数组 并进行合理输出 然后与下一组数据进行比较 如果现在这两个正在比较的数据是相同的 如果不是最后一个数据 则与下一个数据进行比较 否则 判断是输出第几次找到合理数组 并进行合理输出 然后与下一组数据进行比较 欠缺: 只是对应位置上的数据相同才能被找到 比如 1,3,5,8,9 1,2,3,8,9 这样的不会被找到 没有让每一个数据 与其它的每一个数据进行比较 运行时间有待提升 收获: 找到了很多有5个相同的数据组 当然由缺点导致还有很多没有被找到 需要改进 */ $sameN = 5; $diffrentN = 6-$sameN; //每组数据有6个数据 $N=6; //echo $nowArray[0][1]."<br>"; //echo $nowArray[1300][4]."<br>"; echo "统计有 $sameN 个数据相同的数组.<br>"; /* echo $resulte[0]."<br>"; echo $resultArry[300]."<br>"; echo $resulte[1200]."<br>"; echo $resulte[1200][0]."<br>"; echo $resulte[1200][3]."<br>"; echo $resulte[1200][5]."<br>"; echo $resultArry[1700]."<br>"; echo $arrayMesage[0]."<br>"; echo $arrayMesage[300]."<br>"; echo $arrayMesage[1200]."<br>"; echo $arrayMesage[1700]."<br>"; */ //for($j=0; $j<count($nowArray); $j++){ $times=count($nowArray); for($j=0; $j<$times; $j++){ //第几行的1-6个数据与后面所有行的1-6个数据比较 $k = $j; //为了避免首次计数时出现未定义情况, //所以定义一个每组数据找到的满足要求的 //数据个数的数组个数的公用计数器 $thisEchoTime = 0; //for($k=0; $k<count($nowArray); $k++){ while($k<count($nowArray)-1){ $k++; //用于记录与每组数据的不同数据的个数 //用于判断是否超出了允许的不同数据的个数 $thisDiffrent = 0; //比较每个数组的$N(6)个元素 for($i=0; $i<$N; $i++){ //if($k>=count($nowArray) || $thisDiffrent>$diffrentN){ //if($thisDiffrent>$diffrentN || $k>=count($nowArray)){ //如果与本组数据的不同数据量已经超出了 //则与下一组数据进行比较。 /* 可以注释 2个 if($thisDiffrent>$diffrentN){ //echo "总数据条数(即是数组数):".count($nowArray)."<br>"; //$k++; //continue; break 1; } //这一组的比较结束了,进行下一组的比较 if($k>=count($nowArray)){ //echo "总数据条数(即是数组数):".count($nowArray)."<br>"; //$k++; //continue; break 2; } */ //如果正在比较的两个数据不相同 //先判断是结束一层循环,还是进行下一次比较 if($nowArray[$j][$i] != $nowArray[$k][$i]) { $thisDiffrent++; //如果已经有超出允许的不同数据的个数, //则与下一组数据进行比较 if($thisDiffrent > $diffrentN) { break 1; //如果没有超出允许的数据的个数 }else{ //如果比较的不是第六个 //则继续与下一组数据进行比较 if($i < $N-1){ continue; //否则就是第6个数据了, //依之前的判断是已经有符合要求的相同的数据个数了 //则进行相同组数的统计与判断 }else{ //用于统计输出次数的变量 ++$thisEchoTime; //如果是第一次输出, //说明是目前的唯一一组符合相同个数要求的数据 //否则说明不止找到了此一组数据符合要求,之前已经有了 if($thisEchoTime==1){ $sameCount[$j] = 1; //遍历输出整行的所有元素,即是详细信息 //echo $arrayMesage[$j]."\t <br>--------和<br>".$arrayMesage[$k]."\t 有".($N-$thisDiffrent)."个是相同的数据。<br>"; echo "<br><br><br>下面一组找到了有".$sameN."个相同数据的:<br>".$arrayMesage[$j]."<br>".$arrayMesage[$k]."<br>"; write($_SESSION["data"]["txt"],"\r\r\r <br><br><br>下面一组找到了有".$sameN."个相同数据的:<br>".$arrayMesage[$j]."<br>".$arrayMesage[$k]."<br> \r"); }else{ $sameCount[$j] ++; //echo "\t <br>--------和<br>".$arrayMesage[$k]."\t 有".($N-$thisDiffrent)."个是相同的数据。<br>"; echo $arrayMesage[$k]."<br>"; write($_SESSION["data"]["txt"],$arrayMesage[$k]."<br> \r"); } break 1; } } //如果正在比较的两个数据相同 }else{ if($i < $N-1){ //echo $i."进行下一次比较!<br>"; continue; }else{ //用于统计输出次数的变量 ++$thisEchoTime; //统计出现相同的次数(缺点:会被反复统计,因为统计后没有没替换) if($thisEchoTime==1){ $sameCount[$j] = 1; //遍历输出整行的所有元素,即是详细信息 //echo $arrayMesage[$j]."\t <br>--------和<br>".$arrayMesage[$k]."\t 有".($N-$thisDiffrent)."个是相同的<br>"; echo "<br><br><br>下面一组找到了有".$sameN."个相同数据的:<br>".$arrayMesage[$j]."<br>".$arrayMesage[$k]."<br>"; write($_SESSION["data"]["txt"],"\r\r\r <br><br><br>下面一组找到了有".$sameN."个相同数据的:<br>".$arrayMesage[$j]."<br>".$arrayMesage[$k]."<br> \r"); }else{ $sameCount[$j] ++; //echo "\t <br>--------和<br>".$arrayMesage[$k]."\t 有".($N-$thisDiffrent)."个是相同的<br>"; echo $arrayMesage[$k]."<br>"; write($_SESSION["data"]["txt"],$arrayMesage[$k]."<br> \r"); /* //写入文件数据---写入之后注释以备下次更新数据时需要重新写入内容时再次使用 if($j == $N-1){ //write($_SESSION["data"]["txt"],"\n"); write($_SESSION["data"]["txt"],"\n".$resultArry[$j]); }else{ //写到文件中去 write($_SESSION["data"]["txt"],$resultArry[$j]."\t"); //write($fileName,$content); } */ //写到文件中去 //write($_SESSION["data"]["txt"],$resultArry[$j]."\t"); //write($_SESSION["data"]["txt"],$arrayMesage[$k]."<br> \t"); } break 1; } } } } } //*/ //输出各组相同数组的相同次数 if(count($sameCount) != 1){ foreach($sameCount as $key=>$value){ echo "下标为:".$key."的数组相同的次数为:----".$value."次!<br>"; echo "数组详细信息为:".$resulte[$key]."<br>"; //echo $value."<br>"; } }else{ echo "抱歉。先生,现目前还没有重复数据!<br>"; } ?> <br><br><br> <?php //统计单个数据的历史出现总次数 echo "统计单个数据的历史出现总次数<br>"; $CountOne=count_one_history($nowArray,33); $numberCount=count($CountOne); echo "数据个数:".$numberCount."个。<br>"; /* foreach($CountOne as $key=>$value){ echo "数据:".$key."出现的次数为:".$value."次。<br>"; } */ for($j=1; $j<34; $j++){ //echo $CountOne[$j]; echo "数据:".($j)."出现的次数为:".$CountOne[$j]."次。<br>"; } ?> </div> <div id="datalast"> 上次结果:<br> <?php ?> </div> </div> <?php //数据显示区域结束 //》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》> ?> <div id="tables"> 表单:<br> <?php //操作表单的区域 //《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《《< ?> <div id="tableleft"> 左边表单:操作<br> <form action="" method="post" style="border=5px;" name="Selectform"> <input type="submit" name="nextTime" value="进入下一次处理,创建下一个处理文件" /> <input type="submit" name="nextDispose" value="进行下一次数据处理,创建下一个处理结果的存储txt" /> <input type="submit" name="randData" value="一组随机数,并验证历史" /> <input type="submit" name="sub" value="创建此名称的文件" /> <input type="text" name="txtName" value="" />输入要处理的txt文件名称(需要提前将文件存入指定文件夹下,其中可以包含有中文但不作处理)<br> <input type="text" name="txtFile" style="width=500px" style="height=100px" value="" />或者输入需要处理的英文文章(其中可以包含有中文但不作处理)<br> <input type="text" name="selectWords" value="" />输入查询的数组<br> <input type="text" name="ignorWords" value="" />输入设定要忽略的数组<br> <input type="text" name="topN" value="" />输入设定要显示数组排名的前多少组<br> <input type="text" name="topN" value="" />24法则及数据录入,历史重复? 还未出现过的数组,出现数组的集中性分析<br> <input type="submit" name="sub" value="提交" /> </form> </div> <?php //操作表单的区域结束 //》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》》> ?> <div id="tableright"> 右边表单:文件名称 <?php //遍历现有的文件 //声明一个变量,记录文件个数 $fileNum = 0; //$dirname = './'; $dirname = $_SESSION["data"]["folderPath"]; echo "函数遍历文件夹!<br>"; //调用遍历文件夹函数 ergodicFolder($dirname); ?> </div> </div> <br><br><br> </div> <!-- 底部的网站声明 --> <div id="foot"> 感谢,,,的大力支持。 <br> 欢迎入驻本站。 <br> 有需要合作请联系:QQ704863481。 <br> <?php //输出时间,用于计算运行时间 $timeend=microtime(); echo "<br>页面开始运行的详细时间是:".$timestart."!<br>"; echo "页面结束运行的详细时间是:".$timeend."!<br><br>"; echo "页面运行的总时间是:".($timeend-$timestart)."!<br>"; ?> </div> <div id=""> </div> <!-- bodyface结束前 --> bodyface结束前 </div> body结束前 </body> </html>
true
c1992a4677bb2278309374a900aad34e2591a368
PHP
xXCaulDevsYT/KitPvP
/src/kitpvp/duels/pieces/Arena.php
UTF-8
1,197
3.203125
3
[]
no_license
<?php namespace kitpvp\duels\pieces; use pocketmine\Player; use pocketmine\math\Vector3; use pocketmine\level\{ Level, Position }; class Arena{ public $id; public $name; public $spawn1; public $spawn2; public $level; public function __construct($id, $name, Vector3 $spawn1, Vector3 $spawn2, Level $level){ $this->id = $id; $this->name = $name; $this->spawn1 = $spawn1; $this->spawn2 = $spawn2; $this->level = $level; //echo $this->spawn1->getX() . "," . $this->spawn1->getY() . "," . $this->spawn1->getZ(), PHP_EOL; //echo $this->spawn2->getX() . "," . $this->spawn2->getY() . "," . $this->spawn2->getZ(), PHP_EOL; } public function getId(){ return $this->id; } public function getName(){ return $this->name; } public function getSpawn1(){ return $this->spawn1; } public function getSpawn2(){ return $this->spawn2; } public function getLevel(){ return $this->level; } public function teleport(Player $player1, Player $player2){ $player1->teleport($this->getLevel()->getSpawnLocation()); $player2->teleport($this->getLevel()->getSpawnLocation()); $player1->teleport($this->getSpawn1()); $player2->teleport($this->getSpawn2()); } }
true
9a4b1de3b3df41505eae0ae8e887e7f2332554f4
PHP
warner23/kkblog
/app/core/class/Db.php
UTF-8
8,597
3.125
3
[]
no_license
<?php /** * Database Class * Created by Warner Infinity * Author Jules Warner */ class Db extends PDO { private static $_instance; public function __construct($DB_TYPE, $DB_HOST, $DB_NAME, $DB_USER, $DB_PASS) { try { parent::__construct($DB_TYPE.':host='.$DB_HOST.';dbname='.$DB_NAME.';charset=utf8', $DB_USER, $DB_PASS); $this->exec('SET CHARACTER SET utf8'); // comment this line if you don't want error reporting $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); } catch (PDOException $e) { die ( 'Connection failed: ' . $e->getMessage() ); } } // this function creates an instance of db public static function getInstance() { // create instance if doesn't exist if ( self::$_instance === null ) self::$_instance = new self(DB_TYPE, DB_HOST, DB_NAME, DB_USER, DB_PASS); return self::$_instance; } public function select($sql, $array = array(), $fetchMode = PDO::FETCH_ASSOC) { $this->db = self::getInstance(); $smt = $this->db->prepare($sql); //print_r($smt); foreach ($array as $key => &$value) { //echo ":$key", $value; $smt->bindParam(":$key", $value, PDO::PARAM_STR); } $smt->execute(); $result = $smt->fetchAll($fetchMode); $smt->closeCursor(); if($result > 0){ return $result; }else{ echo "null"; } } public function selectwithOptions($sql, $array = array(), $fetchMode = PDO::FETCH_ASSOC) { $this->db = self::getInstance(); $smt = $this->db->prepare($sql); foreach ($array as $key => &$value) { //echo ":$key", $value; $smt->bindParam(':$key', $value, PDO::PARAM_STR); } $smt->execute(); $result = $smt->fetchAll($fetchMode); $smt->closeCursor(); if($result > 0){ return $result; }else{ echo "null"; } } public function Selected($sql, $array = array(), $fetchMode = PDO::FETCH_ASSOC, $while) { $this->db = self::getInstance(); $smt = $this->db->prepare($sql); foreach ($array as $key => &$value) { //echo ":$key", $value; $smt->bindParam(":$key", $value, PDO::PARAM_STR); } $smt->execute(); while ($result = $smt) { echo $while; } $smt->closeCursor(); return $query; } public function selectColumn($sql, $array = array(), $column, $fetchMode = PDO::FETCH_ASSOC) { $db = self::getInstance(); $sth = $db->prepare($sql); foreach ($array as $key => &$value) { $sth->bindParam(":$key", $value); } $sth->execute(); $result = $sth->fetch($fetchMode); //echo $result[$column]; $sth->closeCursor(); //echo "chat_id" . $result[$column]; return $result[$column]; } public function blindFreeColumn($sql, $column, $fetchMode = PDO::FETCH_ASSOC) { $db = self::getInstance(); $sth = $db->prepare($sql); $sth->execute(); $result = $sth->fetch($fetchMode); $sth->closeCursor(); // return $result[$column]; } public function bindfree($query) { $this->db = self::getInstance(); $smt = $this->db->prepare($query); $smt->execute(); $smt->closeCursor(); return $query; } public function insert($table, $data) { ksort($data); $fieldNames = implode('`, `', array_keys($data)); $fieldValues = ':' . implode(', :', array_keys($data)); $sth = $this->prepare("INSERT INTO $table (`$fieldNames`) VALUES ($fieldValues)"); foreach ($data as $key => &$value) { $sth->bindParam(":$key", $value, PDO::PARAM_STR); } $sth->execute(); } public function Arrayinsert($table, $data) { ksort($data); $fieldNames = implode('`, `', array_keys($data)); var_dump($fieldNames); $fieldValues = ':' . implode(', :', array_keys($data)); var_dump($fieldValues); $sth = $this->prepare("INSERT INTO $table (`$fieldNames`) VALUES ($fieldValues)"); foreach ($data as $key => &$value) { $sth->bindParam(":$key", $value, PDO::PARAM_STR); } $sth->execute(); } public function update($table, $data, $where, $whereBindArray = array()) { $this->db = self::getInstance(); ksort($data); //var_dump($data); $fieldDetails = NULL; foreach($data as $key => &$value) { $fieldDetails .= "`$key`=:$key,"; } $fieldDetails = rtrim($fieldDetails, ','); //var_dump($fieldDetails); $smt = $this->db->prepare("UPDATE $table SET $fieldDetails WHERE $where"); //var_dump($smt); foreach ($data as $key => &$value) { //echo ":$key", $value; $smt->bindParam(":$key", $value, PDO::PARAM_STR); //var_dump($value); } foreach ($whereBindArray as $key => &$value) { //echo ":$key", $value; $smt->bindParam(":$key", $value, PDO::PARAM_STR); //var_dump($value); } //var_dump($smt); $smt->execute(); $smt->closeCursor(); } public function delete($table, $where, $bind = array(), $limit = 1) { $this->WIdb = self::getInstance(); $smt = $this->WIdb->prepare("DELETE FROM $table WHERE $where LIMIT $limit"); foreach ($bind as $key => &$value) { $smt->bindParam(":$key", $value); } $smt->execute(); $smt->closeCursor(); } function dd($value) //to be deleted { echo"<pre>",print_r($value,true), "<pre>"; die(); } function executeQuery($sql,$data) { global $conn; $stmt=$conn->prepare($sql); $values=array_values($data); $types= str_repeat('s',count($values)); $stmt->bind_param($types,...$values); $stmt->execute(); return $stmt; } function selectAll($table,$conditions=[]) { global $conn; $sql="SELECT *FROM $table"; if(empty($conditions)){ $stmt=$conn->prepare($sql); $stmt->execute(); $records=$stmt->get_result()->fetch_all(MYSQLI_ASSOC); return $records; } else{ //$sql="SELECT * FROM $table WHERE username='Adarsh' AND admin=1"; $i=0; foreach($conditions as $key => $value){ if($i===0){ $sql= $sql . " WHERE $key=?"; }else{ $sql=$sql . " AND $key=?"; } $i++; } $stmt=executeQuery($sql,$conditions); $records=$stmt->get_result()->fetch_all(MYSQLI_ASSOC); return $records; } } function selectOne($table,$conditions) { global $conn; $sql="SELECT *FROM $table"; $i=0; foreach($conditions as $key => $value){ if($i===0){ $sql= $sql . " WHERE $key=?"; }else{ $sql=$sql . " AND $key=?"; } $i++; } //$sql="SELECT * FROM users WHERE admin=0 AND username='Adarsh' LIMIT 1"; $sql= $sql . " LIMIT 1 "; $stmt=executeQuery($sql,$conditions); $records=$stmt->get_result()->fetch_assoc(); return $records; } function create($table,$data){ global $conn; //sql="INSERT INTO users SET username=?,admin=?,email=?,password=?" $sql=" INSERT INTO $table SET "; $i=0; foreach($data as $key => $value){ if($i===0){ $sql= $sql . " $key=?"; }else{ $sql=$sql . ", $key=?"; } $i++; } $stmt=executeQuery($sql,$data); $id=$stmt->insert_id; return $id; } function updateDetails($table,$id,$data){ global $conn; //sql="UPDATE users SET username=?,admin=?,email=?,password=? WHERE id=?" $sql=" UPDATE $table SET "; $i=0; foreach($data as $key => $value){ if($i===0){ $sql= $sql . " $key=?"; }else{ $sql=$sql . ", $key=?"; } $i++; } $sql=$sql . " WHERE id=? "; $data['id']=$id; $stmt=executeQuery($sql,$data); return $stmt->affected_rows; } function deleteFromTable($table,$id){ global $conn; //sql="DELETE FROM users WHERE id=?" $sql=" DELETE FROM $table WHERE id=? "; $stmt=executeQuery($sql,['id'=>$id]); return $stmt->affected_rows; } } ?>
true
763bc8eecbfc49ef23330e0b8b8219c18bc31396
PHP
softsquad-git/movie
/app/Helpers/Status.php
UTF-8
733
3.171875
3
[ "MIT" ]
permissive
<?php namespace App\Helpers; class Status { public const OFF = 0; public const ON = 1; public const WAITING = 2; public const LOCKED = 3; /** * @param int $statusCode * @return string|null */ public static function getNameStatus(int $statusCode): ?string { switch ($statusCode) { case 0: return 'No active'; break; case 1: return 'Active'; break; case 2: return 'Waiting'; break; case 3: return 'Locked'; break; default: return null; break; } } }
true
916373e53eaf2bf6d1cebc7e094402c0ccc02725
PHP
minioak/royalmail-shipping
/src/Structs/ContentDetails.php
UTF-8
3,482
2.71875
3
[ "MIT" ]
permissive
<?php namespace Minioak\Royalmail\Shipping\Structs; use \WsdlToPhp\PackageBase\AbstractStructBase; /** * This class stands for contentDetails Structs * Meta informations extracted from the WSDL * - documentation: schema to hold array of single parcel structures * @subpackage Structs */ class ContentDetails extends AbstractStructBase { /** * The contentDetail * Meta informations extracted from the WSDL * - maxOccurs: unbounded * @var \Minioak\Royalmail\Shipping\Structs\ContentDetail[] */ public $contentDetail; /** * Constructor method for contentDetails * @uses ContentDetails::setContentDetail() * @param \Minioak\Royalmail\Shipping\Structs\ContentDetail[] $contentDetail */ public function __construct(array $contentDetail = array()) { $this ->setContentDetail($contentDetail); } /** * Get contentDetail value * @return \Minioak\Royalmail\Shipping\Structs\ContentDetail[]|null */ public function getContentDetail() { return $this->contentDetail; } /** * Set contentDetail value * @throws \InvalidArgumentException * @param \Minioak\Royalmail\Shipping\Structs\ContentDetail[] $contentDetail * @return \Minioak\Royalmail\Shipping\Structs\ContentDetails */ public function setContentDetail(array $contentDetail = array()) { foreach ($contentDetail as $contentDetailsContentDetailItem) { // validation for constraint: itemType if (!$contentDetailsContentDetailItem instanceof \Minioak\Royalmail\Shipping\Structs\ContentDetail) { throw new \InvalidArgumentException(sprintf('The contentDetail property can only contain items of \Minioak\Royalmail\Shipping\Structs\ContentDetail, "%s" given', is_object($contentDetailsContentDetailItem) ? get_class($contentDetailsContentDetailItem) : gettype($contentDetailsContentDetailItem)), __LINE__); } } $this->contentDetail = $contentDetail; return $this; } /** * Add item to contentDetail value * @throws \InvalidArgumentException * @param \Minioak\Royalmail\Shipping\Structs\ContentDetail $item * @return \Minioak\Royalmail\Shipping\Structs\ContentDetails */ public function addToContentDetail(\Minioak\Royalmail\Shipping\Structs\ContentDetail $item) { // validation for constraint: itemType if (!$item instanceof \Minioak\Royalmail\Shipping\Structs\ContentDetail) { throw new \InvalidArgumentException(sprintf('The contentDetail property can only contain items of \Minioak\Royalmail\Shipping\Structs\ContentDetail, "%s" given', is_object($item) ? get_class($item) : gettype($item)), __LINE__); } $this->contentDetail[] = $item; return $this; } /** * Method called when an object has been exported with var_export() functions * It allows to return an object instantiated with the values * @see AbstractStructBase::__set_state() * @uses AbstractStructBase::__set_state() * @param array $array the exported values * @return \Minioak\Royalmail\Shipping\Structs\ContentDetails */ public static function __set_state(array $array) { return parent::__set_state($array); } /** * Method returning the class name * @return string __CLASS__ */ public function __toString() { return __CLASS__; } }
true
1c6d0ba91574c31b7810ba1170cc3416955fd721
PHP
nelson6e65/Geonames
/src/Console/Geoname.php
UTF-8
902
2.765625
3
[ "MIT" ]
permissive
<?php namespace MichaelDrennen\Geonames\Console; use Illuminate\Console\Command; class Geoname extends Command { use GeonamesConsoleTrait; /** * The name and signature of the console command. * * @var string */ protected $signature = 'geonames:geoname'; /** * The console command description. * * @var string */ protected $description = "This command downloads and inserts the files you want from geonames.org and saves them locally."; /** * @var array List of absolute local file paths to downloaded geonames files. */ protected $localFiles = []; /** * Download constructor. */ public function __construct () { parent::__construct(); } public function handle () { $this->call( 'geonames:download-geonames' ); $this->call( 'geonames:insert-geonames' ); } }
true
f91242b47c2f6e863820625846667358c6c358a1
PHP
Audrene-C/comparOperateur
/apps/add-destination.php
UTF-8
4,983
2.640625
3
[]
no_license
<?php $path = str_replace('apps', '', __DIR__); //include($path.'/comparOperateur/config/autoload.php'); include($path.'/config/autoload.php'); //include_once $path.'/comparOperateur/partials/connection.php'; include_once $path.'/partials/connection.php'; $destinationsManager = new DestinationsManager($pdo); $osef = new Operator(['osef', 1, 'osef', 0]); if (!empty($_POST['location']) AND !empty($_POST['price']) AND !empty($_POST['operator'])) { $location = $_POST['location']; $price = $_POST['price']; $operator = $_POST['operator']; if (isset($_FILES['small-img']) AND $_FILES['small-img']['error'] == 0) { if ($_FILES['small-img']['size'] <= 1000000) { $infosfichier = pathinfo($_FILES['small-img']['name']); $extension_upload = $infosfichier['extension']; $extensions_autorisees = array('jpg', 'jpeg', 'gif', 'png'); if (in_array($extension_upload, $extensions_autorisees)) { move_uploaded_file($_FILES['small-img']['tmp_name'], 'uploads/' . basename($_FILES['small-img']['name'])); if (isset($_FILES['large-img']) AND $_FILES['large-img']['error'] == 0) { if ($_FILES['large-img']['size'] <= 1000000) { $infosfichier = pathinfo($_FILES['large-img']['name']); $extension_upload = $infosfichier['extension']; $extensions_autorisees = array('jpg', 'jpeg', 'gif', 'png'); if (in_array($extension_upload, $extensions_autorisees)) { move_uploaded_file($_FILES['large-img']['tmp_name'], 'uploads/' . basename($_FILES['large-img']['name'])); } } } $destination = new Destination(["location" => $location, "price" => $price, "id_tour_operator" => $operator], $osef); $destinationsManager->create($destination); header("Location: ".$path."/index.php"); exit(); } } } } else { echo "zut"; } function prettyArray(array $nested_arrays): void { foreach ($nested_arrays as $key => $value) { if (gettype($value) !== 'array') { echo ('<li class="dump">' . $key . ' : ' . $value . '</li>'); } else { echo ('<ul class="dump">' . $key); prettyArray($value); echo ('</ul>'); } } } function prettyDump(array $nested_arrays): void { foreach ($nested_arrays as $key => $value) { switch (gettype($value)) { case 'array': /* ignore same level recursion */ if ($nested_arrays !== $value) { echo ('<details><summary style="color : tomato;' . 'font-weight : bold;">' . $key . '<span style="color : steelblue;' . 'font-weight : 100;"> (' . count($value) . ')</span>' . '</summary><ul style="font-size: 0.75rem;' . 'background-color: ghostwhite">'); prettyDump($value); echo ('</ul></details>'); } break; case 'object': echo ('<details><summary style="color : tomato;' . 'font-weight : bold;">' . $key . '<span style="color : steelblue;' . 'font-weight : 100;"> (' . gettype($value).' : '. get_class($value). ')</span>' . '</summary><ul style="font-size: 0.75rem;' . 'background-color: ghostwhite">'); prettyDump(get_object_vars($value)); echo ' <details open><summary style="font-weight : bold;' . 'color : plum">(methods)</summary><pre>'; prettyArray(get_class_methods($value)); echo '</details></pre>'; echo '</li></ul></details>'; break; case 'callable': case 'iterable': case 'resource': /* not supported yet */ break; default: /* scalar and NULL */ echo ('<li style="margin-left: 2rem;color: teal;' . 'background-color: white">' . '<span style="color : steelblue;font-weight : bold;">' . $key . '</span> : ' . ($value ?? '<span style="font-weight : bold;' . 'color : violet">NULL<span/>') . '</li>'); break; } } } prettyDump($GLOBALS);
true
56fec8d49c5777345875f69b1db2829a7409b18d
PHP
vladimirshornikov125/wp-downloader
/src/NoopCoreInstaller.php
UTF-8
3,955
2.828125
3
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
<?php # -*- coding: utf-8 -*- /* * This file is part of the wp-downloader package. * * (c) Giuseppe Mazzapica * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace WCM\WpDownloader; use Composer\Installer\InstallerInterface; use Composer\IO\IOInterface; use Composer\Package\PackageInterface; use Composer\Repository\InstalledRepositoryInterface; use InvalidArgumentException; /** * The plugin this class is part of has the only aim to download WordPress as a zip artifact, * without considering it a Composer package at all. * * This workflow is probably going to cause issues and conflicts if other packages require * WordPress as a Composer package. * * Since Composer does not have a public official API to remove packages "on the fly", the way we * could obtain that by using Composer script events are hackish and complicated. * The easiest solution I found is to replace the installer for 'wordpress-core' packages with * a custom installer (this class) that just does... nothing. * So Composer will think that WordPress package is installed and will not complain, * but nothing really happened. * * @author Giuseppe Mazzapica <giuseppe.mazzapica@gmail.com> * @package wp-downloader * @license http://opensource.org/licenses/MIT MIT */ class NoopCoreInstaller implements InstallerInterface { /** * @var IOInterface; */ private $io; /** * @param IOInterface $io */ public function __construct(IOInterface $io) { $this->io = $io; } /** * @inheritdoc */ public function supports($packageType) { return $packageType === 'wordpress-core'; } /** * Just return true, because we don't want Composer complain about WordPress not being installed. * * @param InstalledRepositoryInterface $repo repository in which to check * @param PackageInterface $package package instance * * @return bool */ public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package) { return true; } /** * Do nothing. Just inform user that we are skipping the package installation. * * @param InstalledRepositoryInterface $repo repository in which to check * @param PackageInterface $package package instance */ public function install(InstalledRepositoryInterface $repo, PackageInterface $package) { $name = $package->getName(); $this->io->write("\n<comment>Skipping installation of {$name}...</comment>\n"); } /** * Do nothing. Just inform user that we are skipping the package installation. * * @param InstalledRepositoryInterface $repo repository in which to check * @param PackageInterface $initial already installed package version * @param PackageInterface $target updated version * * @throws InvalidArgumentException if $initial package is not installed */ public function update( InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target ) { // do nothing $name = $target->getName(); $this->io->write("\n<comment>Skipping updating of {$name}...</comment>\n"); } /** * We don't support uninstall, at the moment. * * @param InstalledRepositoryInterface $repo repository in which to check * @param PackageInterface $package package instance */ public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package) { // do nothing } /** * We return an existing and valid path to prevent error output or installation abortion in case * Composer checks it exists. * * @param PackageInterface $package * @return string path */ public function getInstallPath(PackageInterface $package) { return getcwd(); } }
true
8af3f55560aef4f2014ef8673668144008591f52
PHP
seanphan05/Marketing_Campaigns_Report_Generating_Application
/frontend/php/editDetails/getCampaignDetailsAjax.php
UTF-8
1,650
2.71875
3
[]
no_license
<?php include('../config.php'); if(isset($_POST['year'] , $_POST['month'], $_POST['promo'])) { try { $year = $_POST['year']; $month = $_POST['month']; $promo = $_POST['promo']; $con = new PDO($dsn, $username, $password, $options); $sql = "SELECT `Months`, `Promo Name`, `Campaign Details` FROM campaign_details WHERE `Years`= ? AND `Months`= ? AND `Promo Name` = ? "; $stmt = $con->prepare($sql); $stmt->execute([$year, $month, $promo]); $result = $stmt->fetchAll(); } catch (PDOException $error) { echo $sql . "<br>" . $error->getMessage(); } } if (isset($_POST['year'] , $_POST['month'], $_POST['promo'])) { if ($result && $stmt->rowCount() > 0) { ?> <table id="current_camp_details_table"> <thead class="table_head"> <tr> <th style="text-align: left">Months</th> <th style="text-align: left">Promo Name</th> <th style="text-align: left">Campaign Details</th> </tr> </thead> <tbody> <?php foreach ($result as $row) { ?> <tr> <td style="text-align: left"><?php echo $row["Months"]; ?></td> <td style="text-align: left"><?php echo $row["Promo Name"]; ?></td> <td style="text-align: left"><?php echo $row["Campaign Details"]; ?></td> </tr> <?php } ?> </tbody> </table> <?php } else { ?> <p>No Result found!</p> <?php } ?> <?php } ?>
true
0d5e9727d4683f185be3ae42d43919517fe595b1
PHP
magnuslopes23/WC4U
/events.php
UTF-8
535
2.578125
3
[]
no_license
<?php require_once "server.php"; if(isset($_POST)){ $name=filter_input(INPUT_POST,'fullname'); $event=filter_input(INPUT_POST,'event'); $fees=filter_input(INPUT_POST,'fees'); $sql="INSERT INTO events (fullname, event, fees) VALUES ('$name','$event', '$fees')"; if(mysqli_query($db, $sql)){ echo "Record was updated successfully."; header("location: event.html"); } else { echo "ERROR: Could not able to execute $sql. " . mysqli_error($db); } mysqli_close($db); } ?>
true
810f78e9b057ec1892a4e90ad3280030d747f530
PHP
TarikAmine/Xoops-TManager
/class/tmanagertheme.php
UTF-8
5,121
2.609375
3
[]
no_license
<?php class TManagerTheme{ private $_instance = null; private $_obj = null; private $_css = array(); /** * constructor */ private function __construct(TManagerPreset $obj) { $this->_obj = $obj; //$this->_obj = new TManagerPreset(); $this->loadCss(); } public static function getInstance() { static $instance; if (!isset($instance)) { $helper = Xoops_Module_Helper::getHelper('tmanager'); $class = __CLASS__; $instance = new $class($helper->getHandlerPresets()->getDefault()); } return $instance; } public function addCssWidth($var, $value){ $value = explode('|', $value); $value[1] .= $value[0]?'%':'px'; $this->_css[$var]['width'] = $value[1]; } public function addCssHeight($var, $value){ $this->_css[$var]['height'] = $value.'px'; } public function addCssBg($var, $value){ $value = explode('|', $value); if(count($value)==1) $this->_css[$var]['background'] = $value[0]; elseif(count($value)==2 && $value[0]) $this->_css[$var]['background'] = 'transparent'; else $this->_css[$var]['background'] = $value[1]; } public function addCssAlign($var, $value){ $align = array('l' => 'left', 'c' => 'center', 'r' => 'right'); $value = $value; $this->_css[$var]['text-align'] = $align[$value]; } public function addCssTxt($var, $value){ $value = explode('|', $value); $this->_css[$var]['font-size'] = $value[0]!='inhert'?$value[0].'px':'inhert'; $this->_css[$var]['color'] = $value[1]; $this->_css[$var]['font-family'] = $value[2]; if($value[3]) $this->_css[$var]['font-weight'] = 'bold'; if($value[4]) $this->_css[$var]['font-style'] = 'italic'; if($value[5]) $this->_css[$var]['text-decoration'] = 'underline'; } public function addCssBox($var, $value, $type){ $value = explode('|', $value); $i = -1; $box = array('top', 'right', 'bot', 'left'); foreach($box as $b) if($value[++$i]!='auto') $this->_css[$var][$type][$b] = $value[$i].'px'; elseif($type == 'padding') $this->_css[$var][$type][$b] = '0'; elseif($b=='top' || $b=='bot') $this->_css[$var][$type][$b] = '0'; else $this->_css[$var][$type][$b] = 'auto'; } public function addCssPadding($var, $value){ $this->addCssBox($var, $value, 'padding'); } public function addCssMargin($var, $value){ $this->addCssBox($var, $value, 'margin'); } /* public function addCssBorder($var, $value){ $value = explode('|', $value); if($value[0]) $this->_css[$var]['border'] = $value[1].'px '.$value[2].' '.$value[3]; else $this->_css[$var] = array('border-top' => $value[1].'px '.$value[2].' '.$value[3], 'border-left' => $value[4].'px '.$value[5].' '.$value[6], 'border-right' => $value[7].'px '.$value[8].' '.$value[9], 'border-bottom' => $value[10].'px '.$value[11].' '.$value[12]); }*/ public function loadCss(){ $vars = $this->_obj->getVars(); $refs = array('g'=>'body', 'h1'=>'h1', 'h2'=>'h2', 'h3'=>'h3', 'link'=>'a', 'hlink'=>'a:hover', 'vlink'=>'a:visited', 'l'=>'#layout', 'h'=>'#header', 'n'=>'.navbar', 's'=>'.sidebar', 'm'=>'#content', 'f'=>'footer'); foreach($vars as $k => $v){ $index = explode('_', $k); if(count($index)==2){ $class = $index[0]; $method = 'addCss'.ucfirst($index[1]); if(is_callable(array($this, $method))){ $this->$method($refs[$class], $v['value']); } } } } public function getMenu(){ return '<div class="navbar '.($this->_obj->getVar('n_type')?'navbar-inverse':'').'" style="position: static;"> <div class="navbar-inner"> <div class="container"> <ul class="nav"> <li class="active"><a href="#">Home</a></li> <li><a href="#">Link</a></li> <li><a href="#">Link</a></li> </ul> <form class="navbar-search pull-right"> <input type="text" class="search-query" placeholder="Search"> </form> </div> </div><!-- /navbar-inner --> </div>'; } public function getPreHeader(){ return $this->_obj->getVar('n_pos')==1?$this->getMenu():''; } public function getPastHeader(){ return $this->_obj->getVar('n_pos')==2?$this->getMenu():''; } public function getStruct(){ $struct = explode('|', $this->_obj->getVar('l_struct')); return array( $struct[0]<6&&$struct[0]>=0?$struct[0]:4, $struct[1]<6&&$struct[1]>3?$struct[1]:4, 12-$struct[0]-$struct[1] ); } public function getSheet(){ $sheet=''; foreach($this->_css as $id => $lines){ $sheet.=$id.'{'; foreach($lines as $att => $val){ $sheet.=$att.':'; if(is_array($val)) foreach($val as $v) $sheet.=' '.$v; else $sheet.=$val; $sheet.=';'; } $sheet.= "}\n"; } return $sheet; } } ?>
true
e7d8f720e2594dafdbdc2a587433b715f043281b
PHP
alan707/gramofon
/api/application/core/MY_Input.php
UTF-8
980
2.921875
3
[]
no_license
<?php if ( ! defined('BASEPATH') ) exit('No direct script access allowed'); /** * Extending core CI Input class to add support for PUT vars. */ class MY_Input extends CI_Input { /** * Fetch an item from the POST array * * @access public * @param string * @param bool * @return string */ public function put( $index = NULL, $xss_clean = FALSE ) { $data = array(); // Parse PUT vars parse_str( file_get_contents( 'php://input' ), $data ); // Check if a field has been provided if ( $index === NULL && ! empty( $data ) ) { $put = array(); // Loop through the full PUT array and return it foreach ( array_keys( $data ) as $key ) { $put[$key] = $this->_fetch_from_array( $data, $key, $xss_clean ); } return $put; } return $this->_fetch_from_array( $data, $index, $xss_clean ); } }
true
51e6696e3e12f71d9f007864ca8c9eb5b947765f
PHP
saruhei/SamuraiCoding2012_Server
/yaguchi_stub/RailsFrontEndStub.php
UTF-8
1,016
2.59375
3
[]
no_license
<?php require_once 'RailsSql.php'; require_once 'HTTP/Request.php'; // settings begin // $game_engine_url = 'http://murooka.me/echo.php'; $game_engine_url = 'http://path/to/gameengine'; $on_server = false; // settings end $ai_urls = array(); if ($on_server) { foreach ($_REQUEST['ai_urls'] as $ai_url) { $ai_urls[] = $ai_url; } } else { $ai_urls[] = 'hoge'; $ai_urls[] = 'fuga'; $ai_urls[] = 'foo'; $ai_urls[] = 'bar'; } $sql =& RailsSql::getInstance(); $match_id = $sql->next_match_id(); $sql->insert_ai_urls($match_id, $ai_urls); $request =& new HTTP_Request($game_engine_url, array('useBrackets' => false)); $request->setMethod(HTTP_REQUEST_METHOD_POST); $request->addPostData('ai_urls[]', $ai_urls); if (!PEAR::isError($request->sendRequest())) { $code = $request->getResponseCode(); $header = $request->getResponseHeader(); $body = $request->getResponseBody(); print_r($code); print_r($header); print_r($body); } else { echo "Error!\n"; } ?>
true
d288709aad145d77e1ddaa16d3b24335678750f6
PHP
Pangil12/search-engine-project
/adminPage/includes/searchQueries.php
UTF-8
1,504
3.078125
3
[]
no_license
<?php include_once 'dbinfo.php'; echo "<table class='table table-striped table-hover'>"; echo "<thead class='bg-info'> <th scope='col'>Search Query</th> <th scope='col'>Number of Page Results</th> </thead> <tbody>\n"; class TableRows extends RecursiveIteratorIterator { public function __construct($it) { parent::__construct($it, self::LEAVES_ONLY); } public function current() { return "\n " . "<td>" . parent::current() . "</td>" . "\n"; } public function beginChildren() { echo "<tr>"; } public function endChildren() { echo "</tr>" . "\n"; } } try { $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $stmt = $conn->prepare("SELECT searchQuery, resultCount FROM UserSearch ORDER BY resultCount DESC"); $stmt->execute(); $result = $stmt->setFetchMode(PDO::FETCH_ASSOC); foreach (new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) { echo $v; } } catch (PDOException $e) { echo "Error: " . $e->getMessage(); } $conn = null; echo "</tbody>" . "\n" . "</table>" . "\n";
true
e6aeecbde27e6f159d16a3737e7332cccacdf71a
PHP
CoBeCTb-RooL/alma
/[models]/UserModel.php
UTF-8
3,645
2.75
3
[]
no_license
<?php class User { const TBL = 'users'; var $id , $surname , $name , $fathername , $password , $birthdate , $email , $phone , $salt , $registrationDate , $registrationIp , $lastActivity , $lastIp , $sex , $active; function init($arr) { if($arr) { $u = new User; $u->id = $arr['id']; $u->surname = $arr['surname']; $u->name = $arr['name']; $u->fathername = $arr['fathername']; $u->birthdate = $arr['birthdate']; $u->email = $arr['email']; $u->sex = $arr['sex']; $u->phone= $arr['phone']; $u->registrationIp = $arr['ip']; $u->lastIp = $arr['ip']; $u->password = $arr['password']; $u->salt = $arr['salt']; $u->active = $arr['active']; return $u; } } function get($id) { if($id = intval($id)) { $sql="SELECT * FROM users WHERE id=".$id; $qr=DB::query($sql); echo mysql_error(); if($attrs = mysql_fetch_array($qr, MYSQL_ASSOC)) { $user = User::init($attrs); } return $user; } } function insert() { $sql = " INSERT INTO `".self::TBL."` SET ".$this->innerAlterSql()." , active = 0 "; DB::query($sql); echo mysql_error(); //vd($sql); } function update() { $sql = " UPDATE `".self::TBL."` SET ".$this->innerAlterSql()." , active= '".($this->active ? 1 : 0)."' WHERE id=".$this->id." "; DB::query($sql); echo mysql_error(); //vd($sql); } function innerAlterSql() { $str=" surname = '".strPrepare($this->surname)."' , name = '".strPrepare($this->name)."' , fathername = '".strPrepare($this->fathername)."' , password = '".strPrepare($this->password)."' , birthdate = '".strPrepare($this->birthdate)."' , email = '".strPrepare($this->email)."' , phone= '".strPrepare($this->phone)."' , registrationDate = NOW() , registrationIp = '".strPrepare($_SERVER['REMOTE_ADDR'])."' , lastActivity = NOW() , lastIp = '".strPrepare($_SERVER['REMOTE_ADDR'])."' , sex = '".strPrepare($this->sex)."' , salt= '".strPrepare($this->salt)."'"; return $str; } /*function authenticate($email, $pass) { $sql="SELECT * FROM `".self::TBL."` WHERE email='".mysql_real_escape_string($email)."' AND password = '".mysql_real_escape_string($pass)."' AND active=1"; $qr=DB::query($sql); echo mysql_error(); $usr=mysql_fetch_array($qr, MYSQL_ASSOC); if($usr) { $_SESSION['user'] = array( 'id'=>$usr['id'], 'surname'=>$usr['surname'], 'name'=>$usr['name'], 'fathername'=>$usr['fathername'], 'email'=>$usr['email'], ); return true; } }*/ function getByEmailAndPassword($email, $password) { $sql="SELECT * FROM `".self::TBL."` WHERE email='".mysql_real_escape_string($email)."' AND password = '".mysql_real_escape_string($password)."' AND active=1"; //vd($sql); $qr=DB::query($sql); echo mysql_error(); $usr=mysql_fetch_array($qr, MYSQL_ASSOC); //vd($usr); return User::init($usr); } function emailExists($eml, $selfId) { $sql="SELECT id FROM `".self::TBL."` WHERE email = '".trim(mysql_real_escape_string($eml))."' ".(intval($selfId) ? " AND id != ".intval($selfId)."" : "").""; $qr=DB::query($sql); echo mysql_error(); return mysql_num_rows($qr) > 0; } function getBySalt($salt) { if($salt = strPrepare(trim($salt))) { $sql="SELECT * FROM `".self::TBL."` WHERE salt='".$salt."'"; $qr=DB::query($sql); echo mysql_error(); if($attrs = mysql_fetch_array($qr, MYSQL_ASSOC)) { $user = User::init($attrs); } return $user; } } } ?>
true
bfcd0c8e54888fa1830871cf8784b7c681c0834d
PHP
Tindata/WebApp
/scoreACT.php
UTF-8
4,829
2.78125
3
[ "MIT" ]
permissive
<?php $servername = ""; $username = ""; $password = ""; $dbname = ""; $name; $DSID; $url; $htmldescription; $region; //error_reporting(0); // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT * FROM datasetList WHERE score = 0"; $result = $conn->query($sql); $array = get_object_vars($result); if ($result->num_rows > 0) { // output data of each row while($row = $result->fetch_assoc()) { //var_dump($row); // echo "<br>"; $DSID = $row["DSID"]; $url = $row["url"]; $htmldescription = $row["htmldescription"]; $region = $row["region"]; $name = $row["name"]; if ($region == "ACT"){ // if ($name == "Traffic camera offences and fines") { $html = file_get_contents($url); if (!isset(explode("};", explode("var initialState = ", rtrim($html, " \t."))[1])[0])) { $notRlyJSON = explode("};", explode("var initialState = ", rtrim($html, " \t."))[1])[0]; // print_r(explode('"viewCount":', $notRlyJSON)); $views = explode("}", explode('"viewCount":', $notRlyJSON)[1])[0]; $downloads = explode(",", explode('"downloadCount":', $notRlyJSON)[1])[0]; $lastUpdated = explode('"', explode('"lastUpdatedAt":"', $notRlyJSON)[1])[0]; $dateCreated = explode('"', explode('"createdAt":"', $notRlyJSON)[1])[0]; $relatedJSON = explode(']', explode('relatedViews: ', $notRlyJSON)[1])[0]."]"; $isTabular = explode(',', explode('"isTabular":', $notRlyJSON)[1])[0]; // echo $views; $datetime1 = new DateTime($lastUpdated); $datetime2 = new DateTime(); $interval = $datetime1->diff($datetime2); $daysSinceUpdate = $interval->format('%r%a'); $datetime3 = new DateTime($dateCreated); $datetime4 = new DateTime(); $interval = $datetime3->diff($datetime4); $daysSinceCreation = $interval->format('%r%a'); //Calculate Score $finalScore = round(10 * ((10 * $downloads + $views)/($daysSinceCreation+1))/(1+($daysSinceUpdate/100))); echo "<br><br><br><br><br>".$name.":".$finalScore."<br><br><br><br>"; $sql1 = "UPDATE datasetList SET score = $finalScore WHERE DSID = $DSID;"; $result1 = $conn->query($sql1); } else { echo "NOT TABULAR"; } // } // if ($isTabular) { // // echo "IS A TABLE"; // $columnsJSON = explode(',"commentUrl"', explode('columns":', $notRlyJSON)[1])[0]; // $columnsArr = json_decode($columnsJSON, true); // foreach ($columnsArr as $key => $column) { // // echo $column["name"]; // // print_r($column); // // foreach ($column as $key1 => $value) { // // print_r($key1); // // echo ":"; // // print_r($value); // // echo "<br>"; // // } // // echo "<br><br>"; // } // //SHOW TABLE // } // else { // //LINK TO DATASET // } // // print_r(explode('columns":', $notRlyJSON)); // // foreach ($relatedArr as $key => $relatedSet) { // // foreach ($relatedSet as $key1 => $value) { // // print_r($key1); // // echo ":"; // // print_r($value); // // echo "<br>"; // // } // // } // // $relatedArr = json_decode($relatedJSON, true); // // foreach ($relatedArr as $key => $relatedSet) { // // foreach ($relatedSet as $key1 => $value) { // // print_r($key1); // // echo ":"; // // print_r($value); // // echo "<br>"; // // } // // } // // echo $relatedJSON; // // echo "<br>".$views."<br>".$downloads."<br>".$lastUpdated."<br>".$dateCreated; // // lastUpdatedAt } } } else { echo "Data set not found."; } $conn->close(); ?>
true
8de9f8c34af64f29f6c0c65e9f42d6897b141151
PHP
andersonSinaluisa/Employed
/ApiCompany/controllers/usuarioController.php
UTF-8
3,835
2.625
3
[]
no_license
<?php require_once('./class/conf/Persona.php'); require_once('./class/mov/Sesion.php'); require_once('./class/conf/Usuario.php'); require_once('./class/conf/Main.php'); require_once('./class/mov/Sesion.php'); require_once('./core/mainModel.php'); class UsuarioController { public function __construct() { } public function login($user, $pass) { $user = MainModel::clearString($user); $pass = MainModel::clearString($pass); $pass = MainModel::encryption($pass); /* comprueba los que los datos no esten vacíos */ if ($user != '' && $pass != '') { /* crea un obj usuario para hacer consulta */ $usuario = new Usuario(); $usuario->setData(null, $user, $user, $pass, null, null, null, null); $result = $usuario->getLogin(); /* si obtiene datos de la consulta */ if ($result->rowCount() > 0) { /* obtiene los datos para setearlo en ek obj usuario */ $dataUser = $result->fetch(PDO::FETCH_ASSOC); $usuario->setData1($dataUser); /* hace una consulta de persona*/ $resultPersona = new Persona(); $rpersona = $resultPersona->getPersona($usuario->getId_persona()); /* si obtiene datos */ if ($rpersona->rowCount() > 0) { $rowPersona = $rpersona->fetch(PDO::FETCH_ASSOC); $resultPersona->setData1($rowPersona); $mainconf = new Main(); $resultMain = $mainconf->getMain($usuario->getId_main()); if ($resultMain->rowCount() > 0) { $rowmain = $resultMain->fetch(PDO::FETCH_ASSOC); $mainconf->setData1($rowmain); /*crea los datos de sesion */ $mainModel = new MainModel(); $ip = $mainModel->getIpClient(); $token = md5(rand()); $sesion = new Sesion(); $sesion->setData(null, $usuario->getId_usuario(), $token, 1, $ip); /* guarda en la tabla de sesion */ $resultSesion = $sesion->save(); if ($resultSesion > 0) { $alert = [ 'id_usuario'=>$usuario->getId_usuario(), 'username'=>$user, 'nombres'=>$resultPersona->getNombres(), 'apellidos'=>$resultPersona->getApellidos(), 'id_rol'=>$usuario->getId_rol(), 'token'=>$sesion->getToken(), 'id_persona'=>$resultPersona->getId_persona(), 'id_main'=>$mainconf->getId(), 'id_empresa'=>$mainconf->getId_empresa() ]; } else { $alert = ['class' => 'danger', 'msj' => 'Error al iniciar Sesion']; } } else { $alert = ['class' => 'danger', 'msj' => 'Error al iniciar Main']; } } else { $alert = ['class' => 'danger', 'msj' => 'Error al iniciar Persona']; } } else { $alert = ['class' => 'danger', 'msj' => 'Usuario y/o contraseña incorrecta']; } } else { $alert = ['class' => 'danger', 'msj' => 'Completa todos los campos']; } return json_encode($alert,JSON_UNESCAPED_UNICODE); } }
true
92f0572b80cfb15377f40bee543bf180aba8f92f
PHP
jnahian/LV-BLOG
/app/models/Post.php
UTF-8
1,070
2.8125
3
[ "MIT" ]
permissive
<?php class Post extends Eloquent { /** * The database table used by the model * * @var string */ protected $table = 'posts'; /** * The unfillabel fields of the table * * @var array */ protected $guarded = ['approved']; /** * The rules for validating a post * * @var array */ public $rules = [ 'title' => 'required', 'content' => 'required', 'attachment' => 'required', 'tags' => 'required', ]; public $errors = []; /** * The validation of registering user * * @var function */ public function validate_post() { $validation = Validator::make($this->attributes, $this->rules); if ($validation->passes()) { return TRUE; } $this->errors = $validation->messages(); return FALSE; } /** * The tags associated to the post * * @return response */ public function tags() { return $this->belongsToMany('Tag'); } }
true
3d615ddfaf9bd96581032cf31c7cb8b973d30ca8
PHP
JulienSacher/ECF_Back_part_1
/src/DataFixtures/AppFixtures.php
UTF-8
4,365
2.8125
3
[]
no_license
<?php namespace App\DataFixtures; use Doctrine\Bundle\FixturesBundle\Fixture; use Doctrine\Persistence\ObjectManager; use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface; use App\Entity\User; use App\Entity\Project; use App\Entity\SchoolYear; use EasySlugger\Slugger; class AppFixtures extends Fixture { private $encoder; public function __construct(UserPasswordEncoderInterface $encoder) { $this->encoder = $encoder; } public function load(ObjectManager $manager) { // créer un utilisateur ayant un rôle admin $user = new User(); $user->setEmail('admin@example.com'); $user->setRoles('ROLE_ADMIN'); $user->setFirstname('Foo'); $user->setLastname('Foo'); // encoder le mot de passe $password = $this->encoder->encodePassword($user, 'motdepasse'); $user->setPassword($password); $manager->persist($user); // créer un générateur de fausses données, localisé pour le français $faker = \Faker\Factory::create('fr_FR'); // créer 60 students for ($i = 0; $i < 60; $i++) { // générer un prénom et un nom de famille $firstname = $faker->firstName; $lastname = $faker->lastName; // sluggifier le prénom et le nom de famille (enlever les majuscules et les accents) // et concaténer avec un nom de domaine de mail généré $email = Slugger::slugify($firstname).'.'.Slugger::slugify($lastname).'@'.$faker->safeEmailDomain; // créer un student avec les données générées $user = new User(); $user->setRoles('ROLE_STUDENT'); $user->setPassword($password); $user->setFirstname($firstname); $user->setLastname($lastname); $user->setEmail($email); $manager->persist($user); } // créer 5 teachers for ($i = 0; $i < 5; $i++) { // générer un prénom et un nom de famille $firstname = $faker->firstName; $lastname = $faker->lastName; // sluggifier le prénom et le nom de famille (enlever les majuscules et les accents) // et concaténer avec un nom de domaine de mail généré $email = Slugger::slugify($firstname).'.'.Slugger::slugify($lastname).'@'.$faker->safeEmailDomain; // créer un teacher avec les données générées $user = new User(); $user->setRoles('ROLE_TEACHER'); $user->setPassword($password); $user->setFirstname($firstname); $user->setLastname($lastname); $user->setEmail($email); $manager->persist($user); } // créer 15 client for ($i = 0; $i < 15; $i++) { // générer un prénom et un nom de famille $firstname = $faker->firstName; $lastname = $faker->lastName; // sluggifier le prénom et le nom de famille (enlever les majuscules et les accents) // et concaténer avec un nom de domaine de mail généré $email = Slugger::slugify($firstname).'.'.Slugger::slugify($lastname).'@'.$faker->safeEmailDomain; // créer un client avec les données générées $user = new User(); $user->setRoles('ROLE_CLIENT'); $user->setPassword($password); $user->setFirstname($firstname); $user->setLastname($lastname); $user->setEmail($email); $manager->persist($user); } // créer 3 school years for ($i = 0; $i < 3; $i++) { // générer un nom $name = $faker->word; // créer une schoolyear avec les données générées $schoolyear = new SchoolYear(); $schoolyear->setName($name); $manager->persist($schoolyear); } // créer 20 project for ($i = 0; $i < 20; $i++) { // générer un nom $name = $faker->word; // créer un project avec les données générées $project = new Project(); $project->setName($name); $manager->persist($project); } // sauvegarder le tout en BDD $manager->flush(); } }
true
2a9d6e36072c9b3169cfcc70f6bbf9804330e2ee
PHP
kidflash23/CST-236
/Milestone_1_Final_Project/Discount.php
UTF-8
2,629
3.21875
3
[]
no_license
<?php require_once 'database.php'; //This is the given code for the discount. We see that it has multiple discounted values for a quarter and halh class Discount { private $promotion; private $amount; private $percent; private $used; public function __construct() { $this->promotion = $promotion; } public function discountCalcPercentageAmount($promotion){ $this->promotion = $promotion; if($this->promotion == "Quarter"){ $this->percent = .25; echo "Congrats! You have offically saved up to 25% off the given purchased item"; return $this->percent; } elseif($this->promotion == "Fifty"){ $this->percent = .50; echo "Congrats! You have offically saved up to 50% off the given purchased item"; return $this->percent; } else{ return 0; } } public function discountedCalculatedDollarAmount($promotion){ $this->promotion = $promotion; if($this->promotion == "25"){ $this->percent = 25; $this->used = true; echo "Congrats. You have saved a total of $25 off the given order"; return $this->percent; } elseif($this->promotion == "50"){ $this->percent = 50; $this->used = true; echo "Congrats. You have saved a total of $50 off the given order"; return $this->percent; } else{ $this->used = false; return 0; } } public function userOnlyUse(){ $conn = new dataBase(); if($this->used == true){ $sql = "INSERT INTO coupon Used values .'$this->used'. where users.ID = userID"; if (mysqli_query($conn->getConnect(), $sql)) { $sql; } else { echo "Error updating record: " . mysqli_error($conn->getConnect()); } mysqli_close($conn->getConnect()); } else{ $sql = "INSERT INTO coupon Used values .'$this->used'. where users.ID = userID"; if (mysqli_query($conn->getConnect(), $sql)) { } else { echo "Error updating record: " . mysqli_error($conn->getConnect()); } mysqli_close($conn->getConnect()); } } }
true
f673c080219bda84ae1ce84cec9294fe48b658fc
PHP
randimays/codeup.dev
/php/db_connect.php
UTF-8
497
2.78125
3
[]
no_license
<?php // Use Sequel Pro to create a new database, user and password. Create a park_migration file that connects to the database and creates a table called national_parks. Populate the table with all national park information for the United States using a file called park_seeder. $dbc = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . "", DB_USER, DB_PASS); $dbc->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // echo $dbc->getAttribute(PDO::ATTR_CONNECTION_STATUS) . "\n";
true
84e6137a72713158432c3d159e79f740286d768b
PHP
yehster/oemrdoc
/Entities/RXNConUsage.php
UTF-8
674
2.578125
3
[]
no_license
<?php namespace library\doctrine\Entities; /** @Entity * @Table(name="dct_med_names_usage") */ class RXNConUsage { public function __construct($rxnconso) { $this->RXNCon=$rxnconso; $this->frequency=1; } /** * @Id * @Column(type="integer",name="id") * @GeneratedValue(strategy="AUTO") */ protected $id; /** * @OneToOne(targetEntity="RXNConcept", inversedBy="usage") * @JoinColumn(name="rxaui_id", referencedColumnName="RXAUI") */ protected $RXNCon; /** * @Column(type="integer") */ private $frequency; public function increment() { $this->frequency++; } } ?>
true
8c9a77faffe7726155ac302eb83563976f702230
PHP
3etechinns/DRCmobile-money-sms-process
/Controlleur/livreurprocess.php
UTF-8
2,019
2.71875
3
[]
no_license
<?php /** * Created by PhpStorm. * User: samy * Date: 4/6/17 * Time: 1:20 PM */ require_once '../Model/Livreur.php'; if( isset($_POST['details'])) { $data =null; $compt = null; $tableau = Livreur::afficherLivreur(); if ($tableau != null) { foreach ($tableau as $row) { $data=$data."<tr> <td>". $row->getIdLivreur()."</td> <td>".$row->getNomLivreur()."</td> <td>".$row->getNumtel()."</td> </tr>"; } } echo $data; } if(isset($_POST['mot'])) { $data = null; $compt = null; $tableaudist =Livreur::recherchelivreur($_POST['mot']); if ($tableaudist != null) { foreach ($tableaudist as $row) { $data=$data."<tr> <td>". $row->getIdLivreur()."</td> <td>".$row->getNomLivreur()."</td> <td>".$row->getNumtel()."</td> </tr>"; } echo $data; } } if(isset($_POST['ajout'])) { $livreur=new Livreur("",$_POST['nom'],$_POST['numtel'],""); if(Livreur::ajouterLivreur($livreur)) { echo "ajout reussi"; } else { echo "ajout non reussi"; } } if(isset($_POST['userJSON'])) { $json=$_POST['userJSON']; if(get_magic_quotes_gpc()) { $json=stripcslashes($json); } $data=json_decode($json); $a=array(); $b=array(); for($i=0; $i<count($data);$i++) { $tableau=Livreur::afficherLivreurParnumEtpass($data[$i]->loginUser,$data[$i]->passwordUser); $a=array(); $b=array(); if($tableau!=null) { foreach ($tableau as $item) { $b["id"] = $item->getIdlivreur(); $b["nom"]=$item->getNomlivreur(); $b["status"] = "yes"; array_push($a, $b); } } else { $b["status"] = "no"; array_push($a, $b); } } echo $_POST['loginUser'].$_POST['passwordUser']; }
true
906c17824606a5b73d8a8e05df9648e3ec88aca2
PHP
InspektorGadjet/FileSharing
/src/Project/Controllers/DeleteController.php
UTF-8
585
2.828125
3
[]
no_license
<?php namespace Project\Controllers; class DeleteController { private $fileManager; private $filesDataGateway; public function __construct(\PDO $pdo) { $this->fileManager = new \Project\Models\FileManager(); $this->filesDataGateway = new \Project\Models\FilesDataGateway($pdo); } public function delete(string $filename, string $directory, string $copyDirectory) { $file = $this->filesDataGateway->getFileByName($filename); $this->filesDataGateway->deleteFile($file->serverName); $this->fileManager->deleteFile($file, $directory, $copyDirectory); return; } }
true
148ce91e7703a87d2e6b4eb533647b6e973b7e98
PHP
L200170046/PWD
/MODUL 5/L200170046/barang.php
UTF-8
2,438
2.578125
3
[]
no_license
<html> <head><title>Data Penjualan</title></head> <?php $conn = mysqli_connect('localhost', 'root', '', 'penjualan'); ?> <body> <center> <h3>Masukan Data Penjualan:<h3> <table border='0' width='30%'> <form method='POST' action='barang.php'> <tr> <td width='25%'>Kode Barang</td> <td width='5%'>:</td> <td width='65%'><input type='text' name='kode_barang' size='10'></td></tr> <tr> <td width='25%'>Nama Barang</td> <td width='5%'>:</td> <td width='65%'><input type='text' name='nama_barang' size='30'></td></tr> <tr> <td width='25%'>Kode Gudang</td> <td width='5%'>:</td> <td width='65%'><input type='text' name='kode_gudang' size='10'></td></tr> </table> <input type='submit' value='Masukkan' name='submit'> </form> <?php error_reporting(E_ALL ^ E_NOTICE); $kode = $_POST['kode_barang']; $nama = $_POST['nama_barang']; $kode2 = $_POST['kode_gudang']; $submit = $_POST['submit']; $input = "insert into barang (kode_barang, nama_barang, kode_gudang) values ('$kode', '$nama', '$kode2')"; if($submit){ if($kode==''){ echo "</br>Kode tidak boleh kosong, diisi dulu"; }elseif($nama==''){ echo "</br>Nama tidak boleh kosong, diisi dulu"; }elseif($kode2==''){ echo "</br>Kode tidak boleh kosong, diisi dulu"; }else{ mysqli_query($conn, $input); echo'</br> Data berhasil dimasukkan'; } } ?> <hr> <table> <tr><td><h4><a href='gudang.php'> Gudang </a></td> <td></h4><h4><a href='barang.php'> Barang </a></h4></td></tr> </table> <h3>Data Penjualan</h3> <table border='1' width='50%'> <tr> <td align='center' width='20%'><b>Kode Barang</b></td> <td align='center' width='30%'><b>Nama Brang</b></td> <td align='center' width='20%'><b>Kode Gudang</b></td> <td align='center' width='30%'><b>Keterangan</b></td> </tr> <?php $cari = "select * from barang order by kode_barang"; $hasil_cari = mysqli_query($conn, $cari); while($data = mysqli_fetch_row($hasil_cari)){ echo" <tr> <td width='20%'>$data[0]</td> <td width='30%''>$data[1]</td> <td width='10%'>$data[2]</td> <td width='30%'><a href='ubahbarang.php?nim=".$data[0]."'> <input type='button' value='ubah' name='ubh'></a> <a href='hapusbarang.php?nim=".$data[0]."'> <input type='button' value='hapus' name='hps'></a></td> </tr>"; } ?> </table></center></body></html>
true
6b2b79dc5cadb1a576ac11789c178bf1e9274f54
PHP
Harrywithrian/WebServiceKlimatologi
/src/entitas/periode.php
UTF-8
1,524
2.78125
3
[]
no_license
<?php class periode { //variable kode private $kd_klimatologi; private $kd_klasifikasi; //koneksi db public function __construct($connect) { $this->connect = $connect; } //set tampil periode kelompok public function setTampilPeriode($kd_klasifikasi) { $this->kd_klasifikasi = $kd_klasifikasi; } //set tambah periode public function setPeriode($item, $kd_klasifikasi) { $this->kd_klimatologi = $item; $this->kd_klasifikasi = $kd_klasifikasi; } //tampil periode kelompok public function tampilPeriode() { $sql = "SELECT * FROM periode, klimatologi where periode.kd_klimatologi = klimatologi.kd_klimatologi AND periode.kd_klasifikasi = :kd_klasifikasi;"; try { //input $stmt = $this->connect->prepare($sql); $stmt->bindParam(':kd_klasifikasi', $this->kd_klasifikasi); //eksekusi $stmt->execute(); //output $result = $stmt->fetchAll(PDO::FETCH_OBJ); echo json_encode($result); } catch (PDOException $e) { echo '{ {"error": {"text": '.$e->getMessage().'} }'; } } //simpan periode public function tambahPeriode() { $sql = "INSERT INTO periode (kd_klasifikasi, kd_klimatologi) VALUES (:kd_klasifikasi, :kd_klimatologi);"; try { //proses $stmt = $this->connect->prepare($sql); $stmt->bindParam(':kd_klasifikasi', $this->kd_klasifikasi); $stmt->bindParam(':kd_klimatologi', $this->kd_klimatologi); $stmt->execute(); } catch (PDOException $e) { echo '{"error": {"text": '.$e->getMessage().'}}'; } } } ?>
true
4f9b265c5a63cb11d88759cb0139c34857cac514
PHP
libgraviton/compose-transpiler
/src/Replacer/ReplacerAbstract.php
UTF-8
567
2.71875
3
[]
no_license
<?php /** * replacer abstract */ namespace Graviton\ComposeTranspiler\Replacer; use Neunerlei\Arrays\Arrays; use Psr\Log\LoggerInterface; abstract class ReplacerAbstract { protected $logger; public function setLogger(LoggerInterface $logger) { $this->logger = $logger; } final public function replaceArray(array $content) { $this->init(); return Arrays::mapRecursive($content, \Closure::fromCallable([$this, 'replace'])); } abstract protected function init(); abstract public function replace($content); }
true
cbe0d0114c2861550f40b216966650e4758d277c
PHP
anytizer/cropnail.php
/bin/class.clis.inc.php
UTF-8
1,016
3.125
3
[ "MIT" ]
permissive
<?php namespace cli; function cli_2($argv = []) { #stop("Parameter 2"); switch ($argv[1]) { case "list": process_list(); break; case "report": process_report(); break; default: stop("Invalid selector: {$argv[1]}."); break; } } function cli_3($argv = []) { switch ($argv[1]) { case "size": process_size($argv[2]); break; default: stop("Unknown size"); break; } } function cli_4($argv = []) { #stop("Parameter 4"); $dimensions = explode("x", $argv[1]); if (count($dimensions) != 2) { stop("Error: Dimensions should be WIDTHxHEIGHT eg. 200x300."); } $x = (int)$dimensions[0]; $y = (int)$dimensions[1]; if (!is_int($x) || !is_int($y)) { stop("Error: Dimensions should be integers. {$x}, {$y}"); } $source = $argv[2]; $target = $argv[3]; resize($source, $target, $x, $y); }
true
4effa8239e92f7cae0aa4dd6514833ed59276553
PHP
zjq1227/lampOS
/database/migrations/2019_08_05_073905_create_brand_table.php
UTF-8
1,065
2.59375
3
[ "MIT" ]
permissive
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateBrandTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('brand', function (Blueprint $table) { $table->increments('id'); $table->integer('sid')->comment("商家的id"); $table->char('bname',64)->comment("品牌的名字"); $table->integer('number')->comment("品牌的序号"); $table->char('blogo',255)->comment("品牌logo"); $table->char('country',64)->comment("品牌国家"); $table->char('describe',255)->comment("品牌描述"); $table->enum('status',['1','2'])->comment("品牌状态1开启")->default("1"); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('brand'); } }
true
77ad73f9186cf70fde6e54ab10c476e66875c532
PHP
zentesty/DailyList
/Hello.php
UTF-8
1,578
2.53125
3
[]
no_license
<?php require_once "M3UFile.php"; /** * Created by PhpStorm. * User: martin-pierreroy * Date: 2018-10-03 * Time: 3:46 PM */ //echo @date('dmy') . "</br>" ; //$m3ufile = new M3UFile(); //$m3ufile->is_ready(); //echo @date_create(@date('dmy'))->modify('-15 days')->format('dmy'); //echo "</br>" ; // //$x = 0; //echo @date_create(@date('dmy'))->modify('-' . $x .' days')->format('dmy'); //echo "</br>" ; // //$a = []; //array_push($a, 10); //array_push($a, 20); //array_push($a, 30); //foreach($a as $entry){ // echo $entry . "</br>"; //} //$sub = "#EXTINF:-1,CA: BBC WORLD NEWS | HD"; //echo substr($sub, 0, 8) . "</br>"; //if(substr($sub, 0, 8) == "#EXTINF:"){ // echo "____YES_____" . "</br>"; // //} //echo substr($sub, 1, 8) . "</br>"; $ret = test_link("http://54.37.188.76:80/live/test1/test1/23642.ts"); if($ret){ echo $ret . " -- TRUE </br>"; } else { echo $ret . " -- FALSE </br>"; } $ret = test_link("http://1028107998.rsc.cdn77.org/ls-54548-2/index.m3u8"); if($ret){ echo $ret . " -- TRUE </br>"; } else { echo $ret . " -- FALSE </br>"; } $ret = test_link("http://54.37.188.76:80/live/new4tec/new4tec/23630.ts"); if($ret){ echo $ret . " -- TRUE </br>"; } else { echo $ret . " -- FALSE </br>"; } //http://1028107998.rsc.cdn77.org/ls-54548-2/index.m3u8 // FoxNews //http://54.37.188.76:80/live/new4tec/new4tec/23630.ts // E! function test_link($url){ ini_set('default_socket_timeout', 1); if(!$fp = @fopen($url, "r")) { return false; } else { fclose($fp); return true; } }
true
aef3cf6dfd7686be38777bc9c23a1c7ef7874cb2
PHP
Giildardo/Papeleria
/web/vistas/main.php
UTF-8
1,443
2.84375
3
[]
no_license
<?php require_once 'abstracta.php'; require_once 'inteface.php'; include '../conec.php'; /** * */ class Productos extends Operacion { public function Modificar($id,$nom,$pre,$exis,$des){ include '../conec.php'; echo "Soy el id v1:<br>"."$id"."<br>"; $collection->updateMany(['_id' => new \MongoDB\BSON\ObjectID($id)], ['$set' => ['nombre' => $nom]]); $collection->updateMany(['_id' => new \MongoDB\BSON\ObjectID($id)], ['$set' => ['precio_u' => $pre]]); $collection->updateMany(['_id' => new \MongoDB\BSON\ObjectID($id)], ['$set' => ['existencia' => $exis]]); $collection->updateMany(['_id' => new \MongoDB\BSON\ObjectID($id)], ['$set' => ['descripcion' => $des]]); } public function Eliminar($ids){ include '../conec.php'; $collection = $database->productos; //$collection->deleteMany(array('_id' => $id)); $collection->deleteOne( array( '_id' => new MongoDB \ BSON \ ObjectID($ids) ) ); } public function Insertar($n,$p,$e,$d){ include '../conec.php'; $document = array( 'nombre' => $n, 'precio_u' => $p, 'existencia' => $e, 'descripcion' => $d ); $collection->insertOne($document);//insertar } //Eliminar("5de446a4f598d82f3c1a746e"); public function Mostrar(){ } } $objeto = new Productos; //$objeto->Modificar("5ddc504068230000e9005b45","2",3.5,4,"5"); //$objeto->Eliminar("5ddae5f26501790418252624");
true
6701096e3c1637264ae5efd0c1a891249198f62f
PHP
waltersono/sigevendas.co.mz
/app/Http/Controllers/Auth/ProfileController.php
UTF-8
2,008
2.765625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers\Auth; use App\Http\Controllers\Controller; use Illuminate\Http\Request; use Illuminate\Support\Facades\Auth; use App\Models\User; use Hash; /** * Controller responsible for handling user profile managment * * @autor Walter Sono */ class ProfileController extends Controller { /** * Displays the profile managment page * * @return \Illuminate\Http\Response */ public function index(){ return view('auth.profile',['user' => Auth::user()]); } /** * Updates the user's name and email * * @param \Illuminate\Http\Request * @param \App\Models\User * @return \Illuminate\Http\Response */ public function updateInfo(Request $request, User $user){ $this->validate($request, [ 'name' => 'required', 'email' => 'required|unique:users,email,' . $user->id ]); $user->email = $request->email; $user->name = $request->name; $user->save(); session()->flash('success','Perfil actualizado com sucesso!'); return redirect()->back(); } /** * Updates the user's password * * @param \Illuminate\Http\Request * @param \App\Models\User * @return \Illuminate\Http\Response */ public function updatePassword(Request $request, User $user){ $this->validate($request, [ 'current_password' => 'required|min:8', 'new_password' => 'required|min:8|same:new_password_confirmation', 'new_password_confirmation' => 'required|min:8' ]); if(app('hash')->check($request->current_password, $user->password)){ $user->password = bcrypt($request->new_password); $user->save(); session()->flash('success','Palavra-passe actualizada com sucesso!'); }else{ session()->flash('warning','Palavra-passe actual nao coincide!'); } return redirect()->back(); } }
true
8fad11609c46d7e48c44813e8fc2c1310443b812
PHP
JakeNierop/Framework
/school/PHP/foreach.php
UTF-8
311
3.125
3
[]
no_license
<?php $data = array( "monday" => '3000kw', "tuesday" => '3200kw', "wednesday" => '3500kw', "thursday" => '3750kw', "friday" => '4000kw', "saturday" => '2800kw', "sunday" => '3400kw'); foreach($data as $key => $value){ echo "$key: $value <br>\n"; }
true
2f0777f51380d5fd58956c41e6bafcf97c7b8db5
PHP
sayanghosh93/phpLoginPage
/register.php
UTF-8
2,087
2.765625
3
[]
no_license
<?php $dbhost = 'localhost:3306'; $dbuser = 'root'; $dbpass = ''; $dbname= 'users'; $link = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname); if (!$link) { die('Connect Error (' . mysqli_connect_errno() . ') ' . mysqli_connect_error()); } echo 'Success... ' . mysqli_get_host_info($link) . "\n"; mysqli_close($link); /*$email=$_POST['email']; $password=$_POST['password']; $confirm_password=$_POST['confirm_password']; if(!empty($email) && !empty($password) && !empty($confirm_password)){ if($password==$confirm_password){ echo 'Registration Successfull'; } } else{ echo 'Please enter email and password'; } $dbhost = 'localhost:3306'; $dbuser = 'root'; $dbpass = ''; if(! get_magic_quotes_gpc() ) { $emp_name = addslashes ($_POST['emp_name']); $emp_address = addslashes ($_POST['emp_address']); }else { $emp_name = $_POST['emp_name']; $emp_address = $_POST['emp_address']; } $conn=mysql_connect($dbhost, $dbuser, $dbpass); if(!$conn){ die("Unable to connect".mysql_error()); } else{ echo "Connection Successfull"; } $sql="INSERT INTO users_table "."(email,password) "."VALUES ($email,$password)"; mysql_select_db('users'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not enter data: ' . mysql_error()); } echo "Entered data successfully\n"; mysql_close($conn);*/ ?> <html> <head> <title>Register Below</title> <link rel="stylesheet" type="text/css" href="css/style.css" /> <link href="https://fonts.googleapis.com/css?family=Comfortaa" rel="stylesheet"> </head> <body> <div class="header"> <a href="index.php">Your app name</a> </div> <h2>Register</h2> <span>or <a href="login.php">Login here</a></span> <form action="register.php" method="POST"> <input type="email" placeholder="Email" name="email" /> <input type="password" placeholder="Password" name="password" /> <input type="password" placeholder="Confirm Password" name="confirm_password" /> <input type="submit" /> </form> </body> </html>
true
34a026ee629610e6a20af986e87edd7e08465a42
PHP
didinahmadi/edholcomb-laravel
/app/Http/Controllers/API/TeamController.php
UTF-8
1,587
2.515625
3
[]
no_license
<?php namespace App\Http\Controllers\API; use App\Http\Controllers\Controller; use App\Http\Resources\TeamResource; use Illuminate\Http\Request; use App\Models\Team; use Illuminate\Support\Facades\DB; class TeamController extends Controller { public function index(Request $request) { return TeamResource::collection(Team::all()); } public function store(Request $request) { $request->validate([ 'name' => 'required|string|max:100' ]); try { $team = new Team; $team->fill($request->all()); $team->save(); return response()->json([ 'data' => new TeamResource($team) ]); } catch (\Exception $e) { throw $e; } } public function destroy(Request $request, $id) { try { $team = Team::findOrFail($id); $team->delete(); return response()->json([ 'data' => [ 'id' => $id ] ]); } catch (\Exception $e) { throw $e; } } public function update(Request $request, $id) { $request->validate([ 'name' => 'required|string|max:100' ]); $team = Team::findOrFail($id); try { $team->fill($request->all()); $team->save(); return response()->json([ 'data' => new TeamResource($team) ]); } catch (\Exception $e) { throw $e; } } }
true
f5ace5f3ed7acf233628aa43a1fd4064d2b141aa
PHP
danishtechverx/danishtest
/wp-content/themes/adventure-tours/woocommerce/includes/reports/WC_Report_ADT_Base.php
UTF-8
3,704
2.65625
3
[]
no_license
<?php /** * Base class for classes related to tour reports functionality. * * @author Themedelight * @package Themedelight/AdventureTours * @version 2.2.7 */ class WC_Report_ADT_Base extends WC_Admin_Report { public $default_range = 'last_month'; public $allow_any_order_status = false; /** * Get the legend for the main chart sidebar. * * @return array */ public function get_chart_legend() { return array(); } public function get_current_range_code() { $result = ! empty( $_GET['range'] ) ? sanitize_text_field( $_GET['range'] ) : null; if ( $result && ! in_array( $result, array( 'custom', 'year', 'last_month', 'month', '7day' ) ) ) { $current_range = null; } return $result ? $result : $this->default_range; } public function get_allowed_order_statuses() { return $this->allow_any_order_status ? array() : array( 'completed', 'processing', 'on-hold' ); } /** * Output the report. */ public function output_report() { $this->load_assets(); $ranges = array( 'year' => __( 'Year', 'adventure-tours' ), 'last_month' => __( 'Last Month', 'adventure-tours' ), 'month' => __( 'This Month', 'adventure-tours' ), '7day' => __( '7 Day', 'adventure-tours' ), ); $current_range = $this->get_current_range_code(); $this->calculate_current_range( $current_range ); include dirname( __FILE__ ) . '/base-view.php'; } /** * Loads assets related to the tour reports functionality. * * @return void */ protected function load_assets() { wp_enqueue_script( 'at_tour_reports', get_template_directory_uri() . '/assets/admin/WooCommerceTourReports.js' ); wp_localize_script( 'at_tour_reports', '_WooCommerceTourReportsCfg', array( 'purge_cache_btn_text' => __( 'Purge Cache', 'adventure-tours' ), )); } /** * Returns current value for date_filter_mode property. * * @return string */ public function get_date_filter_mode() { static $value; if ( null === $value ) { $value = isset( $_REQUEST['date_filter_mode'] ) ? $_REQUEST['date_filter_mode'] : ''; $modes = $this->get_date_filter_mode_list( false ); if ( ! $modes ) { $value = ''; } elseif ( ! $value || ! in_array( $value, $modes ) ) { $value = $modes[0]; } } return $value; } /** * Returns options list for date_filter_mode property. * * @param boolean $with_labels * @return assoc|array */ public function get_date_filter_mode_list( $with_labels = true ) { static $list; if ( null === $list ) { $list = array( 'order_date' => __( 'Order Date', 'adventure-tours' ), 'tour_date' => __( 'Tour Date', 'adventure-tours' ), ); } return $with_labels ? $list : array_keys( $list ); } /** * Renders selector for date_filter_mode. * * @return string */ public function render_date_filter_mode_selector() { $modes = $this->get_date_filter_mode_list(); if ( ! $modes ) { return ''; } $selected = $this->get_date_filter_mode(); $select_html = '<select name="date_filter_mode" style="line-height:26px;height:26px;">'; foreach ( $modes as $key => $value) { $select_html .= sprintf( '<option value="%s"%s>%s</option>', esc_html( $key ), $key == $selected ? ' selected="selected"' : '', esc_html( $value ) ); } $select_html .= '</select>'; return sprintf( '<div style="padding-left:10px">%s %s</div>', esc_html__( 'Filter by', 'adventure-tours' ), $select_html ); } public function render_order_id_link( $order_id, $to_new_tab = true ) { return $order_id > 0 ? sprintf( '<a href="%s"%s>#%s</a>', admin_url( 'post.php?post=' . $order_id . '&action=edit' ), $to_new_tab ? ' target="_blank"' : '', $order_id ) : ''; } }
true
aa8986b72eb6c83159b3ba5df947d74f606e601a
PHP
tugtitu/DATNCT
/server/updateTable.php
UTF-8
2,318
2.75
3
[]
no_license
<?php include "connect.php"; if (isset($_GET['name']) && isset($_GET['idArea']) && isset($_GET['id']) && isset($_GET['is'])) { $table_name = $_GET['name']; $idArea = $_GET['idArea']; $is = $_GET['is']; $id = $_GET['id']; $result = -1; switch ($is) { case '0': $result = insertTable($table_name, $idArea); break; case '1': $result = updateTable($id, $table_name, $idArea); break; case '2': $result = deleteTable($id); break; } result($result); } mysqli_close($con); function result($result) { $success="success"; $message = "message"; echo json_encode(array($success=>$result,$message=>"Success")); } function insertTable($table_name, $idArea) { global $con; $data = "INSERT INTO `table_f`(`id`, `table_name`, `area_id`, `status`) VALUES (null, '$table_name', '$idArea', 0)"; return mysqli_query($con, $data) ? 3 : -1; } function updateTable($id, $table_name, $idArea) { global $con; $data = " UPDATE `table_f` SET `table_name` = '$table_name', `area_id` = '$idArea' WHERE `id` = '$id' "; return mysqli_query($con, $data) ? 1 : -1; } function deleteTable($id) { global $con; $query; $select_table_by_bill_not_payment = " SELECT * FROM `bill` WHERE `bill`.`table_id` = '$id' && `bill`.`status` = '0' "; $data1 = mysqli_query($con, $select_table_by_bill_not_payment); foreach ($data1 as $row) { if (!is_null($row)) { return 0; } } $select_table_by_bill_paymented = " SELECT * FROM `bill` WHERE `bill`.`table_id` = '$id' && `bill`.`status` = '1' "; $data2 = mysqli_query($con, $select_table_by_bill_paymented); foreach ($data2 as $row) { if (!is_null($row)) { $query = "UPDATE `table_f` SET `status` = '-99' WHERE `id` = '$id'"; return mysqli_query($con, $query) ? 1 : -1; } } $query = "DELETE FROM `table_f` WHERE `id` = '$id'"; return mysqli_query($con, $query) ? 2 : -1; } ?>
true
3a1d5e0cda51d33b8033a4062d250ca608b034aa
PHP
Correcter/targetApi
/Resource/Audience/RemarketingPricelist.php
UTF-8
925
2.515625
3
[]
no_license
<?php namespace TargetApi\Resource\Audience; use TargetApi\Model\Audiences\RemarketingPricelist as RemarketingPricelistModel; use TargetApi\Resource\AbstaractResource; /** * @author Vitaliy Dergunov (<correcter@inbox.ru>) */ class RemarketingPricelist extends AbstaractResource { /** * @return object|\TargetApi\Resource\string */ public function get(int $id) { return $this->call('get', ['id' => $id]); } /** * @param int $id * @param RemarketingPricelistModel $model * * @return object|\TargetApi\Resource\string */ public function post(int $id, RemarketingPricelistModel $model) { return $this->call('post', ['id' => $id], $model); } /** * @param int $id * * @return object|\TargetApi\Resource\string */ public function delete(int $id) { return $this->call('delete', ['id' => $id]); } }
true
7cc36a90cb9671862491606d3bf3b3afc7696c3c
PHP
eugene-sukhodolskiy/rating.engine
/fw/kernel/Events.php
UTF-8
1,087
3
3
[]
no_license
<?php namespace Kernel; class Events{ private static $events; private static $waste; public static function add($eventname, $callback){ if(!isset(self::$events[$eventname])){ self::$events[$eventname] = [$callback]; return true; } self::$events[$eventname][] = $callback; return true; } public static function register($eventname, $args){ self::$waste = !self::$waste ? [$eventname => $args] : array_merge(self::$waste, [$eventname => $args]); if(!isset(self::$events[$eventname])) return false; foreach(self::$events[$eventname] as $item => $callback){ $callback($args); } return true; } public static function getList(){ $events = []; foreach(self::$events as $name => $callback){ $events[$name] = count(self::$events[$name]); } return $events; } public static function getWaste(){ return self::$waste; } }
true
4f4524a2f9b5c6b685d795e1eca4639355abd1b5
PHP
msawatzky75/WEBD-2006-A5
/index.php
UTF-8
890
2.859375
3
[]
no_license
<?php require('connect.php'); $query = "SELECT * FROM posts ORDER BY id DESC"; $statement = $db->prepare($query); // Returns a PDOStatement object. $statement->execute(); // The query is now executed. ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My Blog</title> <link rel="stylesheet" href="styles.css"> </head> <body> <section id="container"> <?php require 'header.php'; ?> <?php if (isset($_GET['error'])) : ?> <?php if ($_GET['error'] == 'insert') : ?> <h4 id="errorMessage">There was an error creating the post.</h4> <?php elseif ($_GET['error'] == 'update') : ?> <h4 id="errorMessage">There was an error updating the post.</h4> <?php else : ?> <h4 id="errorMessage">Other error.</h4> <?php endif; ?> <?php endif; ?> <?php require 'posts.php'; ?> </section> </body> </html>
true
f87e3cb7a865c755c9e8910a163423c978f7114b
PHP
Danielle-Kensy/PHP-Lessons
/aula9tarde/util/validacao.class.php
UTF-8
183
2.96875
3
[ "MIT" ]
permissive
<?php class Validacao { public static function validarNome($valor): bool { $expressao = "/^[a-zA-z ]{2,50}$/"; return preg_match($expressao, $valor); } }
true
91d902d3686ec11309599a4dc6dba582c2483ccf
PHP
ShimpeiMatsuda/e-learning
/contact_me.php
UTF-8
1,985
2.609375
3
[]
no_license
<?php require_once 'connect.php'; require_once 'header.php'; if(isset($_POST['send'])){ $name=$_POST['name'].$_POST['lastname']; $email=$_POST['email']; $number=$_POST['phone']; $message=$_POST['message']; $date=$_POST['date']; if($name==""or $email=="" or $number=="" or $message=="" or$date==""){ echo "<p class='alert alert-danger'>You shuold write all forms</p>"; }else{ $sql= "INSERT INTO contacttbl(name,email,number,message,date) VALUES('$name', '$email', '$number', '$message','$date')"; $con->query($sql); echo "<p class='alert alert-success'>Make it</p>"; } } ?> <body> <form action="" method="POST"> <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <div class="row"> <div class="col-md-6"> <label for="name">First Name:</label><br> <input type="text" class="form-control" name="name" id="name"> </div> <div class="col-md-6"> <label for="lastname">Last Name:</label><br> <input type="text" class="form-control" name="lastname" id="lastname"> </div> </div> <br> <div class="row"> <div class="col-md-6"> <label for="email">Email:</label><br> <input type="email" class="form-control" name="email" id="email"> </div> <div class="col-md-6"> <label for="phone">Phone Number:</label><br> <input type="text" class="form-control" name="phone" id="phone"> </div> </div> <br> <div class="row"> <div class="col-md-12"> <label for="message">Your Message:</label><br> <textarea class="form-control" name="message" id="message" rows="5"></textarea><br> </div> <div class="col-md-6"> <label for="exampleInputEmail1">Date Added</label> <input class="datepicker" data-date-format="yyyy-mm-dd" type="text" name="date"> </div> </div> <br> <button class="btn btn-xm btn-primary" name="send">Send</button> </div> </div> </div> </form> </body> <?php require_once 'footer.php'; ?>
true
0c2bfa797379e71779047b1d309f5afb4b211903
PHP
yaseralshikh/talent_project
/app/Http/Livewire/Students.php
UTF-8
3,396
2.515625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Livewire; use Livewire\Component; use App\Models\Student; use App\Models\School; use Livewire\WithPagination; use App\Exports\StudentsExport; use Maatwebsite\Excel\Facades\Excel; class Students extends Component { use WithPagination; public $sortField = 'name'; public $sortAsc = true; public $search = ''; public $school_id = ''; public $sudent_id = ''; public $sudent_name; public $sudent_class; public $sudent_stage; public $sudent_mobile; public $sudent_status; public $modalFormVisible = false; public $changeStatus= ''; public function changeStatus($status) { $this->changeStatus = $status; } public function sortBy($field) { if ($this->sortField === $field) { $this->sortAsc = ! $this->sortAsc; } else { $this->sortAsc = true; } $this->sortField = $field; } public function showUpdateModal($id) { $this->modalFormReset(); $this->modalFormVisible = true; $this->sudent_id = $id; $this->loadModalData(); } public function loadModalData() { $data = Student::find($this->sudent_id); $this->school_id = $data->school_id; $this->sudent_name = $data->name; $this->sudent_class = $data->class; $this->sudent_stage = $data->stage; $this->sudent_mobile = $data->mobile; $this->sudent_status = $data->status; } public function modelData() { $data = [ 'school_id' => $this->school_id, 'mobile' => $this->sudent_mobile, 'status' => $this->sudent_status, ]; return $data; } public function rules() { return [ 'school_id' => ['required'], 'sudent_mobile' => ['numeric', 'digits_between:10,12'], 'sudent_status' => ['required'], ]; } public function modalFormReset() { $this->school_id = null; $this->sudent_mobile = null; $this->sudent_status = null; $this->resetValidation(); } public function update() { $this->validate(); $student = Student::where('id', $this->sudent_id)->first(); $student->update($this->modelData()); $this->modalFormVisible = false; $this->alert('success', 'تم حفظ البيانات', [ 'position' => 'center', 'timer' => 3000, 'toast' => true, 'text' => null, 'showCancelButton' => false, 'showConfirmButton' => false ]); } public function export() { return Excel::download(new StudentsExport, 'students.xlsx'); } public function render() { $activeStud = Student::where('status', true)->count(); $disActiveStud = Student::where('status', false)->count(); $schools = School::orderBy('name')->get(); $students = Student::search($this->search)->Where('status', 'like','%'.$this->changeStatus.'%')->orderBy($this->sortField, $this->sortAsc ? 'asc' : 'desc')->paginate(50); return view('livewire.students', [ 'schools' => $schools, 'students' => $students, 'activeStud' => $activeStud, 'disActiveStud' => $disActiveStud ]); } }
true
c97db9fe14d768a9a8e630dd2ff6f3eeef5a6261
PHP
66ru/gpor-contrib
/_lib/ezcomponents-2009.2/Document/src/converters/element_visitor/docbook/odt/text_processor.php
UTF-8
5,904
2.828125
3
[ "BSD-3-Clause" ]
permissive
<?php /** * File containing the ezcDocumentOdtTextProcessor class. * * @package Document * @version 1.3 * @copyright Copyright (C) 2005-2009 eZ Systems AS. All rights reserved. * @license http://ez.no/licenses/new_bsd New BSD License * @access private */ /** * Processes text nodes with significant whitespaces. * * An instance of this class is used to process DOMText nodes with significant * whitespaces (such as literallayout). * * @package Document * @access private * @version 1.3 */ class ezcDocumentOdtTextProcessor { /** * Checks if whitespaces need additional processing and returns the * corresponding DOMText for the ODT. * * This method checks if the given $textNode is descendant of a * <literallayout /> tag. In this case, whitespaces are processed according * to the ODT specs: * * - More than 2 simple spaces are replaced by a single space and <text:s * /> with the text:c attribute set to the number of spaces - 1. * - One or more tabs / line breaks are replaced by a <text:tab/> / * <text:line-break/> tag, with the text:c attribute set to the number of * whitespaces replaced. * * @param DOMText $textNode * @param DOMElement $newRoot * @return array(DOMNode) */ public function processText( DOMText $textNode, DOMElement $newRoot ) { $parent = $this->getParent( $textNode ); if ( strpos( $parent->getLocationId(), '/literallayout' ) === false ) { return array( new DOMText( $textNode->data ) ); } return $this->processSpaces( $textNode, $newRoot ); } /** * Processes whitespaces in $textNode and returns a fragment for the ODT. * * Processes whitespaces in $textNode according to the rules described at * {@link processText()}. Returns a new DOMDocumentFragment, containing the * processed nodes. * * @param DOMText $textNode * @param DOMElement $newRoot * @return array(DOMNode) */ protected function processSpaces( DOMText $textNode, DOMElement $newRoot ) { $res = array(); // Match more than 2 spaces and tabs and line breaks preg_match_all( '((?: ){2,}|\\t+|\\n+)', $textNode->data, $matches, PREG_OFFSET_CAPTURE ); $startOffset = 0; foreach ( $matches[0] as $match ) { $matchType = $this->getMatchType( $match[0] ); $matchLength = iconv_strlen( $match[0] ); // Append text prepending the current match $res[] = new DOMText( iconv_substr( $textNode->data, $startOffset, $match[1] - $startOffset ) // Append 1 normal space, if spaces matched (ODT specs) . ( $matchType === 's' ? ' ' : '' ) ); $res = array_merge( $res, $this->repeatSpace( $matchType, $matchLength, $newRoot ) ); $startOffset = $match[1] + $matchLength; } // Append rest of the text after the last match if ( $startOffset < iconv_strlen( $textNode->data ) ) { $res[] = new DOMText( iconv_substr( $textNode->data, $startOffset ) ); } return $res; } /** * Generates whitespace elements. * * Retruns an array of DOMElement objects, representing $length number of * whitespaces of type $spaceType. * * @param string $spaceType * @param int $length * @param DOMElement $root * @return array(DOMNode) */ protected function repeatSpace( $spaceType, $length, DOMElement $root ) { $spaces = array(); if ( $spaceType === 's' ) { // Simple spaces use the count attribute $spaceElement = $root->ownerDocument->createElementNS( ezcDocumentOdt::NS_ODT_TEXT, "text:{$spaceType}" ); $spaceElement->setAttributeNS( ezcDocumentOdt::NS_ODT_TEXT, 'text:c', // For normal spaces, a single one is kept in tact (ODT specs) $length - 1 ); $spaces[] = $spaceElement; } else { // Tabs and new-lines are simply repeated for ( $i = 0; $i < $length; ++$i ) { $spaces[] = $root->ownerDocument->createElementNS( ezcDocumentOdt::NS_ODT_TEXT, "text:{$spaceType}" ); } } return $spaces; } /** * Returns what type of whitespace was matched. * * Returns a string indicating what type of whitespaces has been matched. * This string is also the name of the text:* tag used to reflect the * whitespace in ODT: * * - 's' for spaces * - 'tab' for tabs * - 'line-break' for line breaks * * @param string $string * @return string */ protected function getMatchType( $string ) { switch ( iconv_substr( $string, 0, 1 ) ) { case ' ': return 's'; case "\t": return 'tab'; case "\n": return 'line-break'; } } /** * Returns the ancestor DOMElement for $node. * * Returns the next ancestor DOMElement for $node. * * @param DOMNode $node * @return DOMElement */ protected function getParent( DOMNode $node ) { if ( $node->parentNode->nodeType === XML_ELEMENT_NODE ) { return $node->parentNode; } return $this->getParent( $node ); } } ?>
true
7dabd2cbc53b08c252f1d30fdb303d11f059dc5a
PHP
vivekkrishna/Smackron
/genderhint.php
UTF-8
3,089
2.546875
3
[]
no_license
<html> <head> </head> <body> <?php // Fill up array with names session_start(); // Fill up array with names @$con= mysql_connect("localhost","root",""); //mysql_select_db('employee'); //$rs= mysql_query("select * from emp"); $q1=$_GET["q1"]; if($q1=="any"){ $x=1; }else{ $x="gender"."="."'".$q1."'";} $rs= mysql_db_query("smackron","select * from user where select1='$_SESSION[select1]' && color='$_SESSION[color]' && believegod='$_SESSION[believegod]' && select2='$_SESSION[select2]' && wannabe='$_SESSION[wannabe]' && color='$_SESSION[color]' && likemost='$_SESSION[likemost]' && ifrich='$_SESSION[ifrich]' && lifewannabe='$_SESSION[lifewannabe]' && urdream='$_SESSION[urdream]' && urhobby='$_SESSION[urhobby]' && $x"); //var_dump($rs); //echo"no of fields=". mysql_num_fields($rs)."<br>"; //echo "no of columns=". mysql_num_rows($rs)."<br>"; //$row= mysql_fetch_array($rs); //$row= mysql_fetch_array($rs,MYSQL_NUM); //$row= mysql_fetch_array($rs,MYSQL_ASSOC); //$row= mysql_fetch_array($rs,MYSQL_BOTH); //$row= mysql_fetch_row($rs); //$row= mysql_fetch_assoc($rs); //print_r($row); //$row= mysql_fetch_object($rs); //echo $row->empno."--".$row->ename."--".$row->sal; //echo "<table border=1 align=center width=55% style=font-family: verdana;font-size:22px>"; //echo"<caption>employee details</caption>"; //echo "<tr><th>emp no</th><th>emp name</th><th>salary</th></tr>"; @mysql_data_seek($rs,4); while($row= @mysql_fetch_row($rs)) { //echo"<tr>"; //echo"<td>".$row[0]."</td>"; $a[]=$row[1]; $b[]=$row[5]; $c[]=$row[6]; $d[]=$row[7]; $e[]=$row[8]; $f[]=$row[10]; $g[]=$row[11]; //echo"<td>".$row[2]."</td>"; //echo"</tr>"; } //get the q parameter from URL //lookup all hints from array if length of q>0 if ($q1) { $hint=""; for($i=0; $i<count($a); $i++) { if (1) { echo "<table><tr>"; if ($hint=="") { $hint="<table><tr><td width=150px align=center>".$a[$i]."</td><td width=50px align=center>".$b[$i]."</td><td width=100px align=center>".$c[$i]."</td><td width=150px align=center>".$d[$i]."</td><td width=150px align=center>".$e[$i]."</td><td width=70px align=center>".$f[$i]."</td><td width=70px align=center>".$g[$i]."</td><td width=150px align=center>".a."</td></tr></table>"; } else { $hint=$hint." <br/> <table><tr><td width=150px align=center>".$a[$i]."</td><td width=50px align=center>".$b[$i]."</td><td width=100px align=center>".$c[$i]."</td><td width=150px align=center>".$d[$i]."</td><td width=150px align=center>".$e[$i]."</td><td width=70px align=center>".$f[$i]."</td><td width=70px align=center>".$g[$i]."</td><td width=150px align=center>". a."</td></tr></table>"; } echo "</tr>"; } }echo "</table>"; } // Set output to "no suggestion" if no hint were found // or to the correct values if ($hint == "") { $response="no matches found"; } else { $response=$hint; } //output the response echo $response; @mysql_free_result($rs); mysql_close($con); ?> </body> </html>
true
50706f9d9b9dcd02e08681f926b10ecb81bbf0f2
PHP
ixvil/Symfony.Fit
/src/Service/Sberbank/Client.php
UTF-8
1,526
2.6875
3
[]
no_license
<?php /** * Created by PhpStorm. * User: ixvil * Date: 01/07/2018 * Time: 12:33 */ namespace App\Service\Sberbank; use App\Service\Sberbank\Commands\Command; use GuzzleHttp\ClientInterface; use GuzzleHttp\Exception\GuzzleException; class Client { /** * @var ClientInterface */ private $client; /** @var string */ private $bankUrl; /** @var string */ private $login; /** @var string */ private $password; /** * Client constructor. * @param ClientInterface $client */ public function __construct( ClientInterface $client ) { $this->client = $client; $this->login = getenv('SBERBANK_LOGIN'); $this->password = getenv('SBERBANK_PASSWORD'); $this->bankUrl = getenv('SBERBANK_URL'); } /** * @param Command $command * @return array */ public function execute(Command $command): array { try { $response = $this->client->request( $command->getMethod(), $this->bankUrl . $command->getPath(), [ 'form_params' => $command->getData() + [ 'userName' => $this->login, 'password' => $this->password ] ] ); } catch (GuzzleException $e) { return [ 'error' => $e->getMessage() ]; } return $command->prepareAnswer($response); } }
true
09072e4b7bc263c1b74dc829e78839d0ae1be564
PHP
chrisdjsam/smartapp_server_yii
/Neato/protected/models/user/DeviceDetails.php
UTF-8
610
2.640625
3
[]
no_license
<?php Yii::import('application.models._base.BaseDeviceDetails'); /** * User class * */ class DeviceDetails extends BaseDeviceDetails { /** * Returns the static model of the specified AR class. * @param string $className active record class name. * @return DeviceDetails the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } /** * Check for users having this device details * @return boolean */ public function doesUserAssociationExist(){ if($this->userDevices){ return true; } return false; } }
true
6bd439d0ee911e7401766b092d431681d070f4d3
PHP
AboElmagd01/php2
/login.php
UTF-8
1,005
2.53125
3
[]
no_license
<?php session_start(); ?> <!DOCTYPE html> <html> <head> <title> login </title> </head> <body> <form action="validate.php" method="post"> <label for="email">email:</label> <br> <input type="email"id="email" name="email"> <br> <label for="password">password:</label> <br> <input type="password" id="pass" name="pass"> <br> <label for="remember">remember me</label> <input type="checkbox" name="remember" value="1"> <br> <input type="submit" name="submit"> </form> </body> </html> <?php if(isset($_COOKIE['email']) and isset($_COOKIE['pass'])){ $email = $_COOKIE['email']; $pass = $_COOKIE['pass']; echo "<script> document.getElementById('email').value = '$email'; document.getElementById('pass').value = '$pass'; </script>"; } ?>
true
bd0a2ce2b63dadef858b0f8c28a7e806211bed7e
PHP
ionutz2k2/snippet-catalog
/app/Decorators/DecoratorInterface.php
UTF-8
202
2.625
3
[ "MIT" ]
permissive
<?php namespace App\Decorators; use Illuminate\Database\Eloquent\Model; interface DecoratorInterface { public function decorateList(array $itemsList); public function decorate(Model $item); }
true