我正在尝试遍历我的数据库并检查用户是否已经存在于另一个表中。如果他们这样做,那么我想增加一个值,如果他们不想,那么我想添加用户。
当我运行下面的代码时,它会愉快地遍历所有结果:
<?php
$servername = "p:10*********";
$username = "*******";
$password = "*******";
$dbname = "******";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM payroll WHERE user != ' ' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo $result->num_rows;
while($row = $result->fetch_assoc()) {
$user= $row['user'];
$time= $row['time'];
$id= $row['id'];
echo $id;
echo $user;
}
} else {
echo "0 results";
}
$conn->close();
?>
&#13;
但是,当我添加SQL以检查它们是否存在于另一个表中时,循环不再正常运行并且每次都回显相同的用户。
<?php
$servername = "*******";
$username = "******";
$password = "********";
$dbname = "*****";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM payroll WHERE user != ' ' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo $result->num_rows;
while($row = $result->fetch_assoc()) {
$user= $row['user'];
$time= $row['time'];
$id= $row['id'];
echo $id;
echo $user;
$sql = "SELECT * FROM smsreport WHERE user = '$user'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "found";
} else {
echo "USER NOT FOUND";
}
}
} else {
echo "0 results";
}
$conn->close();
?>
&#13;
任何帮助都非常感激。
答案 0 :(得分:2)
睁眼:
重命名内部$result
变量。它正在翻阅第一个$result
。
可能是问题所在。虽然没有测试过。