使用PHP从MySQL数据库获取时不显示数据

时间:2017-04-08 04:42:19

标签: php html

我是stackoverflow的新手,所以如果我做错了,我很抱歉。

问题:我在PHP中用HTML创建了一个函数,但我不知道为什么我的数据没有显示。

这是代码:

<?php
<!-- here is `require blabla.php` -->
    function showName(){
            $sql="SELECT company_name FROM company WHERE 1";
            $result=mysqli_query($connection, $sql);
            if (!$result) {
                die('Invalid query: ' . mysqli_error());
            }
            $row=mysqli_fetch_array($result);
            $var=$row['company_name'];
            echo $var;
        }
?>

<!-- HTML Code -->

<td><b>Company Name: </b></td>
<td><input type="text" class="form-control" value="<?php showName(); ?>" id="name" required name="name"></td>

- 修改 -

myConnection.php

<?php
    $connection = mysqli_connect("localhost", "root", "", "pos");
    if (!$connection) {
        die("Database connection failed: " . mysqli_connect_error());
    }
    $db_select = mysqli_select_db($connection, "pos");
    if (!$db_select) {
        die("Database selection failed: " . mysqli_connect_error());
    }
?>

2 个答案:

答案 0 :(得分:0)

您忘记添加myConnection.php

<?php
function showName(){
        require 'myConnection.php';
        $sql="SELECT company_name FROM company WHERE 1";
        $result=mysqli_query($connection, $sql);
        if (!$result) {
            die('Invalid query: ' . mysqli_error());
        }
        $row=mysqli_fetch_array($result);
        $var=$row['company_name'];
        echo $var;
    }
?>

<!-- HTML Code -->

<td><b>Company Name: </b></td>
<td><input type="text" class="form-control" value="<?php showName(); ?>" id="name" required name="name"></td>

答案 1 :(得分:0)

<强> maincode.php

<?php

require_once 'myconnection.php' ;

function showName(){
    global $connection;
        $sql="SELECT company_name FROM company WHERE 1";
        $result=mysqli_query($connection, $sql);
        if (!$result) {
            die('Invalid query: ' . mysqli_error());
        }
        $row=mysqli_fetch_array($result);
        $var=$row['company_name'];
        echo $var;
    }
?>

<td><b>Company Name: </b></td>
<td><input type="text" class="form-control" value="<?php showName(); ?>" 
id="name" required name="name"></td>

<强> myconnection.php

<?php
$connection = mysqli_connect("localhost", "root","");
if (!$connection) {
    die("Database connection failed: " . mysqli_connect_error());
}
$db_select = mysqli_select_db($connection, "pos");
if (!$db_select) {
    die("Database selection failed: " . mysqli_connect_error());
}

?>

output