我正在使用easyPHP 。我正在尝试更新数据库中的记录,但我不断收到 <?php echo $btitle; ?>
和<?php echo $bauthor; ?>
写在我的 HTML 表单的文本框中,数据未更新,但它确实打印“已成功更新数据”。
这是我的表单代码:
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>Update Book</title>
</head>
<body>
<h1>Update Your Library</h1>
<form method = "post" action = "editBook.php">
<?php
$conn = mysql_connect ("localhost", "root", "");
$db = mysql_select_db ("library", $conn);
$query = "select * from Books where No = ". $_GET['bid'];
$result = mysql_query($query, $conn);
while ($row = mysql_fetch_assoc($result))
{
$bid = $row ['bid'];
$btitle = $row ['btitle'];
$bauthor = $row ['bauthor'];
}
mysql_close($conn);
?>
<table>
<input type="hidden" name="bid" size="5" value="<?php echo $bid;?>">
<tr>
<td>Title:</td>
<td><input type="text" name="btitle" size="100"value="<?php echo $btitle;?>"></td>
</tr>
<tr>
<td>Author:</td>
<td><input type="text" name="bauthor" size="100" value="<?php echo $bauthor;?>"></td>
</tr>
</table>
<p>
<input type="submit" value="Update">
</p>
</form>
</body>
</html>
<?php
$dbhost = '127.0.0.1';
$dbuser = 'root';
$dbpass = '';
$bid=$_POST['bid'];
$btitle=$_POST['btitle'];
$bauthor=$_POST['bauthor'];
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db('library');
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = "update books
set Title='$btitle',
Author='$bauthor'
where book_id='$bid'";
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
print "updated data successfully\n";
mysql_close($conn);
?>
最佳答案
这些文件似乎没有被 PHP 解析。问题可能是配置中未定义文件名扩展名。
另一方面,我看到当第一个问题解决后可能会出现另一个问题。保存信息的变量超出范围。这将导致空答案。
当您从数据库读取时:
while ($row = mysql_fetch_assoc($result))
{
$bid = $row ['bid'];
$btitle = $row ['btitle'];
$bauthor = $row ['bauthor'];
}
这 3 个变量是在 while(){} 范围内创建的,并且它们不存在于其外部。只需在主作用域中的循环之前用空字符串初始化它们即可:
$bid = $btitle = $bauthor = '';
while ($row = mysql_fetch_assoc($result))
{
$bid = $row ['bid'];
$btitle = $row ['btitle'];
$bauthor = $row ['bauthor'];
}
关于php - 使用 PHP 更新 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44076806/