从表列创建PHP数组

时间:2018-01-07 01:07:34

标签: php sql

我正在尝试创建一个显示表中每一行的循环。我想我需要从PK中制作一个阵列,但我无法弄清楚如何做到这一点。到目前为止,这是我的代码:

$conn = dbConnect('read');
$getData = 'SELECT * FROM table';
$allData = $conn->query($getdata);
if (!$allData) {
    $error = $conn->error;
} else {
    $data = $allData->fetch_assoc();
    $rowId = array($data['PK']);
} while ($rowId <= count($rowId)) {
    // code to be run for each row
    $rowId++;
}
编辑:抱歉,我的问题很混乱,我是PHP的新手。

2 个答案:

答案 0 :(得分:4)

你的问题有点让人困惑,但我认为这就是你要做的事情:

$sql = 'SELECT * FROM table';
$query = $conn->query($sql);
while ($row = $query->fetch_assoc()) {
    $data[$row['PK']] = $row;
}

这会迭代每一行,创建一个数组并使用列PK的行值作为关联数组键。

答案 1 :(得分:2)

fetch_assoc()(我现在假设mysqli)并不从结果中获取所有数据,而是在一行之后获取一行。因此,您不需要创建$row['PK']数组,但需要循环结果。

$conn = dbConnect('read');
$getData = 'SELECT * FROM `table`'; // you would need backticks here, if the table really is called "table" (what you shouldn't do...)
$result = $conn->query($getData); // it's not 'allData', it is a result_set. And be carefull about Case! $getData!=$getdata
if (!$result) {
    $error = $conn->error;
} else {
    $cnt=0;
    while($row = $result->fetch_assoc()) {
        // code to be run for each row
        // you can display $row['PK'] now:
        echo $row['PK'];
        // or add that value to something else, whatever you need
        $cnt = $cnt+$row['PK'];
        // or to have a new array with the values of one table-column:
        $columnRows[] = $row['PK'];
    }
    // now you can use the created array
    foreach($columnRows as $PK) {
        echo $PK;
    }
}