在向MYSQL表中添加新列后在PHP中编辑表数据
我使用PHP和MYSQL创建了一个网站,它有3个页面;插入,更新&删除。插入页面将新列添加到数据库表中。在我的更新页面中,我希望能够查看已添加新列的表中的所有数据。我将如何去做这件事?即如果现在孤单在插入后11列,而这10以前我想更新页面显示在向MYSQL表中添加新列后在PHP中编辑表数据
col1 | col2 | col3 | col4 | col5 | col6 | col7 | col8 | col9 | col10 | col11
data | data | data | data | data | data | data | data | data | data | data
下面是一个例子和我的一个表:
<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
}
输出:
col1 col2 col3 col4 col5
10 11 12 13 14
15 16 17 18 10
这是在不知道列名和它们的数量。他们有相同的前缀“col”就足够了。
添加一个新的列后:
ALTER TABLE `test` ADD `col6` INT NOT NULL
UPDATE test SET col6 = col1+1
相同的代码(没有任何变化)产生:
col1 col2 col3 col4 col5 col6
10 11 12 13 14 11
15 16 17 18 10 16
PS:我还是不鼓励这种表结构,你需要动态添加列
即使从PHP添加列(改变程序)是不好的做法对我来说,可能会有不同的解决方案。您可以从INFORMATION_SCHEMA检索的列:
SELECT column_name
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'yourTable';
$row['column_name']; //will output the actual result of columns for that table
而且实际结果是,你可以命名为“COL1,COL2”,这样你就可以遍历这些结果和收到的可变像
$row['col'.$i.''];
然后你可以收到每栏的结果,也可以收到他们的名字。
所以我不得不做一些像SELECT col1,col2等 FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name ='yourTable'; $ row ['col1'],$ row ['col2'];等等? 当然,如果我这样做,它只会显示我已经有的列,而无需手动添加代码? – 2013-04-21 17:04:01
否,SELECT column_name FROM information_schema.columns WHERE table_name ='yourtable'将立即检索该表的列名称。你也可以对它们进行计数,传递给一个变量,并做一个简单的'for'循环,把数字赋给字符串'col'。 – 2013-04-21 17:09:10
啊对了,我现在就和你在一起..我可以用这个代码来编辑这个信息吗? – 2013-04-21 17:12:19
1)运行选择查询2)检索数据3)输出html。 – 2013-04-21 16:51:14
你为什么要改变PHP代码的程序? – 2013-04-21 16:52:16
你正在添加列 - 真的吗?或行? – Revent 2013-04-21 16:54:27