随笔-211  评论-26  文章-8  trackbacks-0
我们前面讲过修改数据库表内容时使用set命令,我们看看如何在脚本中对表进行修改,下面是 
edit.php3的内容:


<html>
<head><title>Editing an entry from the database</title>
</head> 

<body bgcolor=#ffffff>
<h1>Edit an entry</h1

<?
mysql_connect() or die ("Problem connecting to DataBase");
$query = "select * from tbl";
$result = mysql_db_query("example", $query); 

if ($result) {
echo "Found these entries in the database:<br>";
echo "<table width=90% align=center border=1><tr>
<td align=center bgcolor=#00ffff>idx</td>
<td align=center bgcolor=#00FFFF>User Name</td>
<td align=center bgcolor=#00FFFF>Last Name</td>
<td align=center bgcolor=#00FFFF>Free Text</td>
</tr>";

while ($r = mysql_fetch_array($result)) {
$idx = $r["idx"];
$user = $r["UserName"];
$last = $r["LastName"];
$text = $r["FreeText"];

echo "<tr>
<td align=center>
<a href=\"editing.php3?idx=$idx&user=$user&last=$last&text=$text\">
$idx</a></td>
<td>$user</td>
<td>$last</td>
<td>$text</td>
</tr>";

}

echo "</table>";

} else {

echo "No data.";

}

mysql_free_result($result);
include ('links.x');

?>

</body>
</html>


如果不修改信息,输入项中显示的是默认信息。如果对这些信息做了修改,表单元将把修改后的值传递给另一个脚本程序editdb.php3,从而对数据库中的表进行修改。

脚本editdb.php3:


<?php
mysql_connect() or die ("Problem connecting to DataBase");

$query = "update tbl set 
idx='$idx',UserName='$UserName',LastName='$LastName',FreeText='$FreeText'
where 
idx='$idx'";

$result = mysql_db_query("example", $query); 
$query = "SELECT * FROM tbl";
$result = mysql_db_query("example", $query); 

if ($result) {
echo "Found these entries in the database:<br><p></p>";
echo "<table width=90% align=center border=1><tr>
<td align=center bgcolor=#00FFFF>idx</td>
<td align=center bgcolor=#00FFFF>User Name</td>
<td align=center bgcolor=#00FFFF>Last Name</td>
<td align=center bgcolor=#00FFFF>Free Text</td>
</tr>";

while ($r = mysql_fetch_array($result)) {

$idx = $r["idx"];
$user = $r["UserName"];
$last = $r["LastName"];
$text = $r["FreeText"];

echo "<tr>
<td>$idx</td>
<td>$user</td>
<td>$last</td>
<td>$text</td>
</tr>";

}

echo "</table>";

} else {

echo "No data.";

}

mysql_free_result($result);

include ('links.x');

?>

可以看出,代码中重要的部分是下面这一段:


$query = "update tbl set 
idx='$idx',UserName='$UserName',LastName='$LastName',FreeText='$FreeText' 
where idx='$idx'";



其中对数据进行修改的语法格式与在MySQL部分中讲到的是一样的。程序将对表中idx=$idx的行进行修改,如果有多个行满足这个条件,它们都将被修改。如果想让条件更具体些,可以将where条件改成: 


$query = "update tbl set idx='$idx',UserName='$UserName',
LastName='$LastName',FreeText='$FreeText' where idx='$idx'
and UserName='$UserName' and LastName='$LastName' and 
FreeText='$FreeText'";



这个语句将对所有的数据都进行检查看看是否满足条件,而不仅仅是idx。



posted on 2006-10-08 18:18 dragon 阅读(128) 评论(0)  编辑  收藏 所属分类: php学习专区