Mysql
 sql >> डेटाबेस >  >> RDS >> Mysql

तैयार कथन के साथ खोजने के लिए IN निर्देश का उपयोग करें

तैयार किए गए कथन में कोई पैरामीटर नहीं है क्योंकि आपने सूची तैयार करने से पहले सूची को बयान में प्रक्षेपित किया है।

$array=array("item1","item2","item3","item4");
//This is dynamically filled, this is just an example
$in_list = "'".implode("','",$array)."'";//that's why i use implode

$stmt = $this->db->prepare('SELECT libelle,activite,adresse,tel,lat,lng FROM etablissements where type IN ('.$in_list.')');

इस बिंदु पर, आपके द्वारा बनाया गया SQL कथन है:

SELECT libelle,activite,adresse,tel,lat,lng 
FROM etablissements where type IN ('item1','Item2','Item3','Item4')

चूंकि कथन में कोई पैरामीटर नहीं है, mysqli_stmt::bind_param विफल रहता है। कथन में वस्तुओं को प्रक्षेपित करने के बजाय (जो इंजेक्शन के लिए असुरक्षित है), मापदंडों की एक स्ट्रिंग को प्रक्षेपित करें, फिर मूल्यों को बांधें (जिसे अलग रखा जाना चाहिए)।

$array=array("item1","item2","item3","item4");

if (count($in_list) > 0) {
    $query = $this->db->prepare('SELECT libelle,activite,adresse,tel,lat,lng FROM etablissements WHERE type IN (' . str_repeat('?, ', count($in_list)-1) . '?)');

    $args = $in_list;
    array_unshift($args, str_repeat('s', count($in_list)));
    call_user_func_array(array($query, 'bind_param'), $args);
    $query->execute();
    $query->bind_result($libelle,$activite,$adresse,$tel,$lat,$lng);
}

बाइंडिंग के लिए पीडीओ का इंटरफ़ेस अधिक सीधा है।

$array=array("item1","item2","item3","item4");

if (count($in_list) > 0) {
    $query = $this->db->prepare('SELECT libelle,activite,adresse,tel,lat,lng FROM etablissements WHERE type IN (' . str_repeat('?, ', count($in_list)-1) . '?)');

    foreach ($in_list as $i => $arg) {
        // query params are 1-based, so add 1 to the index
        // PDO::PARAM_STR is the default type, so no need to pass 3rd arg
        $query->bindValue($i+1, $arg);
    }
    $query->execute();
    // no need to bind the result
}

वास्तव में, पीडीओ के साथ यह और भी आसान हो सकता है, क्योंकि PDOStatement::execute पैरामीटर मानों की सूची ले सकते हैं:

$array=array("item1","item2","item3","item4");

if (count($in_list) > 0) {
    $query = $this->db->prepare('SELECT libelle,activite,adresse,tel,lat,lng FROM etablissements WHERE type IN (' . str_repeat('?, ', count($in_list)-1) . '?)');

    $query->execute($in_list);
}



  1. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. MySQL कनेक्शन (max_connections) कैसे बढ़ाएं?

  2. MySQL का उपयोग करके मूल SQL क्वेरीज़ सीखें

  3. mysqldump के साथ mysql डेटाबेस बैकअप

  4. Docker (Apple Silicon/M1 Preview) MySQL मैनिफ़ेस्ट सूची प्रविष्टियों में linux/arm64/v8 के लिए मेल नहीं खाता है

  5. MAKE_SET () फ़ंक्शन MySQL में कैसे काम करता है