Shockrate
Shockrate

Reputation: 89

Populate an array with column from a database

I need to populate an array with some datas taken from a database. My DB Table looks like this:

Tablename

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

And with every code I try to use I always get an array that looks like: Array ( )

This is the code that I use to populate the 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();

?>

UPDATE 1

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

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

print_r($var);

still gives the Array() problem.

If I put the "or die(mysqli_error($conn))" it doesn't say anything and I have a blank screen

SOLVED

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

Upvotes: 2

Views: 1168

Answers (2)

Edu C.
Edu C.

Reputation: 408

try doing this:

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

Or:

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

Upvotes: 1

Kostas Mitsarakis
Kostas Mitsarakis

Reputation: 4747

You have to use mysqli functions instead of mysql_* . Also, you need the * in your SELECT statement.

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

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

Upvotes: 4

Related Questions