Table's name: grandTotal
(have two fields :defect_code and total)

defect_code total
LM 23
FM 15
DF 5

How this data can be an array like this
array("LM" >=23, "FM">=15,"DF">=5) using query? please help me..:S

Dani AI

Generated

Both and pointed the right direction: build an associative PHP array keyed by defect_code with total as the value. The OP's shown example used >= by mistake β€” PHP associative arrays use the => key operator. The loop answers using the old ext/mysql functions will work on older PHP, but ext/mysql is deprecated and removed in modern PHP versions.

A cleaner, modern approach is to use PDO and fetch the result as key=>value in one call. Example:

$pdo = new PDO('mysql:host=localhost;dbname=your_db;charset=utf8mb4', 'user', 'pass', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);

$stmt = $pdo->query('SELECT defect_code, total FROM grandTotal');
$array = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
$array = array_map('intval', $array); // totals as integers

If the table can contain multiple rows for the same defect_code, aggregate in SQL first so keys stay unique:

SELECT defect_code, SUM(total) AS total
FROM grandTotal
GROUP BY defect_code;

Quick tips: use prepared statements when injecting user input, set PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION for easier error handling, and explicitly set the connection charset. If you need the result for JavaScript, json_encode($array) produces a ready-to-use object. For PDO fetch options see the manual: PDOStatement::fetchAll. For a mysqli alternative, see mysqli_result::fetch_all.

Recommended Answers

All 4 Replies

Member Avatar for Member #120589

...

while($row = mysql_fetch_array($result)){
  $myarray[$row['defect_code']] = $row['total']; 
}
//check with:
print_r($myarray);

This should work:

<?php
# ...
# connection code
# ...

$q = mysql_query('select defect_code, total from grandTotal');
$a = array();
while($row = mysql_fetch_object($q))
{
    $a[$row->defect_code] = $row->total;
}

print_r($a); # display array
?>

bye :)

ooops ardav, I just saw your reply, sorry.. :D

Member Avatar for Member #120589

Aha, cereal you OOPed it. Nice. :)

Table's name: grandTotal
(have two fields :defect_code and total)

defect_code total
LM 23
FM 15
DF 5

How this data can be an array like this
array("LM" >=23, "FM">=15,"DF">=5) using query? please help me..:S

Thanks!! really appreciate

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.