使用数据库中的列填充数组

时间:2016-02-12 15:00:44

标签: php mysql arrays

我需要使用从数据库中获取的一些数据填充数组。我的数据库表如下所示:

Tablename

ID | PROFILEID  |    PAGEID   | VOTE
------------------------------------
1  | 1563187610 | /example.php| 1
2  | 1563187610 | /example.php| 2
3  | 1946357685 | /example.php| 1
------------------------------------

对于我尝试使用的每个代码,我总是得到一个类似于Array ( )

的数组

这是我用来填充数组的代码:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$sql = "SELECT FROM `Tablename`";
$result = mysql_query($sql);

$var = array();
while ($row = mysql_fetch_array($result)) {
  $var[] = $row['PROFILEID'];
}

print_r($var);
$conn->close();

?>

更新1

$sql = "SELECT * FROM `Tablename`";
$result = mysqli_query($sql, $conn);

$var = array();
while ($row = mysqli_fetch_array($result)) {
  $var[] = $row['PROFILEID'];
}

print_r($var);

仍然会出现Array()问题。

如果我把“or die(mysqli_error($conn))”它没有说什么,我有一个空白的屏幕

解决

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}



$sql = "SELECT * FROM `Tablename`";
$result = $conn->query($sql);
$var = array();

if ($result->num_rows > 0) {
    // output data of each row
    while ($row = mysqli_fetch_array($result)) {
        $var[] = $row["PROFILEID"];
    }
} else {
    echo "0 results";
}

print_r ($var);
$conn->close();

2 个答案:

答案 0 :(得分:4)

您必须使用mysqli个函数而不是mysql_ *。此外,您需要*声明中的SELECT

$sql = "SELECT * FROM `Tablename`";
$result = mysqli_query($sql, $conn);

$var = array();
while ($row = mysqli_fetch_array($result)) {
  $var[] = $row['PROFILEID'];
}

答案 1 :(得分:1)

尝试这样做:

$('#test-container').html(data);

或者:

$var = array();
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
  $var[] = $row['PROFILEID'];
}