2015-08-28 13 views
0

我想知道如何我的數組轉換爲字符串轉換陣列時STRING

$formats = $_POST['formats']; 
     $topics = $_POST['topics']; 

例如,如果我回聲出上面,它只是打印陣列。我希望它顯示數組作爲字符串,這樣我可以用它下面:

$resources = "select * from resources where stage LIKE '%".$stage."%' and formats LIKE '%".$formats."%' and topics LIKE '%".$topics."%'"; 

我一直建議做這樣的事情$formats = $_POST['formats'][0]; ,但我想輸出整個數組作爲一個字符串,"idea generation, business"會被equivilant到["idea generation", business"]

+0

在進一步採取措施之前,您應該搜索關於預準備語句和查詢參數。 –

+2

[Array to String PHP?]可能的重複?(http://stackoverflow.com/questions/7490488/array-to-string-php) – Script47

回答

3

因爲它是無法確定你使用,使該查詢發生的數據庫,我會建議你使用預處理語句paremeterizing你的價值觀根據您可以在PHP.net documentation關於這個問題讀什麼PDO對象構建查詢字符串。

綁定一個PHP變量到對應的命名或問號 佔位符在被用於製備 語句的SQL語句。與PDOStatement :: bindValue()不同,變量被綁定爲 的引用,並且僅在調用PDOStatement :: execute()時調用 。

正如你所看到的,這樣你就不必理會訪問之前轉換你的陣列變量,再加上,您授予安全的查詢語句。

所以,相反的implode荷蘭國際集團一個字符串,你有這樣的事情:

<?php 
    /* Execute a prepared statement by binding PHP variables */ 
    $stage = $_POST['stage']; 
    $formats = $_POST['formats']; 
    $topics = $_POST['topics']; 
    $stmt = $db->prepare('select * from resources where stage LIKE % :stage % and formats LIKE % :formats % and topics LIKE % :topics %'); 
    $stmt->bindParam(':stage', $stage); 
    $stmt->bindParam(':formats', $formats); 
    $stmt->bindParam(':topics', $topics); 
    $stmt->execute(); 
?> 

編輯:當你更新你正在使用的MySQLi,這將是沒有什麼不同。

$stmt = $mysqli_db->prepare('select * from resources where stage LIKE % ? % and formats LIKE % ? % and topics LIKE % ? %'); 
// assuming all your params are strings 
$stmt->bind_param('sss', $stage, $formats, $topics); 
$stmt->execute(); 

由於使用mysqli的,因爲它是一個無緩衝SQL查詢處理程序,你應該存儲你的結果,如果你是循環的同時執行與$stmt->store_result();

有關如何使用mysqlipdo對象,方法的任何疑慮和屬性可以很容易地在php.net文檔(上面鏈接)中找到。

當然,這只是基於您明顯需求的更好實踐的建議,但您仍然可以使用implode函數來實現您的字符串。

+1

嗨,非常感謝您的回覆。我使用mysqli連接到數據庫而不是PDO。 – John

+0

它可能並沒有什麼不同,只是語法上不同:) –

+0

謝謝,但是如何將它與我的mysqli while循環集成? – John