簡體   English   中英

從數據庫中獲取數據以創建表-PHP

[英]Fetch data from database to create a table - PHP

我創建了一個從數據庫中檢索數據的函數,以及一個將數據放入表中的函數。

function get_order()
{
    $order_query = "SELECT order_number From tbl_order_header";
    $data = mysqli_query($con, $order_query);
    $order = array();
    while ($object = mysqli_fetch_object($data))
    {
        $order[] = $object;
    }
    mysqli_close($con);
    return $order;
}

function get_table()
{
    $table_str = '<table>';
    $get_orders = get_order();
    foreach ($get_orders as $get_order) 
    {
        $table_str .= '<td>';
        $table_str .= '<td>'.$get_order->order_number.'</td>';
        $table_str .= '</td>';
    }
    $table_str .= '</table>';
    return $table_str;

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
 <?php echo get_table();?>
</body>
</html>

但是我收到如下錯誤消息。

line 8: $data = mysqli_query($con, $order_query);
Warning: mysqli_query() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\cmg-logistics\Testing.php on line 8

line 10: while ($object = mysqli_fetch_object($data))

Warning: mysqli_fetch_object() expects parameter 1 to be mysqli_result, null given in C:\xampp\htdocs\cmg-logistics\Testing.php on line 10

line 14: mysqli_close($con);

Warning: mysqli_close() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\cmg-logistics\Testing.php on line 14

我該如何解決錯誤?

這是因為未定義$ con。 嘗試在函數內傳遞$ con。

$con = mysqli_connect(HOST, USER, PASS, DB_NAME);

可能是您的連接變量問題。

這樣連接

//db connection

global $conn;

$servername = "localhost";  //host name

$username = "username"; //username

$password = "password"; //password

$mysql_database = "dbname"; //database name

//mysqli prepared statement 

$conn = mysqli_connect($servername, $username, $password) or die("Connection failed: " . mysqli_connect_error());

mysqli_select_db($conn,$mysql_database) or die("Opps some thing went wrong");

函數內部應該是

function get_order()
{
   global $conn;

 }

您得到的所有錯誤都是警告,而不是錯誤。 如果您的PHP代碼有錯誤,它將返回錯誤狀態500 INTERNAL SERVER ERROR 您可以使用以下命令禁用警告。

// Turn off all error reporting
error_reporting(0);
ini_set("display_errors", "0");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM