简体   繁体   English

从同一张表中多次提取数据?

[英]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 where 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM