我的PHP脚本返回具有最高ID的MySQL值,而不是请求的ID:
<?php
$db = mysqli_connect('localhost', 'root', '(Password)', 'web');
#THE 'userEmail' variable is from a script above not displayed on here
$email = $row['userEmail'];
$result = mysqli_query($db, "SELECT * FROM table WHERE email = '$email'");
echo "<center><table border='1'>
<tr>
<th>Username</th>
<th>Password</th>
<th>Active?</th>
<th>Add Account</th>
<th>Delete Account</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
$userName = $row['username'];
$passWord = $row['password'];
$addId = $row['id'];
$deleteId = $row['id'];
echo "<tr>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['password'] . "</td>";
echo "<td>" . $row['activeStatus'] . "</td>";
echo "<td><a href=home.php?add=$addId>Add Account</a></td>";
echo "<td><a href=home.php?delete=$deleteId>Delete Account</a></td>";
echo "</tr>";
}
echo "</table></center>";
if( isset($_GET['delete']) ) {
$deleteId = $_GET['delete'];
$delete = "DELETE FROM table WHERE id = $deleteId";
$result = mysqli_query($db, $delete);
deleteLineInFile("/var/www/html/table-users.txt","'$userName'");
if ($result == TRUE) {
echo "Record updated successfully";
header('Location: home.php');
} else {
echo "Error updating record";
}
}
if( isset($_GET['add']) ) {
$addId = $_GET['add'];
$add = "(Too long to display)";
echo("$userName, $passWord");
file_put_contents("/var/www/html/directory/$addId.xml", $add);
header("Location: directory/$addId.xml");
}
function deleteLineInFile($file,$string)
{
$i=0;$array=array();
$read = fopen($file, "r") or die("can't open the file");
while(!feof($read)) {
$array[$i] = fgets($read);
++$i;
}
fclose($read);
$write = fopen($file, "w") or die("can't open the file");
foreach($array as $a) {
if(!strstr($a,$string)) fwrite($write,$a);
}
fclose($write);
}
?>
每次我尝试获取ID时,它只显示具有最高值的id。我不知道问题出在哪里。我认为这是行的问题,因为$userName = $row['username'];
和$passWord = $row['password'];
行存储在循环中。我注意到它可以正确地获取$_GET
变量的id,但不能获取$row
变量的id。有没有人能帮我弄清楚这种情况?
发布于 2018-06-23 10:38:06
提交表单时,$userName
和$password
不包含所提交ID的信息,它们包含来自while
循环的最后一个值。您需要执行数据库查询来查找相应的用户名。
if( isset($_GET['add']) ) {
$addId = $_GET['add'];
$add = "(Too long to display)";
$stmt = mysqli_prepare($db, "SELECT username, password FROM table WHERE id = ?");
mysqli_stmt_bind_param($stmt, "i", $addId);
mysqli_stmt_execute($stmt);
mysqli_stmt_bind_result($stmt, $userName, $passWord);
if (mysqli_stmt_fetch($stmt)) {
echo("$userName, $passWord");
file_put_contents("/var/www/html/directory/$addId.xml", $add);
header("Location: directory/$addId.xml");
} else {
die("User ID $addId not found");
}
}
我还展示了如何使用预准备语句来防止SQL注入。你应该在任何地方使用这个方法。
https://stackoverflow.com/questions/50997400
复制相似问题