A shelf that falls off the wall usually comes down to one problem — wrong hardware for the weight. Get that right first and the rest is straightforward.
Light shelves can use drywall anchors. Heavy shelves need to hit studs. Anchors fail. Studs don't.
Hold the shelf at the desired height and mark the edge. Draw a level reference line. Run a stud finder and mark stud centers.
Drill pilot holes and drive screws into studs or set anchors. Check bracket is level before fully tightening. Slide shelf onto brackets and test with firm hand pressure.