开发者

fetching data from same table multiple times?

I want to fetch some data from a database table and use it in different sections on a page, currently I'm making multiple queries to fetch data from table, for example i want to fetch video path and description from videos table. I've two functions,

function get_photo_path($id){
SELECT path from videos w开发者_C百科here id = $id;
return path;
}

function get_video_description($id){
SELECT desc from videos where id = $id;
return desc;
}

I'm just wondering if I can make a single function to fetch path and description together and use if in different sections, for example

<div><? //get path ?></div>
<div>some other data</div>
<div><? //get description ?></div>


function get_data($id) {
    $sql = "select path, desc from videos where id = $id;";
    $res = mysql_query($sql) or die(mysql_error());

    $data = mysql_fetch_assoc($res);

    return $data:
}

$data = get_data($id);

?>

<div><?php echo $data['path'] ?></div>
<div><?php echo $data['desc'] ?></div>


Don't make it more complicated than it needs to be. :)

$video = /* SELECT * FROM `videos` WHERE `id` = $id */;

<div><?php echo $video['path']; ?></div>
<div>some other data</div>
<div><?php echo $video['description']; ?></div>


Couldn't you have this at the top of the page:

<?
    // this isn't real mysql, so adjust to fit how you connect
    $sql = "SELECT path, desc FROM videos WHERE id = $id";
    $row = mysql_fetch_assoc(mysql_query($sql));
?>

Then, when you want to print out the variables:

<div><?= $row['path']; ?></div>
<div>some other data</div>
<div><?= $row['desc']; ?></div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜