php代码循环数据库

时间:2016-08-06 11:13:37

标签: php sql database postgresql

我是初学者使用php,我有一个包含下表的postgres数据库:

--------------------------------------------------
| Phone_Number| User_ID| file_ID|  file_Path     |
--------------------------------------------------
| 123456789   | 12345  | abc123 | /picture_22.jpg|
--------------------------------------------------
| 987654321   | 67890  | xyz567 | /voice_33.mp3  |
--------------------------------------------------

我想循环遍历每一行,阅读file_ID 将它附加到url的末尾,转到url获取结果,这是一个下载链接,我不知道如何实现。我感谢任何帮助/帮助。

P.S:这是我不完整的代码:

<?PHP
ini_set('error_reporting',E_ALL);

$website = "https://website.com;

//Connect to Database
$con = pg_connect( "postgres://................."  );

$query = "SELECT * FROM userdata";
$results = pg_query($con, $query);
$row_users = pg_fetch_array($results);

while ($row_users = pg_fetch_array($results)) {

    $fileID =    <---------------- Not sure what goes here
    $filePath = file_get_contents('$website/.getFile?file_id=.fileID');
    $fixedPath = str_replace("\\","","$filePath");

}

pg_close($con); 
?>

4 个答案:

答案 0 :(得分:1)

<?PHP
ini_set('error_reporting',E_ALL);

$website = "https://website.com;

//Connect to Database
$con = pg_connect( "postgres://................."  );

$query = "SELECT * FROM userdata";
$results = pg_query($con, $query);
# NOT NEEDED You are losing a row here $row_users = pg_fetch_array($results);

while ($row_users = pg_fetch_array($results)) {

    $fileID =   $row_users['file_ID']; # This is what goes here
    $filePath = file_get_contents("$website/.getFile?file_id={$fileID}");
    $fixedPath = str_replace("\\","","$filePath");

}

pg_close($con); 
?>

除了标记为获取文件ID而需要进行的更改之外,我还在代码中标记了一个小错误,导致您丢失了一行数据。并且还在file_get_contents调用中使用您的变量。

在这里使用pg_query很好,但是如果你需要使用参数,请使用pg_query_params

答案 1 :(得分:1)

我认为问题在于单引号

$fileID =   $row_users['file_ID'];
$filePath = file_get_contents($website."/getFile?file_id=".$fileID);
$fixedPath = str_replace("\\","",$filePath);

我认为您错过了变量$fileID的“$”。另外,单引号内的语句不会被php解释器处理,因此$filePath没有得到正确的值

答案 2 :(得分:0)

我认为可以:

$fileID = $row_users['file_ID'];
$filePath = file_get_contents("$website/.getFile?file_id=$fileID");

答案 3 :(得分:0)

<?PHP
    ini_set('error_reporting',E_ALL);

    $website = "https://website.com;

    //Connect to Database
    $con = pg_connect( "postgres://................."  );

    $query = "SELECT * FROM userdata";
    $results = pg_query($con, $query);
    $row_users = pg_fetch_array($results);

     while ($row_users = pg_fetch_array($results)) {

        $fileID = $row_users["file_ID"];
        $filePath = file_get_contents("$website/getFile?file_id=" . $fileID);
        $fixedPath = str_replace("\\","","$filePath");

      }

     pg_close($con); 
?>