2017-07-31 134 views
0

我想將我的數據庫表中的一列存儲在一個數組中,這樣我就可以將它與我擁有的數組進行比較。我只從表格中選擇一列,並存儲所有行。我設法這樣做,但在2D數組,但是當比較2D數組到我的1D數組時,我得到一個錯誤。所以請幫助我將它轉換爲1d數組或從開始,如果我可以將數據存儲在1d數組中。從1D數組中的數據庫存儲數據不是2d

$array = array(); 
$serviceId = "SELECT service_id FROM servicesorders WHERE order_id = '$orderId'"; 
$resultId = mysqli_query($connection, $serviceId) or die(mysqli_error($connection)); 
while ($serviceIdfinal = mysqli_fetch_assoc($resultId)) { 
$array[] = $serviceIdfinal; //the array I used to store the data 
} 
var_dump($array); 

$isCheckedstring = $_POST['show']; 
$isCheckedarray = str_split($isCheckedstring, 4); // the array I want to compare the stored data with 
var_dump($isCheckedarray); 

兩個數組的後續代碼var_dump如下:

array( 
    [0]=> array(
     ["service_id"]=> "1" 
    ) 
    [1]=> array(
     ["service_id"]=> "7" 
    ) 
    [2]=> array( 
     ["service_id"]=> "11" 
    ) 
) 

而且

array(
    [0]=>"0011" 
    [1]=>"0012" 
) 
+2

[小博](http://bobby-tables.com/)說** [你的腳本是在對SQL注入攻擊的風險(HTTP://計算器.COM /問題/ 60174 /何燦I-防止-SQL注入式-PHP)**。瞭解[MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php)的[Prepared Statements](準備語句)(http://en.wikipedia.org/wiki/Prepared_statement)。即使** [轉義字符串](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string)**是不安全的! – GrumpyCrouton

+0

和你的問題是什麼? –

+0

@GrumpyCrouton在很長一段時間裏都沒有看到過小笨蛋 –

回答

3

您正在使用mysqli_fetch_assoc,所以你需要獲取關聯列。

您需要更改

while ($serviceIdfinal = mysqli_fetch_assoc($resultId)) { 
    $array[] = $serviceIdfinal; //the array I used to store the data 
} 

while ($serviceIdfinal = mysqli_fetch_assoc($resultId)) { 
    $array[] = $serviceIdfinal['service_id']; //the array I used to store the data 
} 
0

當你的數據庫返回一個數組,它返回行的一組,每個是一個關聯數組。每行都有一個元素並不重要,它仍然是一個數組數組。

你將不得不在$array從一種形式轉化爲另一種與foreach循環:

$newArray = []; 
foreach($array as $row) { 
    // This line here is where you'll do any needed string modifications 
    // such as padding with leading zeroes, etc. 
    $newArray[] = $row["service_id"]; 
} 
var_dump($newArray) 

這應該淨你:

array( 
    [0]=> "1", 
    [1]=> "7", 
    [2]=> "11" 
) 

編輯:或者,你應該這樣做在你正在使用的while循環中,正如米蘭在his answer中指出的那樣。

0

您可以嘗試使用PDO而不是mysqli。

$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); 
$sql = $conn->query("your query"); 
$sql->fetch(PDO::FETCH_ASSOC); 

就是這樣:)

+0

PDO仍然返回一個行數組,每行都是一個數組。它不能解決問題。 – RedDwarfian

相關問題