drjtua5953 2017-02-07 11:09
浏览 64
已采纳

PHP函数并在html中调用它

I'm very new to PHP, so please excuse me if this is a silly question.

I have a separate PHP file which contains a few functions, they were originally in the same document as the HTML site, but I wanted to move them to their own PHP file.

Originally in the HTML I had PHP connect to an SQL server and then ran an SQL Query, then I wanted the results of that query to populate a drop down box, so each row in the returned query was an , this worked great but when I move all that functionality to the separate PHP file it's no longer working.

I have one function now, which connects to the database, runs the query and then attempts to write the output, but I think it's this section that's causing the problem.

I have included this new PHP function file.

Here's the function:

function results() {
    $connection = db();

    $smt = $connection->prepare('SELECT * FROM tblResults');
    $smt->execute();
    $data = $smt->fetchAll();

    foreach ($data as $row) {
    echo "<option>".$row['Score']."</option>";
    }
}

And in the HTML I have this code to call the function:

<select class="selectpicker" data-live-search="true" data-width="auto">
    <?php results(); ?>
</select>

As I said, I'm new to PHP so I'm sorry if this is an obvious error or if the format is wrong.

Any help would be greatly appreciated.

  • 写回答

6条回答 默认 最新

  • douweng9427 2017-02-07 11:52
    关注

    I'm not sure what the issue was, but I've managed to fix it.

    One of the functions was a connection to the database and it had a session_start(); within it, and although I was including this function php file at the beginning, it looks like I have to also put in a session_start(); at the beginning of my function results(); so it now looks like this.

    function results() {
    session_start();
    
    //databse connection Sting
    $connection = new PDO("sqlsrv:server=localhost;Database=Results", "user", "password"); 
    
    $smt = $connection->prepare('SELECT * FROM tblResults');
    $smt->execute();
    $data = $smt->fetchAll();
    
    foreach ($data as $row) {
    echo "<option>".$row['Score']."</option>";
    }
    

    }

    Again, I'm not sure why I need to establish the session_start but it seems to have solved the issue.

    Thank you for all your responses, you helped me break the issue down.

    Cheers!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料