2016-04-28 44 views
0

我有包含下列的表..爲什麼我的數組存儲在會話變量中雙擊?

database columns

我存儲在會話變量表的數據

$sql = "SELECT * from `basic_info` where Username='".$user."' and Password='".$pass."'"; 
$sqlresult = mysqli_query($con,$sql) or die(mysqli_error($con)); 
$rowCount = mysqli_num_rows($sqlresult); 
$currentData = mysqli_fetch_array($sqlresult); 

if($rowCount > 0){ 
    $_SESSION['currentUser'] = $currentData; 
} 

但每當我呼應數組的值使用以下代碼:

<?php 

echo "Welcome {$_SESSION['currentUser'][1]}"; 
echo "<div name='infoDisplay'>"; 
echo "<table>"; 
echo "<tr>"; 
echo "<td><b>Family Name</b><td>"; 
echo "<td><b>First Name</b><td>"; 
echo "<td><b>Middle Name</b><td>"; 
echo "<td><b>Birthday</b><td>"; 
echo "<td><b>Contact Number</b><td>"; 
echo "<td><b>Address</b><td>"; 
echo "<td><b>Username</b><td>"; 
echo "<td><b>Password</b><td>"; 
echo "<td><b>Permission Level</b><td>"; 
echo "<td></td>"; 
echo "</tr>"; 


echo "</table>"; 
echo "</div>"; 

echo "Array count: " . count($_SESSION['currentUser']) . "<br/>"; 

echo "<tr>"; 
for($rowcount=0; $rowcount<=count($_SESSION['currentUser']);$rowcount++){ 
    echo "<td>". $_SESSION['currentUser'][$rowcount] . "</td>"; 
} 
echo "</tr>"; 

?> 

數組數加倍。我的數據庫中只有9列,但結果是返回了18個計數。這就是爲什麼我也越來越以下錯誤:

error

請讓我知道你對我怎麼能輕易解決問題的投入。非常感謝您提前!祝你有美好的一天!

+0

'$ _SESSION [ 'currentUser'] [] = $ CURRENTDATA;'可以有不止一個當前用戶?這是你的實際代碼嗎?頂部和底部並不真正匹配。 –

+3

至於你爲什麼得到雙倍,這是因爲你沒有閱讀[文檔](http://php.net/manual/en/mysqli-result.fetch-array.php),它顯示默認' mysqli_fetch_array'返回數字和字符串鍵,即0-n和列名。 –

+0

@JonStirling我忘了編輯那部分。我已經糾正了這個部分。請忽略該行。謝謝! –

回答

0

正如評論中所述,mysqli_fetch_array返回一個數組,其中包含查詢中選擇的每列的兩個元素:一個元素帶有數字鍵,另一個元素的鍵是列名。因此,如果您選擇9列,陣列將具有從08的數字密鑰,並命名密鑰FamilyName,FirstName等。

您遇到的問題是count($_SESSION['currentUser'])這兩個元素,因此它將返回18而不是9。您的for循環然後將此用作限制,因此它將嘗試回顯$_SESSION['currentUser'][9]$_SESSION['currentUser'][17],這些不存在。

解決方法是使用mysql_fetch_row()而不是mysql_fetch_array()。或使用mysql_fetch_assoc()並使用foreach循環而不是for循環,這是我的正常偏好。

0

FROM THE MANUAL:

mysqli_fetch_array() is an extended version of the mysqli_fetch_row() function. In addition to storing the data in the numeric indices of the result array, the mysqli_fetch_array() function can also store the data in associative indices, using the field names of the result set as keys.

所以你返回的每一行可以說你做select fname,lname from ...

你會得到這樣的每一行的數組: -

$row would be 

[0 => 'fred', 'fname' => 'fred', 1 => 'Bloggs', 'lname' => 'Bloggs'] 

這是翻倍列的你談到

如果使用

mysqli_fetch_array($sqlresult, MYSQLI_ASSOC); 

mysqli_fetch_assoc($sqlresult); 

您只有列名的關聯數組,如:

['fname' => 'fred', 'lname' => 'Bloggs']