从“id”列获取行值

时间:2011-11-01 12:35:02

标签: php

在下面的代码中,我想得到列“id”的行结果作为$ selectedmovieid的结果。 'commenid'是主键属性。很抱歉不知道如何正确使用mysql_fetch_assoc。

<?php
require ("connect-comment.php");
$deleteid=$_GET['commentid'];
$query1=mysql_query("SELECT id FROM comment WHERE commentid='$deleteid'");
$selectedmovieid= mysql_fetch_assoc($query1);
$query2=mysql_query("DELETE FROM comment WHERE commentid='$deleteid'");
header("Location: reload.php?id=$selectedmovieid");
?>

编辑1:我将在稍后进行安全注入,只需要正确的语法并获得正确的结果。所以这就是我到目前为止所做的:

<?php
require ("connect-comment.php");
$deleteid=$_GET['commentid'];
$query1=mysql_query("SELECT id FROM comment WHERE commentid='$deleteid'");
while ($selectedmovieid= mysql_fetch_assoc($query1))
{echo $selectedmovieid['id'];};
$query2=mysql_query("DELETE FROM comment WHERE commentid='$deleteid'");
header("Location: reload.php?id=$selectedmovieid");
?>

现在这对我没有多大意义因为我没有将正确的$selectedmovieid值解析为reload.php?id=

1 个答案:

答案 0 :(得分:0)

尝试更改

$deleteid=$_GET['commentid'];
// ...
header("Location: reload.php?id=$selectedmovieid");

$deleteid = mysql_real_escape_string($_GET['commentid']);
// ...
header("Location: reload.php?id={$selectedmovieid['id']}");

另外,正如Pekka正确建议的那样,请尝试阅读manual page for mysql_fetch_assoc()reading up on SQL injection

作为旁注,您应使用Location:标头重定向的相对路径。 RFC指定此字段应包含完整URL ,并且虽然许多浏览器将正确解释相对路径,但不应依赖此行为。换句话说,Location: reload.php?id=...应为Location: http://mysite.tld/reload.php?id=

编辑试试示例代码的完整版本:

<?php

  require ("connect-comment.php");
  $deleteid = mysql_real_escape_string($_GET['commentid']);

  // Added LIMIT 1 to the query, because you are only using one result
  if (!$query1 = mysql_query("SELECT `id` FROM `comment` WHERE `commentid` = '$deleteid' LIMIT 1")) {
    // Do NOT show the output of mysql_error() to the user in a production environment!
    exit("Something went wrong with query 1: ".mysql_error());
  } else if (mysql_num_rows($query1) < 1) {
    exit("No results from query 1");
  }
  $selectedmovieid = mysql_fetch_assoc($query1);
  $selectedmovieid = $selectedmovieid['id']; // $selectedmovieid now contains the id you want

  if (!$query2 = mysql_query("DELETE FROM `comment` WHERE `commentid` = '$deleteid'")) {
    // Do NOT show the output of mysql_error() to the user in a production environment!
    exit("Something went wrong with query 2: ".mysql_error());
  }

  // If we get this far, everything should be fine
  // You still need a full URL here though, not a relative path...
  header("Location: reload.php?id=$selectedmovieid");

?>