2012-11-02 10 views
3

과 일치하는지 여부에 따라 HTML 테이블 번호 매기기 행 채우기 그래서 기본적으로 데이터 센터 택시 다이어그램을 만들려고합니다. Excel 스프레드 시트가 있지만 쉽게 업데이트하거나 쉽게 검색 할 수는 없습니다. MySQL DB에는 3 개의 테이블이 있습니다. db는 다음과 같습니다. 랙, 테이블은 캐비닛, 장치, & 데이터 센터입니다. 각 테이블의 각 행은 그 내용을 나타냅니다. 캐비닛 테이블에는 높이가 U 인 곳 (일부 데이터 센터의 일부 캐비닛은 다른 곳보다 높습니다)을 지정하는 열이 있습니다. PHP가 캐비닛을 그릴 때, 캐비닛을 각각의 높이로 그립니다. 지금까지 모든 것은 데이터 센터와 포함 캐비닛 및 각각의 높이를 그룹화하는 것과 관련되어 작동합니다. 내 문제는 캐비닛 당 둘 이상의 장치를 채우지 못하는 것입니다. 이것은 전체 페이지, 그리고 MySQL의 DB 설정은 아래 :PHP MYSQL - 행 번호가

여기
<SCRIPT LANGUAGE="JavaScript" type="text/javascript"> 
<!-- 
    function clickHandler(e) 
    { 
     var targetId, srcElement, targetElement; 
     if (window.event) e = window.event; 
     srcElement = e.srcElement? e.srcElement: e.target; 
     if (srcElement.className == "Outline") 
     { 
       targetId = srcElement.id + "d"; 
       targetElement = document.getElementById(targetId); 

      if (targetElement.style.display == "none") 
       { 
         targetElement.style.display = ""; 
         srcElement.src = "images/minus.gif"; 
        } 
      else 
       { 
        targetElement.style.display = "none"; 
        srcElement.src = "images/plus.gif"; 
       } 
     } 
    } 
    document.onclick = clickHandler; 
--> 
</SCRIPT> 
<noscript>You need Javascript enabled for this page to work correctly</noscript> 
<? 
function sql_conn() 
{ 
    $username="root"; 
    $password="root"; 
    $database="racks"; 
    $server="localhost"; 

    @mysql_connect($server,$username,$password) or die("<h2 align=\"center\" class=\"red\">[<img src=\"images/critical.gif\" border=\"0\">] Unable to connect to $server [<img src=\"images/critical.gif\" border=\"0\">]</h2>"); 
    @mysql_select_db($database) or die("<h2 align=\"center\" class=\"red\">[<img src=\"images/critical.gif\" border=\"0\">] Unable to select $database as a database [<img src=\"images/critical.gif\" border=\"0\">]</h2>"); 
} 

sql_conn(); 
$sql_datacenters="SELECT * FROM `datacenters`"; 

$sql_devices="SELECT * FROM `devices`"; 
$result_datacenters=mysql_query($sql_datacenters); 
$result_devices=mysql_query($sql_devices); 
$j=0; 
echo "<table border='1' style='float:left;'>"; 
while ($datacenters_sqlrow=mysql_fetch_array($result_datacenters)) 
{ 
    echo "<tr><td>"; 
    echo "<h2 class='black' align='left'>"; 
    echo "<IMG SRC='images/plus.gif' ID='Out" . $j . "' CLASS='Outline' STYLE='cursor:hand;cursor:pointer'>"; // fancy icon for expanding-collapsing section 
    echo " " . $datacenters_sqlrow['rack'] . ": " . $datacenters_sqlrow['cagenum'] . "</h2>"; // datacenter name and cage number 
    echo "<div id=\"Out" . $j . "d\" style=\"display:none\">"; // opening of div box for section that is to be expanded-collapsed 
    echo "<h3>" . $datacenters_sqlrow['notes'] . "</h3>"; // datacenter notes 
    $sql_cabinets="SELECT * FROM `cabinets` WHERE `datacenter` = '$datacenters_sqlrow[0]' ORDER BY `cabinetnumber` ASC"; 
    $result_cabinets=mysql_query($sql_cabinets); 
    while ($cabinets_sqlrow=mysql_fetch_array($result_cabinets)) 
    { 
     $sql_devices="SELECT * FROM `devices` WHERE `datacenter` = '$datacenters_sqlrow[0]' AND `cabinet` = '$cabinets_sqlrow[1]' ORDER BY `ustartlocation` ASC"; 
     $result_devices=mysql_query($sql_devices); 
     $num_devices=mysql_numrows($result_devices); 
     echo "<table border='1' style='float:left;'>"; // opening of table for all cabinets in datacenter 
     echo "<tr><td colspan='2' align='middle'>" . $cabinets_sqlrow[1] . "</td></tr>"; // cabinet number, spans U column and device name column 
     while($row = mysql_fetch_array($result_devices)) 
     { 
      $server = $row['devicename']; 
      $ustart = $row['ustartlocation']; 
     } 
     for ($i = 0; $i < $cabinets_sqlrow[2]; $i++) // iterates through number of U in cabinet  
     { 
      $u = $cabinets_sqlrow[2] - $i; // subtracts current $i value from number of U in cabinet since cabinets start their numbers from the bottom up 
      echo "<tr>"; 
      echo "<td width='15px' align='right'>$u</td>"; // U number 
      echo "<td width='150px' align='middle'>"; 
      if ($u == $ustart) // determines if there is a device starting at this U 
      {echo $server;} // device name 
      else 
      {echo "empty";} // empty space in cabinet 
      echo "</td>"; 
      echo "</tr>"; 
     } 
     $server=""; 
     $ustart=""; 

     echo "</table>"; // closes table opened in row 65 
    } 
    echo "</td></tr>"; 
    echo "</div>"; // close for div box that needs expanding-collapsing by fancy java 
    $j++; // iteration for the fancy java expand-collapse 
} 
echo "</table>"; 
mysql_close(); 
?> 

는 MySQL의 설정입니다 :

-- phpMyAdmin SQL Dump 
-- version 3.5.1 
-- http://www.phpmyadmin.net 
-- 
-- Host: localhost 
-- Generation Time: Nov 02, 2012 at 02:13 AM 
-- Server version: 5.5.25 
-- PHP Version: 5.4.4 

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; 
SET time_zone = "+00:00"; 

-- 
-- Database: `racks` 
-- 

-- -------------------------------------------------------- 

-- 
-- Table structure for table `cabinets` 
-- 

CREATE TABLE `cabinets` (
    `id` tinyint(3) NOT NULL AUTO_INCREMENT, 
    `cabinetnumber` varchar(25) NOT NULL, 
    `numberofu` varchar(3) NOT NULL, 
    `datacenter` tinyint(3) NOT NULL, 
    KEY `id` (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ; 

-- 
-- Dumping data for table `cabinets` 
-- 

INSERT INTO `cabinets` (`id`, `cabinetnumber`, `numberofu`, `datacenter`) VALUES 
(1, '0101', '45', 2), 
(2, '0102', '45', 2), 
(3, '0101', '50', 1), 
(4, '0102', '50', 1), 
(5, '0103', '50', 1); 

-- -------------------------------------------------------- 

-- 
-- Table structure for table `datacenters` 
-- 

CREATE TABLE `datacenters` (
    `id` tinyint(3) NOT NULL AUTO_INCREMENT, 
    `rack` varchar(20) NOT NULL, 
    `cagenum` varchar(255) NOT NULL, 
    `notes` longtext NOT NULL, 
    KEY `id` (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ; 

-- 
-- Dumping data for table `datacenters` 
-- 

INSERT INTO `datacenters` (`id`, `rack`, `cagenum`, `notes`) VALUES 
(1, 'CAGE1', '', ''), 
(2, 'CAGE2', '', ''), 
(3, 'CAGE3', '', ''), 
(4, 'CAGE4', '', ''), 
(5, 'CAGE5', '', ''), 
(6, 'CAGE6', '', ''), 
(7, 'CAGE7', '', ''); 

-- -------------------------------------------------------- 

-- 
-- Table structure for table `devices` 
-- 

CREATE TABLE `devices` (
    `id` int(10) NOT NULL AUTO_INCREMENT, 
    `devicename` varchar(255) NOT NULL, 
    `datacenter` varchar(255) NOT NULL, 
    `cabinet` varchar(255) NOT NULL, 
    `frontorrear` tinyint(3) NOT NULL, 
    `ustartlocation` varchar(255) NOT NULL, 
    `usize` varchar(255) NOT NULL, 
    `spare1` varchar(255) NOT NULL, 
    `spare2` varchar(255) NOT NULL, 
    `spare3` varchar(255) NOT NULL, 
    KEY `id` (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ; 

-- 
-- Dumping data for table `devices` 
-- 

INSERT INTO `devices` (`id`, `devicename`, `datacenter`, `cabinet`, `frontorrear`, `ustartlocation`, `usize`, `spare1`, `spare2`, `spare3`) VALUES 
(1, 'SERVER1', '1', '0101', 1, '33', '1', '', '', ''), 
(2, 'SERVER2', '1', '0102', 1, '36', '1', '', '', ''), 
(3, 'SERVER3', '1', '0101', 1, '40', '2', '', '', ''); 

답변

1

직접 문제를 해결하기 위해 (좀 더 얻을 수 있습니다 비트), 당신은 장치의 전체 목록을 통해 반복하고 다음 - 당신이 그들 모두를 통해 루프를 마친 후에 - 그들을 표시하려고 시도합니다. 이 때문에 터치 된 최종 장치 만 표시됩니다.

현재 코드립니다입니다 :

while($row = mysql_fetch_array($result_devices)) { 
    $server = $row['devicename']; 
    $ustart = $row['ustartlocation']; 
} 
for ($i = 0; $i < $cabinets_sqlrow[2]; $i++) { 
    $u = $cabinets_sqlrow[2] - $i; 
    ... 
    if ($u == $ustart) { 
     echo $server; 
    } 
    ... 
} 

난 당신이 뭘 하려는지 이해한다면, 당신은 각 중에 통해 "장치"배열과 루프에 각 장치를 저장해야합니다 귀하의 for 루프 반복. 배열의 인덱스로 ustartlocation 사용하여 수행 할 수있는이 같은 작업을 수행하는 더 우아한 방법

$devices = array(); 
while($row = mysql_fetch_array($result_devices)) { 
    $devices[] = array(
     'server' => $row['devicename'], 
     'ustart' => $row['ustartlocation'] 
    ); 
} 
for ($i = 0; $i < $cabinets_sqlrow[2]; $i++) { 
    ... 
    $output = 'empty'; 
    foreach ($devices as $device) { 
     if ($u == $device['ustart']) { 
      $output = $device['server']; 
      break; 
     } 
    } 
    echo $output; 
    ... 
} 

,하지만 ustartlocation는 개별 장치/서버에 고유해야합니다 : 뭔가를 시도

$devices = array(); 
while($row = mysql_fetch_array($result_devices)) { 
    $devices[$row['ustartlocation']] = $row['devicename']; 
} 
for ($i = 0; $i < $cabinets_sqlrow[2]; $i++) { 
    ... 
    echo (isset($devices[$u]) ? $devices[$u] : 'empty'); 
    ... 
} 

이 방법을 사용하면 매번 장치 목록을 반복 할 필요가 없지만 다시 - ustartlocation이 고유해야합니다.

사이드 노트 (추가 비 응답 특정 비판)이 $sql_devices="SELECT * FROM 장치 ";$result_devices=mysql_query($sql_devices);을 실행하지만,이 개체를 사용하지 않을 코드의 시작 부분에서

  1. . 하나의 추가 쿼리 (상당히 무거운 쿼리)이므로 제거 할 수 있고 제거해야합니다.

  2. 두 번째 while -loop에는 $num_devices=mysql_numrows($result_devices); 줄이 있습니다. PHP 함수가 mysql_numrows()인데, 이것은 mysql_num_rows() 함수의 오타이라고 생각합니다. (똑같은 일을하는 커스텀 - 작성 함수가 있습니다.) 또한이 라인을 실제로 제거 할 수 있도록 $num_devices 변수를 사용하지 않습니다. 전적으로

  3. 당신은 이전에 사용되지 않는 기능을 사용하고 있습니다 (이 기능들에 대한 문서 페이지 상단의 경고 메시지를 확인하십시오; 여기에는 mysql_connect() 참조). 커뮤니티에서 mysqli_ 또는 PDO 방법으로 업그레이드 할 것을 권장합니다.

  4. 코드는 사용자 입력에서 직접 입력하는 것처럼 보이지는 않지만이 요인을 제외시키는 것으로 보이지 않으므로 SQL 주입에 특별히 제한되지는 않지만 비신 장 SQL 오류가 발생합니다. 예를 들어, cabinet 또는 datacenter 값에 작은 따옴표가 포함되어 있으면 어떻게됩니까? $sql_cabinets="SELECT * FROM cabinets WHERE datacenter = '" . mysql_real_escape_string($datacenters_sqlrow[0]) . "' ORDER BY cabinetnumber";

+0

감사합니다, 당신의 제안 (내가 더 우아한 하나를 선택했다) 일 : 당신이 mysql_ 방법을 사용하고 있기 때문에, 나는 당신이 mysql_real_escape_string() 전에 데이터베이스 호출에서 그들을 사용하여 각 포장 좋습니다. 나는 도움뿐만 아니라 제안을 매우 감사하고 그들을 점검하고 구현할 것이다. 나는 다음과 같은 질문을 가지고 있습니다. ustartlocation은 캐비닛에 여러 U를 걸쳐 놓을 수있는 장치가 있기 때문에 장치를 시작할 수있는 위치를 지정합니다. 어떻게 그 PHP에서 처리 될 것이라고 (나는 장치 테이블에 usize 필드가)? html 테이블에 대해 알고, 그것은 단지 rowspan 것입니다,하지만 PHP가 어떻게 처리 할 것인지 궁금합니다. – eclipsed450

+0

@ eclipsed450 잘된 것을 기쁘게 생각합니다! 새/초 질문은이 사이트에 대해 완전히 새로운/다른 질문을 할 자격이 있습니다. 현재 작업중인 코드로 하나를 만들면 나를 연결하면 내가 도울 수 있는지 알게 될 것입니다. (다른 사람들이 먼저 얻을 수 있지만, 그게 당신에게 좋을 것입니다!). 요청시 – newfurniturey

+0

: http://stackoverflow.com/questions/13219921/php-mysql-populate-html-table-numbered-rows-based-on-whether-the-match-row-nu – eclipsed450