简体   繁体   中英

Fetch data from database to create a table - PHP

I have created a function to retrieve data from database and a function put data into a table.

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>

But I get an error message as below.

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

How do I resolve the error?

It is because the $con is not defined. try to pass $con inside the function.

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

may be your connection variable issue.

connect like this

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

inside the function should be

function get_order()
{
   global $conn;

 }

All the errors you are getting are warnings, not errors. In case of error in your PHP code, it will return error status 500 INTERNAL SERVER ERROR . You can disable the warnings using following commands.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM