- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我以前问过这个问题,但我因为重复的问题而被打了一巴掌...但有趣的是,重复的问题答案是我不理解的东西,也不知道如何在我的代码中实现它。
“重复”问题的答案提到了 PDO 连接,目前我不知道或不理解。
我想出了在帮助下编写两个类,一个将数据提交到MySql数据库,另一个用于搜索MySql数据库的列。
我的问题是实际上将这两个类放在一个 php 文件中,并允许它们都只使用一个连接类。
这两个类都以不同的格式编写,我试图了解如何将它们组合成一个,或者至少使用一个连接类,而不是每个类都使用自己的连接函数,我知道,这是糟糕的 php 标准...
我被指出提到的答案:
$pdo = new PDO('something');
function foo() {
global $pdo;
$pdo->prepare('...');
}
我的问题是这样...我没有使用 PDO...请协助并解释我需要更改哪些内容才能使这两个类使用一个数据库连接...
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
function db_connect() {
// Define connection as a static variable, to avoid connecting more than once
static $connection;
// Try and connect to the database, if a connection has not been established yet
if(!isset($connection)) {
$connection = mysqli_connect('localhost','user','pass','resrequest_db1');
}
// If connection was not successful, handle the error
if($connection === false) {
// Handle error - notify administrator, log to a file, show an error screen, etc.
return mysqli_connect_error();
}
return $connection;
}
function db_query($query) {
// Connect to the database
$connection = db_connect();
// Query the database
$result = mysqli_query($connection,$query);
return $result;
}
class booking
{
private $error;
private $success;
private $form_data = array();
function __construct()
{
//check if the booking form has been submitted
if (isset($_POST['submit_form'])) {
foreach ($_POST as $field => $value)
$this->form_data[$field] = $value;
//start perform the validation once the form has been submitted
$this->validateInformation();
}
//check to see if the mail has been sent, and then display a success message
if (isset($_GET['m']) && $_GET['m'] == "s") {
$this->error = "<div class='alert alert-success'>Thank You! We received your booking</div>";
}
//display error if any
if (!empty ($this->error) || !empty ($this->success))
$this->displayMessage(!empty($this->error) ? $this->error : (!empty($this->success) ? $this->success : ''), false);
}
/********************************************************
* This function retrieves data for booking form
* and performs validation
*******************************************************/
private function validateInformation()
{
// check if person provided his name
if (empty($this->form_data['b_name'])) {
$this->error .= '<li>You must enter your name.</li>';
}
// check if person provided his email
if (empty($this->form_data['email'])) {
$this->error .= '<li>You must enter your email.</li>';
}
// check if the email address provided by user is in correct format
if (!empty($this->form_data['email'])) {
if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $this->form_data['email'])) {
$this->error .= '<li>Email format your entered is not valid.</li>';
}
}
// check if contact_number is empty
if (empty($this->form_data['contact_number'])) {
$this->error .= '<li>Please enter a contact number.</li>';
}
//Check for a valid phone number (Only numbers between 7 & 20 caracters)
if (!empty($this->form_data['phone'])) {
$phone = $this->form_data['phone'];
$pattern = "/^[0-9\_]{10,20}/";
if (preg_match($pattern,$phone)){
$phone = $this->form_data['phone'];}
else{ $errors[] = 'Your Phone number can only be numbers.';}
} else {$errors[] = 'You forgot to enter your Phone number.';}
// check if person provided total rooms
if (empty($this->form_data['nr_rooms'])) {
$this->error .= '<li>Indicate total rooms.</li>';
}
// check if person provided arrival date
if (empty($this->form_data['arrival'])) {
$this->error .= '<li>Please select arrival date.</li>';
}
// check if person provided departure date
if (empty($this->form_data['departure'])) {
$this->error .= '<li>Please select departure date.</li>';
}
$this->error = (isset($this->error)) ? "<div class='alert alert-danger'><h4 class='alert-heading'>Attention!</h4>$this->error</div>" : '';
// if no errors are found, get ready to send the mail
if (empty($this->error)) {
$this->dbInsert();
}
}
/********************************************************
* This function inserts data into Db
*******************************************************/
private function dbInsert()
{
$b_name=$this->form_data['b_name'];
$email=$this->form_data['email'];
$contact_number=$this->form_data['contact_number'];
$nr_rooms=$this->form_data['nr_rooms'];
$arrival=$this->form_data['arrival'];
$departure=$this->form_data['departure'];
// An insertion query.
$result = db_query("INSERT INTO bookings (b_name,email,contact_number,nr_rooms,arrival,departure)
VALUES ('$b_name','$email','$contact_number','$nr_rooms','$arrival','$departure')");
if($result === false) {
// Handle failure - log the error, notify administrator, etc.
$error ="<div class='alert alert-danger'><h4 class='alert-heading'>Attention!</h4>
Databse error!!!</div>";
} else {
$redirect_page = "index.php?m=s";
header('Location: ' . $redirect_page);
exit();
}
}
/********************************************************
* This function displays error if any
*******************************************************/
private function displayMessage($error, $exit = true)
{
if (!empty($error)) :
include_once(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . 'header.php');
echo $error;
if ($exit) {
include_once(dirname($_SERVER['SCRIPT_FILENAME']) . '/' . 'footer.php');
exit();
}
endif;
}
/********************************************************
* This function will store the submitted data in case
* of any error so user does not have to re enter the
* information which he/she already provided
*******************************************************/
public function fetchPost($var)
{
return empty($this->form_data[$var]) ? '' : $this->form_data[$var];
}
}
$booking = new booking();
class search {
/**
* MySQLi connection
* @access private
* @var object
*/
private $mysqli;
/**
* Constructor
*
* This sets up the class
*/
public function __construct() {
// Connect to our database and store in $mysqli property
$this->connect();
}
/**
* Database connection
*
* This connects to our database
*/
private function connect() {
$config = parse_ini_file('config.ini'); //<--------------------------- Not to be placed in root directory, done for Resrequest demo
$this->mysqli = new mysqli( 'localhost', $config['username'],$config['password'],$config['dbname'] );
}
/**
* Search routine
*
* Performs a search
*
* @param string $search_term The search term
*
* @return array/boolen $search_results Array of search results or false
*/
public function search($search_term) {
// Sanitize the search term to prevent injection attacks
$sanitized = $this->mysqli->real_escape_string($search_term);
// Run the query
$query = $this->mysqli->query("
SELECT b_name, email, contact_number, arrival, departure
FROM bookings
WHERE b_name LIKE '%{$sanitized}%'
OR email LIKE '%{$sanitized}%' OR contact_number LIKE '%{$sanitized}%'
OR arrival LIKE '%{$sanitized}%' OR departure LIKE '%{$sanitized}%'
");
// Check results
if ( ! $query->num_rows ) {
return false;
}
// Loop and fetch objects
while( $row = $query->fetch_object() ) {
$rows[] = $row;
}
// Build our return result
$search_results = array(
'count' => $query->num_rows,
'results' => $rows,
);
return $search_results;
}
}
?>
最佳答案
这是处理此类事情的常见方法。请尝试:
class Database {
private static $instance;
private $db;
private function __construct() {
$this->db = mysqli_connect('localhost','user','pass','resrequest_db1');
}
public static function getInstance() {
if(self::$instance === null) {
self::$instance = new Database();
}
return self::$instance->db;
}
}
class MyClass {
private $db = null;
public function __construct($db){
$this->db = $db
}
.... your code here
}
// you create the unique connection here.
$db = Database::getInstance();
// call of the class
$myClass = new MyClass($db);
关于php - 不知道如何为我的两个类创建全局 Mysqli 连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32078065/
关闭。这个问题是off-topic .它目前不接受答案。 想改进这个问题? Update the question所以它是on-topic对于堆栈溢出。 9年前关闭。 Improve this que
我有一堆 php 脚本计划在 CentOS 机器上的 cron 中每隔几分钟运行一次。我希望每个脚本在启动时自我检查它的前一个实例是否仍在运行,如果是则停止。 最佳答案 我这样做是为了管理任务并确保它
是否有 bash 命令、程序或 libusb 函数(尽管我没有找到)来指示 USB 设备的 OUT 或 IN 端点是什么? 例如,libusb_interface_descriptor(来自 libu
我如何知道 NSTextField 何时成为第一响应者(即当用户单击它来激活它时,但在他们开始输入之前)。我尝试了 controlTextDidBeginEditing 但直到用户键入第一个字符后才会
我怎么知道我的代码何时完成循环?完成后我还得再运行一些代码,但只有当我在那里写的所有东西都完成后它才能运行。 obj.data.forEach(function(collection) {
我正在使用音频标签,我希望它能计算播放了多少次。 我的代码是这样的: ; ; ; 然后在一个javascript文件中 Var n=0; function doing(onplaying)
我正在尝试向 Package-Explorer 的项目上下文菜单添加一个子菜单。但是,我找不到该菜单的 menuid。 所以我的问题是如何在 eclipse 中找到 menuid? 非常感谢您的帮助。
我有一个名为“下一步”的按钮,它存在于几个 asp.net 页面中。实际上它是在用户控件中。单击“下一步”时,它会调用 JavaScript 中的函数 CheckServicesAndStates。我
我正在尝试在 Visual Studio 中使用 C++ 以纳秒为单位计算耗时。我做了一些测试,结果总是以 00 结尾。这是否意味着我的处理器(Ryzen 7-1800X)不支持 ~1 纳秒的分辨率,
我有一个自定义 ListView ,其中包含一些元素和一个复选框。当我点击一个按钮时。我想知道已检查的元素的位置。下面是我的代码 public class Results extends ListAc
如何在使用 J2ME 编写的应用程序中获取网络运营商名称? 我最近正在尝试在 Nokia s40 上开发一个应用程序,它应该具有对特定网络运营商的独占访问权限。有没有这样的API或库? 最佳答案 没有
我使用服务器客户端组件,当在此组件的 TransferFile 事件中接收文件时,我使用警报消息组件。所以我希望,如果用户单击警报消息,程序将继续执行 TransferFile 事件中的代码,以在单击
如果我创建一个类A具有一些属性,例如 a, b, c我创建对象 A x1; A x2; A x3; ... A xN 。有没有办法在同一个类中创建一个方法来检索我创建的所有对象?我想创建类似 stat
我正在制作一个应用程序,其中包含相同布局的 81 个按钮。它们都被称为我创建的名为“Tile”的对象。问题是这些图 block 存储在数组中,因此我需要知道以 int 格式单击了哪个按钮才能调用图 b
UIProgressView有这个setProgress:animated: API。 有没有办法确切知道动画何时停止? 我的意思是这样的? [myProgress setProgress:0.8f
我正在使用两个 jQuery 队列,我希望其中一个队列在另一个队列完成后出队。我怎么知道第一个是否完成?我应该使用第三个队列吗?! 这是我所拥有的: var $q = $({}); $q.que
jQuery 中有没有一种方法可以知道是否至少有一个复选框已被选中? 我有一个包含很多复选框的表单,每个复选框都不同。 我需要一种 jQuery 的方式来表达这样的内容,这就是逻辑: If at le
给定 2 个选择 100 50 100 在这两种情况下,我都想在 .example 中获取数字,使用相同的选择器或者以某种方式知道 .no-text 和 之间的区别。带文字 执行
我在我的应用程序中使用 System.ComponentModel.BindingList 作为 DataGridView.DataSource。该列表非常大,需要几秒钟才能绘制到 DataGridV
我想知道用户在 Android 中选择的默认键盘。我知道我可以使用 InputMethodManager 访问已启用的输入法列表,但我想知道用户当前使用的是哪一个。 到目前为止,我已经尝试获取当前的输
我是一名优秀的程序员,十分优秀!