问题描述
我正在使用PHP和MYSQL创建一个有3页的网站;插入,更新和删除。插入页面将新列添加到数据库表。在我的更新页面中,我希望能够查看添加了新列的表中的所有数据。我将如何处理?也就是说,如果现在在插入之后有11列,而不是以前的10列,我希望更新页面显示
I am creating a website using PHP and MYSQL which has 3 pages; Insert, Update & Delete. The insert page adds a new column to a database table. In my update page I want to be able to view all data which is in the table where the new column has been added. How would I go about this? i.e if theres now 11 columns after the insert rather that 10 previous i want the update page to show
col1 | col2 | col3 | col4 | col5 | col6 | col7 | col8 | col9 | col10 | col11
data | data | data | data | data | data | data | data | data | data | data
推荐答案
下面是一个带有我的表的示例:
Here's an example with a table of mine:
<table>
<tr>
<?php
$mysqli = new mysqli("localhost", "user", "pass", "test");
/*
* CREATE TABLE `test` (
`col1` int(11) NOT NULL,
`col2` int(11) NOT NULL
... // until col5
*/
$query = "SELECT column_name FROM information_schema.columns
WHERE table_name = 'test' AND table_schema = 'test'";
$result = $mysqli->query($query);
// INSERT INTO `test`.`test` (`col1`, `col2`, `col3`, `col4`, `col5`)
// VALUES ('10', '11', '12', '13', '14'), ('15', '16', '17', '18', '10');
$query2 = "SELECT * FROM test";
$result2 = $mysqli->query($query2);
while ($row = $result->fetch_assoc()) {
?>
<td><?=$row['column_name'];?></td>
<?php
}
?>
</tr>
<tr>
<?php
while ($res = $result2->fetch_assoc()) {
$count_columns = $result->num_rows;
for ($i = 1; $i <= $count_columns; $i++) {
?>
<td><?=$res['col'.$i.''];?></td>
<?php
}
?>
</tr>
<tr>
<?php
}
输出:
Output:
col1 col2 col3 col4 col5
10 11 12 13 14
15 16 17 18 10
这并不知道列名及其计数。它们具有相同的前缀 col就足够了。
That's without knowing the column names and their count. It's enough they have the same prefix "col".
添加了新列之后:
ALTER TABLE `test` ADD `col6` INT NOT NULL
UPDATE test SET col6 = col1+1
相同的代码(不做任何更改)产生:
The same code (without any change) produces:
col1 col2 col3 col4 col5 col6
10 11 12 13 14 11
15 16 17 18 10 16
PS:我仍然不鼓励这种表结构,您需要动态地添加列
P.S.: I'm still not encouraging this table structuring, where you need to add columns dynamicly
这篇关于向MYSQL表中添加新列后,在PHP中编辑表数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!