注意:未定义的索引:第3行的C:\ xampp \ htdocs \ libsys \ edit.php中的id

时间:2014-10-05 00:08:59

标签: php mysql

我知道这是一个新手问题,但是这个错误一直困扰我一段时间,请帮助ty

<?PHP
include "configdb.php";
$id = $_POST['id'];

if (isset($id))
{
    $newName = $id;
    $sql = 'SELECT * FROM booklist WHERE id = $id';
    $res = mysqli_query($connect, $sql) or die("Could not update".mysql_error());
    $row = mysqli_fetch_row($res);
    $id = $row[0];
    $title = $row[1];
    $author = $row[2];
    $ISBN = $row[3];
    $category = $row[4];
    $image_upload = $row[5];
    $image_upload2 = $row[6];

}
?>

2 个答案:

答案 0 :(得分:1)

目前尚不清楚,但我相信您应该在$id = $_POST['id']声明中移动if

,代码应为:

<?PHP
include "configdb.php";


if (isset($_POST['id']))
{
    $id = $_POST['id'];
    $sql = "SELECT * FROM `booklist` WHERE `id` = '$id'";
    $res = mysqli_query($connect, $sql) or die("Could not update".mysql_error());
    $row = mysqli_fetch_row($res);
    $id = $row[0];
    $title = $row[1];
    $author = $row[2];
    $ISBN = $row[3];
    $category = $row[4];
    $image_upload = $row[5];
    $image_upload2 = $row[6];
}
?>

额外信息

如果我认为这个问题是关于从图书清单中获取图书ID,那么在db中运行查询以返回结果,那么更好的代码将是这样的:

<?PHP
include "configdb.php";


if (isset($_POST['id']))
{
  $id = $_POST['id'];
  $sql = mysqli_query($connect, "SELECT * FROM booklist WHERE id = $id") or die("Could not update".mysql_error());
  $rows = mysqli_num_rows($sql); // get the number of returning rows (0 means no query match found, > 0 means a query match found)
  if($rows > 0)
  {
    while($i = mysqli_fetch_assoc($sql))
    {
      $book_id        = $sql[0];
      $book_title     = $sql[1];
      $author         = $sql[2];
      $ISBN           = $sql[3];
      $category       = $sql[4];
      $image_upload   = $sql[5];
      $image_upload2  = $sql[6];

      // the rest of your code and what you want to do with the result....
    }
  }
  eles // no results found message
  {
  echo 'Sorry, no results found.';
  } // end of else 
}
?>

另请注意,您可以使用列名而不是$sql[0], $sql[1], $sql[3]

因此,如果您的第一个表格列的名称为book_id,那么它可以是

$book_id = $sql['book_id'];代替$book_id = $sql[0];。当您在代码中工作时,这更容易处理,因此您不必返回到数据库的第四位以检查列的索引。此外,当您更新代码或与他人共享代码时,它会对您有所帮助。

答案 1 :(得分:1)

您的SQL语句未检查表单中的数字ID值,而是检查字符串$id。需要改变:

'SELECT * FROM booklist WHERE id = '. $id