php
  • loops
  • mysqli
  • foreach
  • 2014-12-25 47 views 0 likes 
    0

    在這裏我爆炸上面的字符串與,並得到了陣列$ myArray。準備mysqli選擇使用爆炸

    <?php 
    $myString = '1,2,3,4'; 
    $myArray = explode(',', $myString); 
    print_r($myArray); 
    

    但我怎麼能使其成爲一個select語句

    mysqli_query($con,"SELECT * FROM Persons where id = 'First part of Array'"); 
    mysqli_query($con,"SELECT * FROM Persons where id = 'Second part of Array'"); 
    mysqli_query($con,"SELECT * FROM Persons where id = 'Third part of Array'"); .. 
    

    在Foreach循環

    回答

    1

    無需爆炸。

    $myArray = explode(',', $myString); 
    

    如果您有:使用IN算哪裏的情況下

    mysqli_query($con,"SELECT * FROM Persons where id IN (".$myString.")"); 
    

    查詢像

    SELECT * FROM Persons where id IN (1,2,3,4); 
    
    +0

    謝謝,這是偉大的 – ABD

    1

    爲什麼寫多個sql語句,如果你得到了IN運營商,您檢查一些特定的字符串值需要使用這個:

    $myArray =array_map('strval', $myArray); 
    
    mysqli_query($con,"SELECT * FROM Persons where id IN (".$myString.")"); 
    
    1

    我認爲它是一個壞主意,爲每個迭代進行查詢。相反,運行像

    $myString = '1,2,3,4'; 
    $myArray = explode(',', $myString); 
        // Just format the string so that it appears as '1','2'... instead of '1,2' 
    for ($i = 0; $i < count($myArray); $i ++) 
    { 
        $myArray[$i] = "'" . $myArray[$i] . "'"; 
    } 
    $myFormattedString = implode(',', $myArray); 
    
    mysqli_query($con,"SELECT * FROM Persons where id IN (".$myFormattedString.")"); 
    
    0

    單個查詢您可以使用:

    mysqli_query($con,"SELECT * FROM Persons where IN ('".$myString."')"); 
    

    或者:

    $ids = join(',',$myArray); 
    mysqli_query($con,"SELECT * FROM Persons where IN ($ids)"); 
    
    相關問題