2013-04-09 28 views
1

若本功能保存的值:直接参数VS.在变量

function get_article_info(){ 
     $id = $_GET['id']; 
     $data = array(); 
     $q = "SELECT * FROM articles WHERE article_id = $id"; 
     $qry = mysql_query($q); 
     while($row = mysql_fetch_assoc($qry)){ 
      $data[] = $row; 
     } 
     return $data; 
    } 

是相同的,因为这一个:

function get_article_info2(){ 
     $id = $_GET['id']; 
     $data = array(); 
     $q = mysql_fetch_assoc(mysql_query("SELECT * FROM articles WHERE article_id = $id")); 

     while($row = $q){ 
      $data[] = $row; 
     } 
     return $data; 
    } 

如果我尝试使用get_article_info2我得到这个错误:

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 35 bytes) 

灿任何告诉我为什么它不工作? THX)

+0

你真的不应该使用'mysql_ *'函数,因为它们已被废弃,不再支持,请查看** PDO **或** mysqli **而不是 – Pankucins 2013-04-09 13:24:28

回答

2
$q = mysql_fetch_assoc(mysql_query("SELECT * FROM articles WHERE article_id = $id")); 

    while($row = $q){ 
     $data[] = $row; 
    } 

没有结束这种循环,因为你一旦前值分配给$ Q,它永远不会改变。所以同一行被重复添加到$ data中,最后脚本内存不足。

您必须分别调用每个记录的获取函数(如第一个代码所示)。

2

首先,你应该始终逃生或消毒你的SQL参数:

$sql = sprintf('SELECT * FROM articles WHERE article_id = %d', (int)$_GET['id']); 
$res = mysql_query($sql); 

其次,你应该执行mysql_fetch_assoc()循环;否则会造成死循环:

while (($row = mysql_fetch_assoc($req)) !== false) { 
    $data[] = $row; 
} 

这就是说,你应该停止使用旧mysql_*功能;改为使用PDO或mysqli,并利用准备好的语句的力量。

+0

Jack Y U无SQL注入警告? – 2013-04-09 13:37:22

+0

@Null没有提到参数应该被转义或消毒?我错过了什么? – 2013-04-09 13:54:38

+0

是的,你做得很好,但我认为它更好地告诉为什么要逃避或消毒参数.. :-)是和+1 – 2013-04-09 13:56:49