gpt4 book ai didi

php - 不知道如何为我的两个类创建全局 Mysqli 连接

转载 作者:行者123 更新时间:2023-11-29 22:06:55 24 4
gpt4 key购买 nike

我以前问过这个问题,但我因为重复的问题而被打了一巴掌...但有趣的是,重复的问题答案是我不理解的东西,也不知道如何在我的代码中实现它。

“重复”问题的答案提到了 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com