从另一个 php 文件调用方法


Calling method from another php file

所以我正在尝试从头开始创建php方法。我的课程还不完全是课程,我仍在努力。无论如何,我的问题是我似乎无法从数据库中获得我期望的值。这是我的代码片段:

文件1.php

<?php function dbConnect() {
$connection = mysqli_connect("localhost", "music_root", "", "music");
if($connection->connect_error) {
    return null;
}
return $connection;}
function getCategory() {
$cn = dbConnect();
if($cn == null) {
    echo "Failed to connect to database.";
} else {
    $fetchQuery = mysqli_query($cn, "SELECT * FROM tbl1 ORDER BY 'Name'") or die(mysqli_error($cn));
    if(mysqli_num_rows($fetchQuery) > 0) {
        while($item = mysqli_fetch_array($fetchQuery)) {
            return $item["Name"];
        }
    }
}} ?>

这是我如何在 file2 中调用上述方法的代码片段.php

<?php ini_set("display_errors", 1);
  include_once("file1.php");
  $con = dbConnect();
  $updateStat = false;  ?>
<div>
    <label>Genre</label>
    <select id="genre" name="genre" value="Please select genre">
    <option value="<?php $con->getCategory() ?>"></option>
    </select>
</div>

我尝试在方法开始时打印一条消息,以查看它是否被调用,但消息也没有打印,所以我想知道,我在这里可能错过了什么?

我认为您的代码中有服务器错误...我想,您不使用OOP(类),所以我修改了一个应该可以工作的示例..如果没有,请发布错误消息

文件1.php

function getCategory($cn) {
   $out = array();
   if($cn == null) {
       echo "Failed to connect to database.";
   } else {
      $fetchQuery = mysqli_query($cn, "SELECT * FROM tbl1 ORDER BY 'Name'") or die(mysqli_error($cn));
      if(mysqli_num_rows($fetchQuery) > 0) {
        while($item = mysqli_fetch_array($fetchQuery)) {
           $out[] = $item["Name"];
        }
      }
      return $out;
   }
}

fil2.php

<?php 
    ini_set("display_errors", 1);
    require_once("file1.php");
    $con = dbConnect();
    $updateStat = false;
    $res = getCategory($con);
 ?>
 <div>
<label>Genre</label>
<select id="genre" name="genre" value="Please select genre">
<?php          
     foreach($res as $cat):
?>
<option value="<?php echo $cat ?>"><?php echo $cat ?></option>
<?php endforeach;?>
</select>