在php中从数据库中获取数据

时间:2013-04-06 09:50:17

标签: php sqlite

我正在尝试根据userId从数据库中获取特定的详细信息。

问题是,它正在显示

,而不是提取数据
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);
}
?> 

任何人都可以帮帮我吗?

1 个答案:

答案 0 :(得分:0)

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

应该是:

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

您的脚本中没有$obj变量。