从另一个php文件调用方法

时间:2015-02-03 07:25:44

标签: php

因此,我尝试从头开始创建php方法。我的班级还没有完全上课,我还在努力。无论如何,我的问题似乎无法从我的数据库中获得我期望的值。这是我的代码片段:

file1.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>

我已经尝试在方法开头打印一条消息,看看它是否被调用但消息没有打印,所以我想知道,我在这里可能缺少什么?

1 个答案:

答案 0 :(得分:1)

我认为你的代码中有很多错误...我猜你不会使用OOP(类)所以我修改了一个应该工作的例子..如果没有,请发布错误消息

file1.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>

相关问题