【发布时间】:2020-01-10 09:45:38
【问题描述】:
注意:未定义变量:第 32 行 C:\xampp\htdocs\xampp\index1.php 中的 db
警告:mysqli_query() 期望参数 1 为 mysqli,给定 null 在 C:\xampp\htdocs\xampp\index1.php 第 32 行
警告:mysqli_fetch_array() 期望参数 1 为 mysqli_result, 第 43 行 C:\xampp\htdocs\xampp\index1.php 中给出的 null 注意: 未定义变量:在线更新 C:\xampp\htdocs\xampp\index1.php 69
<!DOCTYPE html>
<html>
<head>
<title>CRUD: CReate, Update, Delete PHP MySQL</title>
</head>
<body>
<?php if (isset($_SESSION['message'])): ?>
<div class="msg">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
?>
</div>
<?php endif?>
<?php
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$update = true;
$record = mysqli_query($db, "SELECT * FROM info WHERE id=$id");
if (count($record) == 1) {
$n = mysqli_fetch_array($record);
$name = $n['name'];
$address = $n['address'];
}
}
?>
<?php
$results = mysqli_query($db, "SELECT * FROM info");?>
<table>
<thead>
<tr>
<th>Name</th>
<th>Address</th>
<th colspan="2">Action</th>
</tr>
</thead>
<?php while ($row = mysqli_fetch_array($results)) {?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['address']; ?></td>
<td>
<a href="index.php?edit=<?php echo $row['id']; ?>" class="edit_btn" >Edit</a>
</td>
<td>
<a href="server.php?del=<?php echo $row['id']; ?>" class="del_btn">Delete</a>
</td>
</tr>
<?php }?>
</table>
<form>
<form method="post" action="php_code.php" >
<input type="hidden" name="id" value="<?php echo $id; ?>">
<div class="input-group">
<label>Name</label>
<input type="text" name="name" value="">
</div>
<div class="input-group">
<label>Address</label>
<input type="text" name="address" value="">
</div>
<div class="input-group">
<?php if ($update == true): ?>
<button class="btn" type="submit" name="update" style="background: #556B2F;" >update</button>
<?php else: ?>
<button class="btn" type="submit" name="save" >Save</button>
<?php endif?>
</div>
</form>
</body>
</html>
2ND FILE
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'crud');
$name = "";
$address = "";
$id = 0;
$update = false;
if (isset($_POST['save'])) {
$name = $_POST['name'];
$address = $_POST['address'];
mysqli_query($db, "INSERT INTO info (name, address) VALUES ('$name', '$address')");
$_SESSION['message'] = "Address saved";
header('location: index.php');
}
if (isset($_POST['update'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$address = $_POST['address'];
mysqli_query($db, "UPDATE info SET name='$name', address='$address' WHERE id=$id");
$_SESSION['message'] = "Address updated!";
header('location: index.php');
}
if (isset($_GET['del'])) {
$id = $_GET['del'];
mysqli_query($db, "DELETE FROM info WHERE id=$id");
$_SESSION['message'] = "Address deleted!";
header('location: index.php');
}
【问题讨论】:
-
注意:未定义的变量:第 32 行的 C:\xampp\htdocs\xampp\index1.php 中的 db 告诉您问题,您尝试在分配 $db 之前使用它
-
然后告诉我怎么分配?
-
好好看看你的第二个文件
-
并且不要在公共服务器上使用此代码,您的 SQL 查询不安全。 sql注入是可能的。学习准备好的语句和/或如何清理你的变量 w3schools 有一些很好的例子
-
在第二个文件中向下滚动
标签: php html mysql parameters undefined