我有多个文本框,显示与mysql数据库中的一行相对应的字符串。我希望能够通过在文本框中键入并单击提交来更改数据库中的每个字符串。
因此,我在连接到数据库后创建了带有while循环的文本框。
<form action="<?php $self ?>" form method="post">
<?php
$query = "SELECT * FROM `table` ORDER BY table.ID DESC";
$result = @mysql_query($query) or die('
ERR: The database returned an unexpected error.
');
$num=mysql_numrows($result);
$change="";
$i=0;
while ($i < $num) {
$post=mysql_result($result,$i,"post");
$id=mysql_result($result,$i,"ID");
$ts=mysql_result($result,$i,"timeStamp");
$page = html_entity_decode($post);
$output = stripslashes($page);
if ($output != "") {
echo '<textarea name="' . $id . '" rows="4" cols="70">' . $output . '</textarea><div class="time"><font face="monospace">' . $ts . '</font></div>';
} //creates tables for each filled entry with a name corrsponing to its auto-increment id.
$i++;
}
?>
<input name="send" type="hidden" />
<div class="mod">
<p><input class="master" type="submit" value="Mod" /></p></div><!--submit button is called "Mod"-->
</form>
</body>
</html>
一切都显示正常。如果数据库有4行,其中包含文本,则会将这4行分别显示在一个单独的文本框中。
现在,我想用用户在文本框中输入的内容替换数据库中的文本。这是我试过的代码。它什么都不做。
<?php
$i=0;
while ($i < $num) {
$id=mysql_result($result,$i,"ID");
$post=mysql_result($result,$i,"post");
if (!isset($_POST[$id])) {
$_POST[$id] = "";
}
$change = $_POST[$id];
mysql_query("UPDATE 'database'.'table' SET 'post' = '$change' WHERE 'table'.'ID' ='$id';");
$i++;
}
基本上,循环将为表中的每一行运行一次。对于每个文本框,它都应该更新"数据库"ID为"1"的"POST"的$_POST[1]表,ID为"2"的"POST"的$_POST[2]表,等等。。。相反,什么也没发生。如有任何帮助,我们将不胜感激。
<form action="<?php $self ?>" form method="post">
<?php
$query = "SELECT * FROM `table` ORDER BY table.ID DESC";
$result = @mysql_query($query) or die('Query error:'.mysql_error());
$num=mysql_num_rows($result);
$change="";
while($post = mysql_fetch_array($result))
{
/*
$post = array(
'post' => '....',
'ID' => '...',
'timeStamp' => '...'
);
*/
$page = html_entity_decode($post['post']);
$output = stripslashes($page);
if ($output != "") {
echo '<textarea name="posts['.$post['ID'].']" rows="4" cols="70">' . $output . '</textarea><div class="time"><font face="monospace">' . $post['timeStamp'] . '</font></div>';
} //creates tables for each filled entry with a name corrsponing to its auto-increment id.
}
?>
<input name="send" type="hidden" />
<div class="mod">
<p><input class="master" type="submit" value="Mod" /></p></div><!--submit button is called "Mod"-->
</form>
</body>
</html>
php更新文件:
$query = "SELECT * FROM `table` ORDER BY table.ID DESC";
$result = @mysql_query($query) or die('Query error:'.mysql_error());
while($update_post = mysql_fetch_array($result))
{
$update = (isset($_POST[$update_post['ID']])) ? $_POST[$update_post['ID']] : "";
if($update != "")
{
mysql_query("UPDATE 'database'.'table' SET 'post' = '$update' WHERE 'table'.'ID' ='".$update_post['ID']."';");
echo "<!--POST ID ".$update_post['ID']." been updated-->'n";
}
}
我添加了一个html注释(<!-- -->
),这样您就可以检查更新是否真的发生了。通过这种方式,您可以调试代码。(您还应该阅读print_r,var_dump)