2012-03-14 52 views
1

我有这段代码。这只是为了测试目的,所以你不需要告诉我使用参数绑定和准备好的语句和PDO来避免SQL注入。为什么PHP会为此代码发出未定义的变量消息?

foreach($dd->getElementsByTagName("ReportItem") as $elmt){ 
    foreach ($elmt->childNodes as $node){ 
     if($node->nodeName==="ModuleName") 
      $name = $node->nodeValue; 

      if($result=mysqli_query($conn,"select * from technology_info where name = $name")){ 
       if(mysqli_num_rows($result)==0){ 

        mysqli_query($conn,"insert into technology_info(id,name,tool_id) values(null,$name,'2')"); 
        //ERROR: Undefined variable: name 

       } 

      } 
     } 
} 

这是什么代码是为了完成:如果变量$name是已经在数据库中的值,什么也不做。否则,将其添加到数据库。

不过,我收到一条错误消息:注意:未定义的变量:在/var/www/teste/index5.php

名字我的意思是,变量那里。任何想法可能发生什么?

+0

呼应$名称= $节点 - >的nodeValue后的变量;看看输出是什么 – 2012-03-14 19:30:15

+0

以及如果说$名不总是设置。 – 2012-03-14 19:31:12

回答

3

因为$name只被设定if($node->nodeName==="ModuleName")。 if语句只适用于那一行,但它下面的代码(mysql语句)将继续运行。

1

$node->nodeValue可能是null,其设置$namenull。 PHP会呈现为未定义的。

+0

赋值上方的'if'语句会阻止此操作。 – thetaiko 2012-03-14 19:31:45

+0

另外'null'肯定是不一样的“不确定” – thetaiko 2012-03-14 19:33:12

+0

@thetaiko,检查'nodeName',不'nodeValue',和PHP的松动,有时呈现空为未定义。 – Jon 2012-03-14 19:34:33

0

好并不总是如$节点 - >节点名称不等于“模块名”,那么$ name变量永远不会被创建。尝试在你的循环之外定义你的$ name变量,甚至在你的if语句之外。

0

$名字超出范围。

尝试

foreach($dd->getElementsByTagName("ReportItem") as $elmt){ 
    foreach ($elmt->childNodes as $node){ 
     if($node->nodeName==="ModuleName"){ 
      $name = $node->nodeValue; 
      if($result=mysqli_query($conn,"select * from technology_info where name = $name")){ 
       if(mysqli_num_rows($result)==0){ 
        mysqli_query($conn,"insert into technology_info(id,name,tool_id) values(null,$name,'2')"); 
        //ERROR: Undefined variable: name 
       } 
      } 
     } 
    } 
} 
1

你忽略了一组花括号

foreach($dd->getElementsByTagName("ReportItem") as $elmt){ 
foreach ($elmt->childNodes as $node){ 
    if($node->nodeName==="ModuleName") 

    { // *** You left this out 

     $name = $node->nodeValue; 

     if($result=mysqli_query($conn,"select * from technology_info where name = $name")){ 
      if(mysqli_num_rows($result)==0){ 

       mysqli_query($conn,"insert into technology_info(id,name,tool_id) values(null,$name,'2')"); 
       //ERROR: Undefined variable: name 

      } 

     } 
    } 
} 
} 

也将需要大约$名称一些报价在您的查询。

相关问题