dougaoxian8922 2016-08-11 11:13
浏览 68
已采纳

迭代获取的SQL数据

I am adding a database to my event website with the webpages mon-sun each with its own SQL table. Each page can have any number of events. The table has 6 columns (ID,name,club,location,host,description). Currently I am using a tiresome method to call the data. I'm looking for an addition to my code so that calling the data is a bit more automated. My code so far.

<?php
  $dbhost  = 'localhost';    
  $dbname  = 'events';   
  $dbuser  = 'max';   
  $dbpass  = '';   
  $appname = "Dundaah"; 

  $connection = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
  if ($connection->connect_error) die($connection->connect_error);

  function queryMysql($query)
  {
    global $connection;
    $result = $connection->query($query);
    if (!$result) die($connection->error);
    return $result;
  }
  $row = queryMysql("SELECT * FROM monday WHERE ID=1");
  $one = $row->fetch_array(MYSQLI_ASSOC);
  $row2 = queryMysql("SELECT * FROM monday WHERE ID=2");
  $two = $row2->fetch_array(MYSQLI_ASSOC);

?>

Then to call for the first event I use.

<?php echo ucwords(strtolower($one['name']));?>
<?php echo ucwords(strtolower($one['club']));?>
<?php echo ucwords(strtolower($one['location']));?>
<?php echo ucwords(strtolower($one['host']));?>
<?php echo ucwords(strtolower($one['description']));?>

For the second event I use the same method but I'm looking for a way to loop through instead of declaring a new fetch array every time. Thank you.

</div>
  • 写回答

3条回答 默认 最新

  • duanpo1498 2016-08-12 04:37
    关注

    Got it.

    $query = "SELECT * FROM events WHERE day='mon'";
    
    $result = $conn->query($query);
    if (!$result) die($conn->error);
    
    $rows = $result->num_rows;
    $j = 0;
    
    $name_array='';
    $club_array='';
    $location_array='';
    $host_array='';
    $description_array='';
    
    while ($j < $rows )
    {
    $result->data_seek($j);
    $row = $result->fetch_array(MYSQLI_ASSOC);
    
    $event_name = $row['name'];
    $event_club = $row['club'];
    $event_location = $row['location'];
    $event_host = $row['host'];
    $event_description = $row['description'];
    
    $name_array[]=$event_name;
    $club_array[]=$event_club;
    $location_array[]=$event_location;
    $host_array[]=$event_host;
    $description_array[]=$event_description;
    
    ++$j;
    }

    echo $name_array[0];
    echo $club_array[0];
    echo $location_array[0];
    echo $host_array[0];
    echo $description_array[0];

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?