Pasting this PHP breaks my page. Why?

Make sure you reference the global $wpdb variable first, otherwise PHP doesn’t know what $wpdb is or whether or not it has a get_results() method or a prefix property.

So just add global $wpdb; to fix it:

<?php 
global $wpdb;
$gallery_ids = $wpdb->get_results(
"SELECT gid FROM ".$wpdb->prefix."ngg_gallery ORDER BY gid ASC", ARRAY_A);
?>