亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 PHP 中使用 PDO 從多個表中搜索的更好方法是什么?

在 PHP 中使用 PDO 從多個表中搜索的更好方法是什么?

PHP
繁星coding 2023-07-08 20:14:48
我有一個 HTML 表單,其中有一個用于輸入產品名稱的搜索字段,下面是復選框,每個復選框對應一個要搜索產品名稱的商店。用戶可以通過選中復選框從多個商店進行搜索。該表單向服務器發送 GET 請求,其中有一個數據庫,其中包含針對不同商店的單獨表。<form action="price.php" method="get">    <input type="text" id="query" name="query" value="">    <input type="checkbox" name="shop1" id="shop1">    <input type="checkbox" name="shop2" id="shop2">    <input type="submit" name="submit" value="submit"></form>因此,在服務器端,我編寫了一段 PHP 代碼,它將從與用戶檢查的商店相對應的表中搜索產品名稱。由于我將來會添加越來越多的商店,以下哪些 PHP 代碼更適合?版本1<?phpfunction search($pdo, $shop) {if ( isset($_GET[$shop]) && ($_GET['query'] !== "") ) {    switch ($shop) {        case "shop1":            $stmt = $pdo->prepare("SELECT * FROM `shop1` WHERE `name` LIKE :query");            $stmt->execute(array(":query" => "%". $_GET['query'] . "%"));            break;        case "shop2":            $stmt = $pdo->prepare("SELECT * FROM `shop2` WHERE `name` LIKE :query");            $stmt->execute(array(":query" => "%". $_GET['query'] . "%"));            break;        ...        ...        ...    }    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);    if ( count($rows) === 0 ) {        $_SESSION[$shop] = 'nothing found from '. $shop;        return array();    } else {        return $rows;    }    } else {        return array();    }}if ( ! isset($_GET['query']) ) {    $_SESSION['success'] = "search for an item";} else {    $rowsShop1 = search($pdo, "shop1");    $rowsShop2 = search($pdo, "shop2");    ...    ...    ...}?>版本2<?phpfunction search1($pdo, $shop, $sql) {    $stmt = $pdo->prepare($sql);    $stmt->execute(array(":query" => "%". $_GET['query'] . "%"));    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);    if ( count($rows) === 0 ) {        $_SESSION[$shop] = 'nothing found from '. $shop;        return array();    } else {        return $rows;    }}或者有更好的方法來做到這一點嗎?
查看完整描述

1 回答

?
幕布斯7119047

TA貢獻1794條經驗 獲得超8個贊

如果小提琴不知何故不再工作,下面是 SQL 代碼。(假設MySQL/MariaDB)

create table product

(

? ? id int auto_increment,

? ? name varchar(255) not null,

? ? constraint product_pk

? ? ? ? primary key (id)

);


create table shop

(

? ? id int auto_increment,

? ? name varchar(255) not null,

? ? constraint shop_pk

? ? ? ? primary key (id)

);


create table product_shop

(

? id int auto_increment,

? product_id int,

? shop_id int,

? quantity int not null default 0,

? constraint product_shop_pk

? ? ? primary key (id)

);


alter table product_shop

? ? add constraint product_shop_product_fk

? ? ? ? foreign key (product_id) references product (id);

alter table product_shop

? ? add constraint product_shop_shop_fk

? ? ? ? foreign key (shop_id) references shop (id);


查看完整回答
反對 回復 2023-07-08
  • 1 回答
  • 0 關注
  • 129 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號