我是php的新手并尝试添加删除按钮以从列表中删除对象(作业), 我希望删除按钮出现在每个单独的对象(作业)旁边,一旦单击,该作业将从数据库表中删除。下面是我的edit_jobs.php(显示特定用户的所有作业)和delete_job.php的代码(假设从表中删除该特定作业)有人可以告诉我我做错了什么,
我的edit_jobs页面显示特定用户发布的表格中的所有作业。
<?php
include_once "connect_to_mysql.php";
$id = $userid;
$username = $_GET['username'];
$result = mysql_query("SELECT * FROM jobs WHERE user_id ='$id'")
or die(mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<a href="job.php?id=' . $row['job_id'] . '"> ' . $row['job'] . '</a><br />';
echo 'category: ' . $row['category'] . '<br />';
echo 'description: ' . $row['description'] . '<br />';
echo '<a href="member.php?id=' . $row['userid'] . '">Clients profile</a><br />';
echo '<br />';?>
<a href="delete_job.php?job_id=<?php echo $row['job']; ?>"
onclick="return confirm('Are you sure you want to delete this book?');">
<img src="images/delete20.png" alt="Delete Book" />
</a>
<?php } ?>
delete_job页面
<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
if (!empty($_GET['job_id'])) {
$jobId = $_GET['job_id'];
require_once 'connect_to_mysql.php';
$sql = "DELETE FROM jobs WHERE job_id = ?";
$params = array($jobId);
$stmt = $link->prepare($sql);
$status = $stmt->execute($params);
if ($status == true) {
header("Location: edit_jobs.php");
}
else {
$error_info = $stmt->errorInfo();
$error_message = "failed to delete job: {$error_info[2]} - error code {$error_info[0]}";
require 'error.php';
}
}
else {
$error_message = "book id not specified";
require 'edit_jobs.php';
}
}
else {
}
?>
答案 0 :(得分:0)
我发现这段代码存在很多问题。第一 - 我同意以上关于漏洞的内容。然而,这是一个简单的解决方案只需将作业ID验证为整数,如果验证失败,则不执行SQL代码。
第二 - 我认为$ param = array($ jobId)不正确。您根本没有将作业变量传递给SQL代码......它为执行语句提供了一个空值。我清理了你的代码,不能保证这会工作,因为我看不到你的SQL语句,但这是一个更好的方法,应该正常工作......
# Include this before anything else...
require_once 'connect_to_mysql.php';
# Ditch the server GET validation check, waste of load time, store job ID in a variable off the bat
$jobId = $_GET['job_id'];
# Validate if the job is is numeric and not empty
if ((!empty($jobId)) || (is_numeric($jobId))
{
# Ditch the $sql variable for speed/memory, just include it in the prepare statement
# Note the limit statement - it's good practice to limit deletion queries to only one row
# if you are only deleting one row so additional data doesn't accidentally get deleted
$stmt = $link->prepare("DELETE FROM jobs WHERE job_id = ? LIMIT 1");
# This code prepares job ID as a parameterized query and tells the database to parse it as an int
$stmt->bind_param('i', $jobId);
# Execute and validate
$status = $stmt->execute($params);
if ($status == true)
header("Location: edit_jobs.php");
else
{
$error_info = $stmt->errorInfo();
$error_message = "failed to delete job: {$error_info[2]} - error code {$error_info[0]}";
require 'error.php';
}
}
else
{
$error_message = "Booking ID is not valid";
require 'edit_jobs.php';
}
# Make sure to close your database connection when finished...
答案 1 :(得分:-1)
你试过这个吗?
$jobId = $link->real_escape_string($jobId);
$sql = "DELETE FROM jobs WHERE job_id = $jobId";