2013-04-06 74 views
0

我想從基於userId的數據庫中獲取特定的細節。在php中從數據庫中獲取數據

的問題是不是獲取數據,它顯示

line 2 line 3{"posts":[]}. 

我使用下面的代碼,

<?php 
@ob_start(); 
/* require the user as the parameter */ 

if(isset($_GET['user']) && intval($_GET['user'])) 
{ 
print "line 2"; 
/* soak in the passed variable or set our own */ 
$number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default 
$format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default 
$user_id = intval($_GET['user']); //no default 

print "line 3"; 

/* connect to the db */ 
$link = mysql_connect('localhost','username','password') or die('Cannot connect to the DB'); 
mysql_select_db('database',$link) or die('Cannot select the DB');   

/* grab the posts from the db */ 
$query = "SELECT * FROM tablename WHERE userId= '".$obj->{'userId'}."'"; 

$result = mysql_query($query,$link) or die('Errant query: '.$query); 


$posts = array(); 

if(mysql_num_rows($result)) 
{   
    while($post = mysql_fetch_assoc($result)) 
    {     
     $posts[] = array('posts' =>$post); 
    } 
} 

/* output in necessary format */ 
if($format == 'json') 
{ 
    header('Content-type: application/json'); 
    echo json_encode(array('posts'=>$posts)); 
    exit(); 
} 
else 
{ 
    header('Content-type: text/xml'); 
    echo '<posts>'; 
    foreach($posts as $index => $post) 
    { 
     if(is_array($post)) 
     { 
      foreach($post as $key => $value) 
      { 
       echo '<',$key,'>'; 
       if(is_array($value)) 
       { 
        foreach($value as $tag => $val) 
        { 
         echo '<',$tag,'>',htmlentities($val),'</',$tag,'>'; 
        } 
       } 
       echo '</',$key,'>'; 
      } 
     } 
    } 
    echo '</posts>'; 
} 

/* disconnect from the db */ 
@mysql_close($link); 
} 
?> 

任何一個能幫助我嗎?

+0

嘗試在while循環中添加print_r($ post)並向我們顯示結果... – 2013-04-06 09:52:38

+0

您在哪裏設置'$ obj - > {'userId'}'?不應該只是'$ user_id'嗎? – Barmar 2013-04-06 09:55:02

+0

@Mohit Mehta:它正在打印{「posts」:[]} – DevAndro 2013-04-06 10:23:59

回答

0
$query = "SELECT * FROM tablename WHERE userId= '".$obj->{'userId'}."'"; 

應該是:

$query = "SELECT * FROM tablename WHERE userId= '".mysql_real_escape_string(userId)."'"; 

有一個在你的腳本沒有$obj變量。

+0

我在其他php文件中設置了$ obj - > {'userId'}。 – DevAndro 2013-04-06 10:22:31

+0

輸出'$ query'的值並確保它包含你期望的內容。問題是您的查詢沒有返回任何行。 – Barmar 2013-04-06 10:30:05