简体   繁体   中英

Best practices for querying an entire row in a database table? (MySQL / CodeIgniter)

Sorry for the novice question!

I have a table called cities in which I have fields called id, name, xpos, ypos. I'm trying to use the data from each row to set a div's position and name.

What I'm wondering is what's the best practice for dynamically querying an unknown amount of rows (I don't know how many cities there might be, I want to pull the information from all of them) and then passing the variables from the model into the view and then setting attributes with it?

Right now I've 'hacked' a solution where I run a different function each time which pulls a value using a query ('SELECT id FROM cities;'), then I store that in a global array variable and pass it into view. I do this for each var so I have arrays called: city_idVar, city_nameVar, city_xposVar, city_yposVar then I know that the city_nameVar[0] matches up with city_xposVar[0] etc. Is there a better way?

I'm not sure what you mean by "set a div's position", but here is an attemp:

controller

$data = array(
    'cities' => $this->cities_model->get_cities_info()
);
$this->load->view('view',$data);

model

function get_cities_info()
{
  return $this->db->query('SELECT id, name, xpos, ypos FROM cities')->result();
}

view

<?php foreach($cities as $city) : ?>
<div style="position:absolute;top:<?= $city->ypos ?>;left:<?= $city->xpos ?>">
<?=  $city->name ?>
</div>
<?php endforearch ?>

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