尝试读取行时出现“未定义的变量”

时间:2015-03-01 22:02:09

标签: php mysql variables mysqli undefined

我试图阅读一堆行并显示它们而没有通常的" ARRAY =>"废话,但我得到的只是这个错误

  

注意:未定义的变量:第0行的C:\ xampp \ htdocs \ sql.php中的数据

这是我的代码:

<?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>";
?>

我哪里错了?

2 个答案:

答案 0 :(得分:1)

以下是如何使用pdo,mysqli和mysql

的mysqli

    $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);

答案 1 :(得分:0)

我认为你必须使用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>";
?>