循环查询和查找表。 mysql& PHP

时间:2015-12-24 19:23:22

标签: php mysql arrays loops

我在找出一个循环时遇到了一些困难。

他们并不是我的强项。 ;)

它使用了一个类"查找"作为一个看起来像这样的查找表:(为了简洁省略了很多行)

class lookup {
   protected $lookup = array(
    array('rider_count' => '1', 'heat_count' => '1', 'riders_in_heat_1' => '1'),
    array('rider_count' => '2', 'heat_count' => '1', 'riders_in_heat_1' => '2'),
    array('rider_count' => '3', 'heat_count' => '1', 'riders_in_heat_1' => '3'),
    array('rider_count' => '4', 'heat_count' => '1', 'riders_in_heat_1' => '4'),
    array('rider_count' => '5', 'heat_count' => '1', 'riders_in_heat_1' => '5'),
    array('rider_count' => '6', 'heat_count' => '1', 'riders_in_heat_1' => '6'),
    array('rider_count' => '7', 'heat_count' => '1', 'riders_in_heat_1' => '7'),
    array('rider_count' => '8', 'heat_count' => '2', 'riders_in_heat_1' => '4', 'riders_in_heat_2' => '4'),
    array('rider_count' => '9', 'heat_count' => '2', 'riders_in_heat_1' => '5', 'riders_in_heat_2' => '4'),
    array('rider_count' => '10', 'heat_count' => '2', 'riders_in_heat_1' => '5', 'riders_in_heat_2' => '5'),
    array('rider_count' => '11', 'heat_count' => '2', 'riders_in_heat_1' => '6', 'riders_in_heat_2' => '5'),
    array('rider_count' => '12', 'heat_count' => '2', 'riders_in_heat_1' => '6', 'riders_in_heat_2' => '6'),
    array('rider_count' => '13', 'heat_count' => '2', 'riders_in_heat_1' => '7', 'riders_in_heat_2' => '6'),
    array('rider_count' => '14', 'heat_count' => '2', 'riders_in_heat_1' => '7', 'riders_in_heat_2' => '7')
   );
  public function select ($field, $value)
  {
    $list = array();
    foreach ($this->lookup as $count)
    {
      if ($count[$field] == $value)
      {
        $list[] = $count;
      }
    }
    return $list;
  }
}

$classes = new lookup();

我的php:

      <?php

        // get entries for the event
      function getEntries($class_id, $limit, $offset)
      {
        global $db;
        $getentries = $db->prepare("SELECT entry_id FROM tbl_event_entries WHERE event_id = :event_id AND class_id = :class_id LIMIT :offset, :limit");
        $getentries->bindValue(':event_id', $_GET['event_id']);
        $getentries->bindValue(':class_id', $class_id);
        $getentries->bindValue(':limit', $limit);
        $getentries->bindValue(':offset', $offset);
        $getentries->execute();
        while ($r = $getentries->fetch(PDO::FETCH_ASSOC)) return $r['entry_id'];
      }
        // get count of entries per class
        // get classes for the event
        $geteventclasses = $db->prepare("SELECT class_id FROM tbl_event_classes WHERE event_id = :event_id");
        $geteventclasses->bindValue(':event_id', $_GET['event_id']);
        $geteventclasses->execute();
        while ($r = $geteventclasses->fetch(PDO::FETCH_ASSOC))
        {
        $getentriesperclass = $db->prepare("SELECT entry_id FROM tbl_event_entries WHERE class_id = :class_id AND event_id = :event_id");
        $getentriesperclass->bindValue(':class_id', $r['class_id']);
        $getentriesperclass->bindValue(':event_id', $_GET['event_id']);
        $getentriesperclass->execute();
        $r2count = $getentriesperclass->rowCount();
        $counts[$r['class_id']] = $r2count;
        }
          foreach ($counts as $class => $rider_count)
          {
            $list = $classes->select('rider_count', $rider_count);

            echo "class: ".  $class ."; ridercount: " . $list[0]['rider_count'] ."; heats: ". $list[0]['heat_count'] ." heats, consisting of :<br>\n";


            for ($i = 1; $i <= $list[0]['heat_count']; $i++)
            {
              if ($list[0]['heat_count'] > 0)
              {
                for ($rih = 1; $rih <= $list[0]['riders_in_heat_'.$i]; $rih++)
                {
                  $offset = 1;
                  echo "<li>Heat ". $i ." : ". getEntries($class, $list[0]['riders_in_heat_'.$i], $offset) ." </li>";
                }
                $offset = $offset + $list[0]['riders_in_heat_'.$i];
              }

            }
              echo "</ul>";
          }
       ?>

这将最终构建一个更新查询来分配&#34; heat_nbr&#34;和&#34; heat_position&#34;到每个entry_id。

任务是从class_id中取出rider_count并将其分解,这样我们每次热力赛最多只能有7名骑手,并且可以将骑手均匀地分配给每个热量。

查找是我们如何确定分布如何发生的。那部分看起来很完美。我只是坚持如何让每个骑手被分配到一个位置。

我尝试了几种不同的方法,这就像我得到的答案一样接近。

非常感谢正确方向的推动!

在此处查看我目前的输出结果:

http://home.garyeterry.com/midam/createheats.php?event_id=113

由于

表格结构:

CREATE TABLE IF NOT EXISTS `tbl_event_entries` (
 `entry_id` int(11) NOT NULL AUTO_INCREMENT,
 `event_id` int(1) DEFAULT NULL,
 `racer_id` int(4) DEFAULT NULL,
 `class_id` int(1) DEFAULT NULL,
 `racing_nbr` varchar(4) DEFAULT NULL,
 `machine_cc` int(2) DEFAULT NULL,
 `brand_id` int(1) DEFAULT NULL,
 `overall_finish` int(1) DEFAULT NULL,
 `xtra_int1` varchar(10) DEFAULT NULL,
 `heat_nbr` int(1) DEFAULT NULL,
 `heat_position` int(1) DEFAULT NULL,
 `heat_row` int(1) DEFAULT NULL,
 `heat_finish` int(1) DEFAULT NULL,
  PRIMARY KEY (`entry_id`),
  UNIQUE KEY `entry_id` (`entry_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=165 ;

2 个答案:

答案 0 :(得分:1)

尽我所能清理,可能不完美,但应该足以在正确的方向上轻推。

lookup类移至数据库表

在我看来,在这里将lookup类的意图移动到数据库表中会更好。想象一下这样的事情:

CREATE TABLE IF NOT EXISTS `tbl_lookup` (
 `lookup_id` int(11) NOT NULL AUTO_INCREMENT,
 `rider_count` int NOT NULL,
 `heat_count` int NOT NULL,
 `riders_in_heat_1` int NOT NULL,
 `riders_in_heat_2` int,
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

然后插入lookup类的所有数据。

使用JOIN&amp;第一个SQL查询中的GROUP BY

您需要确定特定事件和班级中的骑手数量。您可以加入tbl_event_classestbl_event_entries,然后GROUP BY tbl_event_entries.event_id来获取这些数量。

SELECT tec.class_id, tec.event_id, COUNT(tee.event_id) AS entries_per_class
FROM tbl_event_classes tec
JOIN tbl_event_entries tee ON tee.event_id = tec.event_id
WHERE tec.event_id = :event_id
GROUP BY tee.event_id

清理PHP

现在您的PHP代码应该更容易理解。一个主要查询,用于获取每个类每个事件的骑手数量的事件和类。然后,当您遍历该结果集时,确定每次加热的骑手数量。

这有点粗糙,但我相信你可以从这里打磨它。

function getEntriesPerClass($event_id) {
    global $db;

    $stmt = $db->prepare(
        'SELECT tec.class_id, tec.event_id, COUNT(tee.event_id) AS entries_per_class ' .
        'FROM tbl_event_classes tec ' .
        'JOIN tbl_event_entries tee ON tee.event_id = tec.event_id ' .
        'WHERE tec.event_id = :event_id ' .
        'GROUP BY tee.event_id');

    $stmt->bindValue(':event_id', $event_id);
    $stmt->execute();

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

function getRidersInHeats($class_id, $event_id, $riders_per_class)
{
    global $db;

    $stmt = $db->prepare(
        'SELECT tl.riders_in_heat_1, tl.riders_in_heat_2 ' .
        'FROM tbl_lookup ' .
        'WHERE class_id = :class_id AND event_id = :event_id AND rider_count = :entries');

    $stmt->bindValue(':class_id', $class_id);
    $stmt->bindValue(':event_id', $event_id);
    $stmt->bindValue(':rider_count', $riders_per_class);

    $stmt->execute();

    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}

$entriesPerClass = getEntriesPerClass($_GET['event_id']);
foreach($entriesPerClass as $entry) {
    $riders = getRidersInHeats($entry['class_id'], $entry['event_id'], $entry['entries_per_class']);

    echo
        "class     : " . $row['class_id']       . "; " .
        "ridercount: " . $riders['rider_count'] . "; " .
        "heats     : " . $riders['heat_count']  . "<br/>";

    echo "Heats, consisting of :<br>\n<ul>";
    echo "<li>Heat 1: " . $riders['riders_in_heat_1'] . "</li>";

    $ridersInHeat2 = $riders['riders_in_heat_2'];
    if($ridersInHeat2 > 0) {
        echo "<li>Heat 2: " . $riders['riders_in_heat_2'] . "</li>";
    }

    echo "</ul>";
}

答案 1 :(得分:1)

我今天早上一直坚持这一点,知道循环是我的问题,并且知道我接近我需要的东西。在我的主循环中对$ offset进行了一点按摩,并且正如我需要它一样工作。 ;)

再次感谢那些提供帮助的人。以下是有效的代码。

<?php
session_start();
require_once "../db.class.php";
require_once "../functions.class.php";

$f = new functions();
$event_id = $_POST['id'];
header("Content-Type:application/json; Charset=utf-8");


// -- Function Name : getLookup
// -- Params : $value
// -- Purpose : get count of riders and return distribution of riders and heats
function getLookup($value)
{
    global $db;
    $stmt = $db->prepare("SELECT * FROM tbl_lookup WHERE rider_count = :value");
    $stmt->bindValue(':value', $value);
    $stmt->execute();
    return $r = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
// -- Function Name : getEntries
// get entries for the event
// -- Purpose : get entries to determine race orders
function getEntries($class_id, $limit, $offset)
{
    global $db;
    global $event_id;
    $getentries = $db->prepare("SELECT entry_id FROM tbl_event_entries WHERE event_id = :event_id AND class_id = :class_id LIMIT :offset, :limit");
    $getentries->bindValue(':event_id', $event_id);
    $getentries->bindValue(':class_id', $class_id);
    $getentries->bindValue(':limit', $limit);
    $getentries->bindValue(':offset', $offset);
    $getentries->execute();
    while ($r = $getentries->fetch(PDO::FETCH_ASSOC)) return $r['entry_id'];
}
// -- Function Name : getEntriesPerClass
// get count of entries per class
// -- Purpose : get entries per class to feed the lookup function  
function getEntriesPerClass ()
{
    global $db;
    $getentriesperclass = $db->prepare("SELECT tbl_event_entries.class_id, COUNT(tbl_event_entries.entry_id) AS riders, tbl_moto_order.moto_nbr
                                FROM tbl_event_entries
                                JOIN tbl_moto_order ON tbl_event_entries.event_id = tbl_moto_order.event_id AND tbl_event_entries.class_id = tbl_moto_order.class_id
                                WHERE tbl_event_entries.event_id = :event_id
                                GROUP BY tbl_event_entries.class_id
                                ORDER BY moto_nbr;");
    $getentriesperclass->bindValue(':event_id', $_POST['id']);
    $getentriesperclass->execute();
    $counts = array();
    while ($r = $getentriesperclass->fetch(PDO::FETCH_ASSOC)) $counts[$r['class_id']] = $r['riders'];
    return $counts;
}

$counts = getEntriesPerClass();
$race = 1; //set to add value to race_nbr field, increments 1 time for each total heat race

foreach ($counts as $class => $rider_count)
{
    $list = getLookup($rider_count); // lookup to get heat race counts and line ups for each heat.
    // update event classes table with counts so we don't have to loop like crazy to build the printouts
    $assign_class_counts = $db->prepare("UPDATE tbl_event_classes SET nbr_of_heats = :nbr_of_heats, nbr_of_riders_in_heats = :nbr_of_riders_in_heats WHERE event_id = :event_id AND class_id = :class_id");
    $assign_class_counts->bindValue(':nbr_of_heats', $list[0]['heat_count']);
    $assign_class_counts->bindValue(':nbr_of_riders_in_heats', $list[0]['rider_count']);
    $assign_class_counts->bindValue(':event_id',  $_POST['id']);
    $assign_class_counts->bindValue(':class_id', $class);
    $assign_class_counts->execute();

    $offset = 0; // set offset to feet the main query to give us the position in each heat for a rider. Used in the getEntries query.
    for ($i = 1; $i <= $list[0]['heat_count']; $i++)
    {
        if ($list[0]['heat_count'] > 0)
        {
            for ($rih = 1; $rih <= $list[0]['riders_in_heat_'.$i]; $rih++)
            {
                $assignheats = $db->prepare("UPDATE tbl_event_entries SET heat_nbr = :heat_nbr, heat_position = :heat_position, race_nbr = :race_nbr WHERE entry_id = :entry_id");
                $assignheats->bindValue(':heat_nbr', $i);
                $assignheats->bindValue(':heat_position', $rih);
                $assignheats->bindValue(':race_nbr', $race);
                $assignheats->bindValue(':entry_id', getEntries($class, $list[0]['riders_in_heat_'.$i], $offset));
                $assignheats->execute();
                $offset++;
            }
            $race++;
        }
    }
}

echo json_encode(array('status' => true));