"Undefined Variable" 尝试读取行时

"Undefined Variable" while trying to read rows

我正在尝试读取一堆行并在没有通常 "ARRAY =>" 废话的情况下显示它们,但我得到的只是这个错误

Notice: Undefined variable: data in C:\xampp\htdocs\sql.php on line 0

这是我的代码:

<?php virtual('/Connections/TDBS_local.php');
$query = "SELECT sub_category FROM sub_category WHERE main_category_id = 2 ";
$result = mysqli_query($TDBS_local, $query);
if ($result = mysqli_query($TDBS_local, $query)) {

/* fetch associative array */
if($row = mysqli_fetch_assoc($result)) {
    $data = unserialize($row['sub_category']);
}

/* free result set */
mysqli_free_result($result);
}

 print "<pre>";
 print_r($data);
 print "</pre>";
?>

我哪里错了?

我认为你必须使用 require 或 include 而不是 virtual:

<?php
require('Connections/TDBS_local.php');
$data = '';
$query = "SELECT sub_category FROM sub_category WHERE main_category_id = 2 ";
$result = mysqli_query($TDBS_local, $query);
if ($result = mysqli_query($TDBS_local, $query)) {

/* fetch associative array */
if($row = mysqli_fetch_assoc($result)) {
    $data = unserialize($row['sub_category']);
}

/* free result set */
mysqli_free_result($result);
}

 print "<pre>";
 print_r($data);
 print "</pre>";
?>

以下是使用 pdo、mysqli 和 mysql

的方法

MYSQL我

    $con=mysqli_connect("localhost","username","password","dbname");

    $sql="SELECT sub_category FROM sub_category WHERE main_category_id = 2";

    $result=mysqli_query($con,$sql);

    $new_array = array();

    while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
        $new_array[] = $row;
    }
    print_r($new_array);

    mysqli_free_result($result);

    mysqli_close($con);

MYSQL

mysql_connect("localhost","username","password");
mysql_select_db("dbname"); 

$result = mysql_query("SELECT sub_category FROM sub_category WHERE main_category_id = 2");
$new_array = array();
while ($row = mysql_fetch_array($result)) {
    $new_array[] = $row;
}
print_r($new_array);

PDO

$pdo = new PDO('mysql:host=localhost;dbname=dbname', 'username', 'password');

$statement = $pdo->query("SELECT sub_category FROM sub_category WHERE main_category_id = 2");
$new_array = array();
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
    $new_array[] = $row;
}
print_r($new_array);