简体   繁体   中英

SELECT COUNT(a.id) AS id… => Result array is empty! [PHP, MySQL]

I'm having trouble with some PHP since yesterday, looked through the web and had the stupid feeling that I'm missing something important.

Using mysql_fetch_object usually, tried it with mysql_fetch_array though (did not help). Here's the part of the code which gives me an headache:

public static function get_datacenter_by_id($id) {
$result = mysql_query("SELECT COUNT(rack.id) AS Racks, COUNT(device.id) AS Devices, COUNT(card.id) AS Cards, COUNT(port.id) AS Ports 
          FROM datacenter, rack, device, card, port, location, building 
          WHERE location.id = building.location_id AND
          building.id = datacenter.building_id AND
          datacenter.id = '.$id.' AND
          rack.id = device.rack_id AND
          device.id = card.device_id AND
          (card.id = port.card_id1 OR
          card.id = port.card_id2)") or die ("Error in query: ".mysql_error());

$array = array();

while($row = mysql_fetch_object($result)) {
    $array[] = array($row->Racks, $row->Devices, $row->Cards, $row->Ports);                     
}

return $array;
}

$array is used in another .php file, but using print_r $array already shows you, that the array stays empty (0) . I'm quite sure that the error appears in this block of code, could " COUNT (x) AS y " be at fault?

PS: The MySQL Query works, tested it via Workbench before. I'd appreciate some good adivce! :-)

Have a nice day!

Instead of using it like this

while($row = mysql_fetch_object($result)) {
$array[] = array($row->Racks, $row->Devices, $row->Cards, $row->Ports);                     
}

You should do this

$row = mysql_fetch_object($result)
$array[] = $row->Racks;
$array[] = $row->Devices;
$array[] = $row->Cards;

Because you are fetching 1 record and using it in while is causing problem

Isn't this as simple as:

$result = mysql_query("SELECT COUNT(rack.id) AS Racks, COUNT(device.id) AS Devices,     COUNT(card.id) AS Cards, COUNT(port.id) AS Ports 
      FROM datacenter, rack, device, card, port, location, building 
      WHERE location.id = building.location_id AND
      building.id = datacenter.building_id AND
      datacenter.id = '" . $id . "' AND
      rack.id = device.rack_id AND
      device.id = card.device_id AND
      (card.id = port.card_id1 OR
      card.id = port.card_id2)") or die ("Error in query: ".mysql_error());

Note the modification from '.$id.' to '" . $id . "'. Your query is looking for a data centre ID of '.$id.'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM