สอบถาม PHP การค้าหา ฟิวเดียว แต่หลายเงีื่อนไข

เริ่มโดย JumDaiDee, 01 เมษายน 2014, 15:30:14

หัวข้อก่อนหน้า - หัวข้อถัดไป

0 สมาชิก และ 1 ผู้มาเยือน กำลังดูหัวข้อนี้

JumDaiDee

สวัสดีครับ พี่ๆ โปรแกรมเมอร์

พอดีผมติดปัญหาอยู่ว่า อยากได้ข้อมูลจากฟิว ticket_status_id ฟิวเดียว
โดยมีมีหลายเงื่อนไข โดยปกติแล้ว จะต้อง AND ที่ฟิวก่อนแล้วค่อย OR ตามเงื่อนไข
จากตัวอย่างโค้ดมีวิธีแก้ไหมครับ หากเราไม่เลือกเงื่อนไขแรก จะทำให้ AND หาย แล้วรู้สึกว่ามันจะไม่อ่าน OR เลยครับ

if (!empty($_GET[status1])) $where .= " and tk.ticket_status_id = '$_GET[status1]'";
if (!empty($_GET[status2])) $where .= " or tk.ticket_status_id = '$_GET[status2]'";
if (!empty($_GET[status3])) $where .= " or tk.ticket_status_id = '$_GET[status3]'";
if (!empty($_GET[status4])) $where .= " or tk.ticket_status_id = '$_GET[status4]'";
if (!empty($_GET[status5])) $where .= " or tk.ticket_status_id = '$_GET[status5]'";

รบกวนด้วยครับ
:wanwan017: :wanwan017:
สินค้าออนไลน์ https://www.shoppook.com/product | โปรแกรมออนไลน์ : https://appnon.com

ohmohm

$str1 = " and (";
$str2 = "";
if (!empty($_GET[status1])) {$where .= $str1 ." tk.ticket_status_id = '$_GET[status1]'"; $str2 = ")"; $str1 = " or ";}
if (!empty($_GET[status2])) {$where .= $str1 ." tk.ticket_status_id = '$_GET[status2]'"; $str2 = ")"; $str1 = " or ";}
if (!empty($_GET[status3])) {$where .= $str1 ." tk.ticket_status_id = '$_GET[status3]'"; $str2 = ")"; $str1 = " or ";}
if (!empty($_GET[status4])) {$where .= $str1 ." tk.ticket_status_id = '$_GET[status4]'"; $str2 = ")"; $str1 = " or ";}
if (!empty($_GET[status5])) {$where .= $str1 ." tk.ticket_status_id = '$_GET[status5]'"; $str2 = ")"; $str1 = " or ";}
$where .= $str2;

แนวคิดก็คือ ก่อนหน้าตัวดำเนินการเปรียบเทียบ (=) ต้องมีอะไรบ้างอย่างนำหน้า หรือเพื่อเป็นตัวเชื่อม เช่น status ที่เจอตัวแรก (ไม่ empty) ต้องนำหน้าด้วย "and (" จากนั้นตัวที่เจอถัดมาต้องเปลี่ยนตัวนำหน้าเป็น " or " และถ้ามี status มาแล้วอย่างน้อยหนึ่งตัว ต้องปิดท้ายด้วย ")"
เปลี่ยนชื่อ $str1, $str2 ตามความจำเป็นได้นะครับ
แล้วต้องระวัง SQL injection ด้วยนะครับ
http://www.thaiseoboard.com/index.php/topic,344170.0.html

JumDaiDee

ได้แล้วครับผม

ขอบคุณพี่ ohmohm มากสุดๆครับ
อุสา มานั่งคิดแล้วเขียนโค้ดให้

โค้ดที่พี่ให้มา สามารถทำงานได้แล้ว

พี่ให้พี่ ohmohm เจริญในหน้าที่การงานนะครับ
แถม +1 ให้เลยครับผม
:wanwan020: :wanwan020:
สินค้าออนไลน์ https://www.shoppook.com/product | โปรแกรมออนไลน์ : https://appnon.com