1

I am trying to load a list of IDs into a PHP array which I can loop through. The SQL query I am using returns 283 rows when I run it in PHPMyAdmin. However, when I run the following PHP script, it only returns a single row (the first row). How can I modify my code to include all the rows from the resulting SQL query in my PHP array?

Code:

//Get active listing IDs 
$active = "SELECT L_ListingID FROM `markers`";
$active = mysql_query($active) or die(mysql_error());

if(is_resource($active) and mysql_num_rows($active)>0){
$row = mysql_fetch_array($active);
print_r($row);
};

Thanks,

3 Answers 3

7

Using mysql_fetch_array will return only the first row and then advance the internal counter. You need to implement it as part of a loop like the following to get what you want.

while($row = mysql_fetch_array($active)) {
 // Your code here
}

Keep in mind that mysql_ functions are now also deprecated and slated to be removed in future version of php. Use mysqli_ functions or PDO.

Sign up to request clarification or add additional context in comments.

1 Comment

How could I write the same function using PDO instead?
4

In PDO it's rather straight forward:

$rows = $conn->query($active)->fetchAll();

See PDO::queryDocs and PDOStatement::fetchAllDocs.

Comments

2

With mysqli you would use mysqli_result::fetch_all and with PDO there's PDOStatement::fetchAll to fetch all rows into an array.

Code for mysqli

$sql = "SELECT L_ListingID FROM `markers`";
$result = $mysqli->query($sql);
if ($result !== false) {
    $rows = $result->fetch_all();
}

with PDO it's nearly the same

$sql = "SELECT L_ListingID FROM `markers`";
$result = $pdo->query($sql);
if ($result !== false) {
    $rows = $result->fetchAll();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.