从数据库中获取数据以创建表 - PHP

时间:2016-06-15 03:52:13

标签: php html mysql

我创建了一个从数据库中检索数据的函数,以及一个将数据放入表中的函数。

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

如何解决错误?

3 个答案:

答案 0 :(得分:0)

这是因为没有定义$ con。尝试在函数内传递$ con。

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

答案 1 :(得分:0)

可能是您的连接变量问题。

像这样连接

//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;

 }

答案 2 :(得分:0)

您收到的所有错误都是警告,而不是错误。如果您的PHP代码出错,它将返回错误状态500 INTERNAL SERVER ERROR。您可以使用以下命令禁用警告。

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