简体   繁体   English

如何解决未定义索引:在php中显示数据库检索值时的注意事项

[英]How to resolve Undefined index: Notice when displaying database retrieved value in php

I'm getting an undefined index notice, but can't figure out how to fix it. 我收到未定义的索引通知,但无法弄清楚如何解决它。

Below is the code which is generating the error: 下面是生成错误的代码:

<?php

include 'dbconfig.php';

$id;

if(isset($_POST['Tid']))
{
  $id=$_POST['To_ID'];
  echo "selected value:".$id;
  $query="select 'ID','Name' from  where ID='$id'";
  $result=sqlsrv_query($conn,$query);
  $a=sqlsrv_num_rows($result);
  echo $a;

  if(!$result)
  {
    echo "Query execution failed"; 
  }   
  else {
    while($row = sqlsrv_fetch_array($result))
    {
       print_r($row['ID'].$row['Name']);
    }
  } 
} 
else {
  echo "Post variable not set";
}

I am getting error on the line here- 我在这里遇到错误-

print_r($row['ID'].$row['Name']);

And also i am verified database columns the columns ID and Name is present in the database and the select query is also executing well when i tried seperately. 另外,我还通过数据库中的ID和Name列验证了数据库列,当我分别尝试时,select查询也执行得很好。

Even though the filed name ID and Name exists i am getting Undefined Index ID and Name Error. 即使文件名ID和名称存在,我也得到未定义的索引ID和名称错误。

Please help me to resolve this error. 请帮助我解决此错误。

Thanks in advance. 提前致谢。

You are using the wrong kind of quotes and you are missing the table name: 您使用了错误的引号,并且缺少表名:

$query="select 'ID','Name' from  where ID='$id'";

Should be: 应该:

$query="select ID,Name from table_name where ID='$id'";

Or, if the column names need to be quoted you need block-quotes in sql server: 或者,如果列名需要用引号引起来,则需要在sql server中使用块引号:

$query="select [ID],[Name] from [table_name] where [ID]='$id'";

Also note that you have an sql injection problem. 另请注意,您有一个sql注入问题。 Ideally, you should use a prepared statement, but if the value of the ID is an integer, you can also do: 理想情况下,您应该使用准备好的语句,但是如果ID的值是整数,则还可以执行以下操作:

$id = (int) $_POST['To_ID'];
$query = "select ID,Name from table_name where ID='$id'";

try this: 尝试这个:

$query="select ID,Name from where ID='$id'";

$result=sqlsrv_query($conn,$query);


$a=sqlsrv_num_rows($result);
echo $a;

if(!$result)
{
echo "Query execution failed"; 
}    else {

for($i = 0; $i < $a; $i++)
{

print_r($row[$i]['ID'].$row[$i]['Name'].'<br/>');

}
} 
} else {
echo "Post variable not set";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM