在php函数中选择语句

时间:2016-06-01 13:32:39

标签: php mysql function select

我正在尝试创建一个函数,它将在mysql中进行查询并使用mysql_fetch_assoc输出。

问题是当我在循环内返回输出时它只输出第一个字段。同样,如果我将输出返回到循环之外,我只得到最后一个值。

无论如何都要绕过这个?

这是主页:

 
<?php
$dbhost = "localhost";
$dbuser = "widget_cms";
$dbpass = "cjclone123";
$dbdata = "widget_corp";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass, $dbdata);

if(mysqli_connect_errno()) {
    die("database connection failed: " .
        mysqli_connect_error() .
            " (" . mysqli_connect_errno() . ")"
    );
} else {
    echo "success!";
} 

Insert_Line_Into_subjects();

    $table = "subjects";

    $result = Output_Table($table);

    var_dump($result);

    echo (Display_Table($result));

    mysqli_free_result($result); 


?>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html lang="en">
 <head>
  <title>phpMysql</title>
 </head>
 <body>

    <ul>
     <form action="phpMysql.php" method="post">
     Menu Name: <input type="text" name="menuName" value=""><br>
     Position: <input type="text" name="pos" value=""><br>
     Visibility: <input type="text" name="vis" value=""><br>
     <input type="submit" name="submit" value="Create account"><br>
     </form>
    </ul> 

 </body>
</html>

<?php mysqli_close($connection); ?>

以下是我使用的所有功能:

function Insert_Line_Into_subjects(){

if (isset($_POST["submit"])) {
    global $connection; 

    $menu_name = ($_POST["menuName"]);
    $position = ($_POST["pos"]);
    $visibility = ($_POST["vis"]);

    $query1 = "INSERT INTO subjects ";
    $query1 .= "(menu_name, position, visible) ";
    $query1 .= "VALUES ('$menu_name', '$position', '$visibility')";
    $result = mysqli_query($connection, $query1);
    Check_SQL_Execution($result);
    return $result;
    }
}

    function Check_SQL_Execution($result) {
        global $connection;

    if (!$result) {
        die("<br>Database query failed: " . mysqli_error($connection));
    }
    }

    function Output_Table ($table) {
    global $connection; 

    $query1 = "SELECT * ";
    $query1 .= "FROM {$table}" ;
    $result1 = mysqli_query($connection, $query1);
    Check_SQL_Execution($result1);
    return $result1; 

}

    function Display_Table($result) {

        //if (isset($_POST["submit"])){
        $output = '';

        while ($row = mysqli_fetch_assoc($result)) {
        $output = $row["menu_name"];
        $output .= " ("; 
        $output .= $row["id"];
        $output .= ")";
    }
    return $output;
 }

我做错了什么?谢谢!

1 个答案:

答案 0 :(得分:4)

function Display_Table($result) {
    $output = '';
    while ($row = mysqli_fetch_assoc($result)) {
        $output .= $row["menu_name"];
        $output .= " ("; 
        $output .= $row["id"];
        $output .= ")";
    }
    return $output;
}