Poblando un cuadro combinado HTML mediante concatenación en bucle -- php campo con html campo con sql campo con array camp codereview Relacionados El problema

Populating an HTML combo box by looped concatenation


3
vote

problema

Español

Este código toma los resultados de una consulta de la base de datos y los usa para rellenar las opciones en un ComboBox en un formulario.

¿Sería mejor comenzar con un código 9988776655544337 "y luego concatenar todo el código <option> en el bucle antes de finalmente usando echo fuera del bucle?

también, ¿necesito declarar var status: Int32 = 0 // Protocol configuration var hints = addrinfo( ai_flags: AI_PASSIVE, // Assign the address of my local host to the socket structures ai_family: AF_UNSPEC, // Either IPv4 or IPv6 ai_socktype: SOCK_STREAM, // TCP ai_protocol: 0, ai_addrlen: 0, ai_canonname: UnsafeMutablePointer<Int8>.null(), ai_addr: UnsafeMutablePointer<sockaddr>.null(), ai_next: UnsafeMutablePointer<addrinfo>.null()) // For the result from the getaddrinfo var servinfo = UnsafeMutablePointer<addrinfo>.null() // Get the info we need to create our socket descriptor status = getaddrinfo(UnsafePointer<Int8>.null(), ap_servicePortNumber, &hints, &servinfo) // Cop out if there is an error if status != 0 { return } // Print a list of the found IP addresses if ap_applicationInDebugMode { var info = servinfo while info != UnsafeMutablePointer<addrinfo>.null() { // Check for IPv4 if info.memory.ai_family == AF_INET { var ipAddressString = [CChar](count:Int(INET_ADDRSTRLEN), repeatedValue: 0) inet_ntop( info.memory.ai_family, info.memory.ai_addr, &ipAddressString, socklen_t(INET_ADDRSTRLEN)) let addressStr = String.fromCString(&ipAddressString) var message = addressStr == nil ? "No IPv4 address found" : "IPv4 address: " + addressStr! log.atLevelDebug(source: SOURCE, object: nil, message: message) } else { // Should be IPv6 var ipAddressString = [CChar](count:Int(INET6_ADDRSTRLEN), repeatedValue: 0) inet_ntop( info.memory.ai_family, info.memory.ai_addr, &ipAddressString, socklen_t(INET6_ADDRSTRLEN)) let addressStr = String.fromCString(&ipAddressString) var message = addressStr == nil ? "No IPv6 address found" : "IPv6 address: " + addressStr! log.atLevelDebug(source: SOURCE, object: nil, message: message) } info = info.memory.ai_next } } // Get the socket descriptor, use the results from the getaddrinfo call earlier var socketDescriptor = socket(servinfo.memory.ai_family, servinfo.memory.ai_socktype, servinfo.memory.ai_protocol); log.atLevelDebug(source: SOURCE, object: nil, message: "Socket value: " + socketDescriptor.description) // Since we will be listening, bind the socket descriptor to our socket status = bind(socketDescriptor, servinfo.memory.ai_addr, servinfo.memory.ai_addrlen); log.atLevelDebug(source: SOURCE, object: nil, message: "Status from binding: " + status.description) // Cop out if there is an error // PS: Need to handle "in use" errors if status != 0 { let message = "Binding error, status = " + status.description + ", error = " + errno.description log.atLevelEmergency(source: SOURCE, object: nil, message: message) setApplicationError(ErrorCode.initPortForListeningBindingError, message) return } // Don't need this anymore freeaddrinfo(servinfo) 0 , var status: Int32 = 0 // Protocol configuration var hints = addrinfo( ai_flags: AI_PASSIVE, // Assign the address of my local host to the socket structures ai_family: AF_UNSPEC, // Either IPv4 or IPv6 ai_socktype: SOCK_STREAM, // TCP ai_protocol: 0, ai_addrlen: 0, ai_canonname: UnsafeMutablePointer<Int8>.null(), ai_addr: UnsafeMutablePointer<sockaddr>.null(), ai_next: UnsafeMutablePointer<addrinfo>.null()) // For the result from the getaddrinfo var servinfo = UnsafeMutablePointer<addrinfo>.null() // Get the info we need to create our socket descriptor status = getaddrinfo(UnsafePointer<Int8>.null(), ap_servicePortNumber, &hints, &servinfo) // Cop out if there is an error if status != 0 { return } // Print a list of the found IP addresses if ap_applicationInDebugMode { var info = servinfo while info != UnsafeMutablePointer<addrinfo>.null() { // Check for IPv4 if info.memory.ai_family == AF_INET { var ipAddressString = [CChar](count:Int(INET_ADDRSTRLEN), repeatedValue: 0) inet_ntop( info.memory.ai_family, info.memory.ai_addr, &ipAddressString, socklen_t(INET_ADDRSTRLEN)) let addressStr = String.fromCString(&ipAddressString) var message = addressStr == nil ? "No IPv4 address found" : "IPv4 address: " + addressStr! log.atLevelDebug(source: SOURCE, object: nil, message: message) } else { // Should be IPv6 var ipAddressString = [CChar](count:Int(INET6_ADDRSTRLEN), repeatedValue: 0) inet_ntop( info.memory.ai_family, info.memory.ai_addr, &ipAddressString, socklen_t(INET6_ADDRSTRLEN)) let addressStr = String.fromCString(&ipAddressString) var message = addressStr == nil ? "No IPv6 address found" : "IPv6 address: " + addressStr! log.atLevelDebug(source: SOURCE, object: nil, message: message) } info = info.memory.ai_next } } // Get the socket descriptor, use the results from the getaddrinfo call earlier var socketDescriptor = socket(servinfo.memory.ai_family, servinfo.memory.ai_socktype, servinfo.memory.ai_protocol); log.atLevelDebug(source: SOURCE, object: nil, message: "Socket value: " + socketDescriptor.description) // Since we will be listening, bind the socket descriptor to our socket status = bind(socketDescriptor, servinfo.memory.ai_addr, servinfo.memory.ai_addrlen); log.atLevelDebug(source: SOURCE, object: nil, message: "Status from binding: " + status.description) // Cop out if there is an error // PS: Need to handle "in use" errors if status != 0 { let message = "Binding error, status = " + status.description + ", error = " + errno.description log.atLevelEmergency(source: SOURCE, object: nil, message: message) setApplicationError(ErrorCode.initPortForListeningBindingError, message) return } // Don't need this anymore freeaddrinfo(servinfo) 1 99887766555443312 como variables de clase o están bien como es porque solo son utilizado en este método?

  var status: Int32 = 0  // Protocol configuration  var hints = addrinfo(     ai_flags: AI_PASSIVE,       // Assign the address of my local host to the socket structures     ai_family: AF_UNSPEC,       // Either IPv4 or IPv6     ai_socktype: SOCK_STREAM,   // TCP     ai_protocol: 0,     ai_addrlen: 0,     ai_canonname: UnsafeMutablePointer<Int8>.null(),     ai_addr: UnsafeMutablePointer<sockaddr>.null(),     ai_next: UnsafeMutablePointer<addrinfo>.null())   // For the result from the getaddrinfo  var servinfo = UnsafeMutablePointer<addrinfo>.null()   // Get the info we need to create our socket descriptor  status = getaddrinfo(UnsafePointer<Int8>.null(), ap_servicePortNumber, &hints, &servinfo)   // Cop out if there is an error  if status != 0 { return }   // Print a list of the found IP addresses  if ap_applicationInDebugMode {      var info = servinfo      while info != UnsafeMutablePointer<addrinfo>.null() {          // Check for IPv4         if info.memory.ai_family == AF_INET {              var ipAddressString = [CChar](count:Int(INET_ADDRSTRLEN), repeatedValue: 0)             inet_ntop(                 info.memory.ai_family,                 info.memory.ai_addr,                 &ipAddressString,                 socklen_t(INET_ADDRSTRLEN))             let addressStr = String.fromCString(&ipAddressString)             var message = addressStr == nil ? "No IPv4 address found" : "IPv4 address: " + addressStr!             log.atLevelDebug(source: SOURCE, object: nil, message: message)          } else { // Should be IPv6              var ipAddressString = [CChar](count:Int(INET6_ADDRSTRLEN), repeatedValue: 0)             inet_ntop(                 info.memory.ai_family,                 info.memory.ai_addr,                 &ipAddressString,                 socklen_t(INET6_ADDRSTRLEN))             let addressStr = String.fromCString(&ipAddressString)             var message = addressStr == nil ? "No IPv6 address found" : "IPv6 address: " + addressStr!             log.atLevelDebug(source: SOURCE, object: nil, message: message)         }          info = info.memory.ai_next     } }   // Get the socket descriptor, use the results from the getaddrinfo call earlier  var socketDescriptor = socket(servinfo.memory.ai_family, servinfo.memory.ai_socktype, servinfo.memory.ai_protocol);  log.atLevelDebug(source: SOURCE, object: nil, message: "Socket value: " + socketDescriptor.description)   // Since we will be listening, bind the socket descriptor to our socket  status = bind(socketDescriptor, servinfo.memory.ai_addr, servinfo.memory.ai_addrlen);  log.atLevelDebug(source: SOURCE, object: nil, message: "Status from binding: " + status.description)   // Cop out if there is an error  // PS: Need to handle "in use" errors  if status != 0 {     let message = "Binding error, status = " + status.description + ", error = " + errno.description     log.atLevelEmergency(source: SOURCE, object: nil, message: message)     setApplicationError(ErrorCode.initPortForListeningBindingError, message)     return }   // Don't need this anymore  freeaddrinfo(servinfo) 3  

Yo uso una matriz para cada combobox en el formulario:

  var status: Int32 = 0  // Protocol configuration  var hints = addrinfo(     ai_flags: AI_PASSIVE,       // Assign the address of my local host to the socket structures     ai_family: AF_UNSPEC,       // Either IPv4 or IPv6     ai_socktype: SOCK_STREAM,   // TCP     ai_protocol: 0,     ai_addrlen: 0,     ai_canonname: UnsafeMutablePointer<Int8>.null(),     ai_addr: UnsafeMutablePointer<sockaddr>.null(),     ai_next: UnsafeMutablePointer<addrinfo>.null())   // For the result from the getaddrinfo  var servinfo = UnsafeMutablePointer<addrinfo>.null()   // Get the info we need to create our socket descriptor  status = getaddrinfo(UnsafePointer<Int8>.null(), ap_servicePortNumber, &hints, &servinfo)   // Cop out if there is an error  if status != 0 { return }   // Print a list of the found IP addresses  if ap_applicationInDebugMode {      var info = servinfo      while info != UnsafeMutablePointer<addrinfo>.null() {          // Check for IPv4         if info.memory.ai_family == AF_INET {              var ipAddressString = [CChar](count:Int(INET_ADDRSTRLEN), repeatedValue: 0)             inet_ntop(                 info.memory.ai_family,                 info.memory.ai_addr,                 &ipAddressString,                 socklen_t(INET_ADDRSTRLEN))             let addressStr = String.fromCString(&ipAddressString)             var message = addressStr == nil ? "No IPv4 address found" : "IPv4 address: " + addressStr!             log.atLevelDebug(source: SOURCE, object: nil, message: message)          } else { // Should be IPv6              var ipAddressString = [CChar](count:Int(INET6_ADDRSTRLEN), repeatedValue: 0)             inet_ntop(                 info.memory.ai_family,                 info.memory.ai_addr,                 &ipAddressString,                 socklen_t(INET6_ADDRSTRLEN))             let addressStr = String.fromCString(&ipAddressString)             var message = addressStr == nil ? "No IPv6 address found" : "IPv6 address: " + addressStr!             log.atLevelDebug(source: SOURCE, object: nil, message: message)         }          info = info.memory.ai_next     } }   // Get the socket descriptor, use the results from the getaddrinfo call earlier  var socketDescriptor = socket(servinfo.memory.ai_family, servinfo.memory.ai_socktype, servinfo.memory.ai_protocol);  log.atLevelDebug(source: SOURCE, object: nil, message: "Socket value: " + socketDescriptor.description)   // Since we will be listening, bind the socket descriptor to our socket  status = bind(socketDescriptor, servinfo.memory.ai_addr, servinfo.memory.ai_addrlen);  log.atLevelDebug(source: SOURCE, object: nil, message: "Status from binding: " + status.description)   // Cop out if there is an error  // PS: Need to handle "in use" errors  if status != 0 {     let message = "Binding error, status = " + status.description + ", error = " + errno.description     log.atLevelEmergency(source: SOURCE, object: nil, message: message)     setApplicationError(ErrorCode.initPortForListeningBindingError, message)     return }   // Don't need this anymore  freeaddrinfo(servinfo) 4  
Original en ingles

This code takes the results of a database query and uses them to populate the options in a combobox on a form.

Would it be better to start with an empty htmlCode and then concatenate all the <option> code in the loop before finally using echo outside the loop?

Also, do I need to declare $boxOption, $paramKey and $paramValue as class variables or are they OK as is because they're only used in this method?

public function populateComboBox ($boxToPopulate)     {         $this->boxOptions = $this->getQueryResults($this->boxParams[$boxToPopulate]['query']);          foreach ($this->boxOptions as $boxOption) {              foreach ($this->htmlParams as $paramKey => $paramValue) {                  if (!empty($this->boxParams[$boxToPopulate][$paramKey])) {                      $this->htmlParams[$paramKey] = $boxOption[$this->boxParams[$boxToPopulate][$paramKey]];                 }             }              $this->htmlCode = "<option value='{$this->htmlParams['value']}' "                               . "class='{$this->htmlParams['class']}'>"                               . "{$this->htmlParams['text']}</option>\n";              echo <<<_CODE                                 {$this->htmlCode} _CODE;         }      } 

I use an array for each combobox on the form:

    $this->boxParams['issue'] = array (         'query' => 'SELECT interface_issue, current_issue '                  . 'FROM interface_issue '                  . 'WHERE current_issue = -1 '                  . 'ORDER BY interface_issue;',         'value' => 'interface_issue',         'class' => '',         'text' => 'interface_issue'     ); 
           

Lista de respuestas

3
 
vote
vote
La mejor respuesta
 

Nos da una pieza de código muy corta, y dos preguntas simples. No diré las otras cuestiones de su código (o tal vez lo haré), pero concentraré en las dos preguntas.

1. "¿Sería mejor comenzar con un código html vacío y luego concatenar todo el código en el bucle antes de finalmente usando eco fuera del bucle?"

¿Supongo que la otra alternativa está echando el html dentro del bucle? ¿Esta es probablemente una pregunta sobre el rendimiento? La mejor manera de resolver esto, es probar ambos casos. Si la pregunta se trata de codificación, no haría eco dentro de este método, sino que solo devolvería una cadena con el HTML. Esto le permite decidir más tarde, en otra parte del código, qué hacer con el HTML: ¡Aléntrate? Ponerlo en un email? O echo de eco?

2. "¿Necesito declarar $boxOption , $paramKey $paramValue como las variables de clase o están bien como se debe a que solo se usan en este método ? ".

Bueno, si solo se usan en este método, deben ser variables locales, no las variables de la clase en las que las convirtió en ahora. Así que reemplace $this-> por $ .

Solo un comentario sobre su método: un método debe tener un propósito, una cosa que hacer. El suyo hace varios: 1. Recupere los datos de la base de datos utilizando una consulta que se almacena de manera extraña. 2. Construye HTML, pero ni siquiera un 99887766555544335

También parece tener una clase que hace muchas cosas. El 'principio de la responsabilidad única' no parece haber sido aplicado. Estos principios están aquí por una muy buena razón. Ver:

http://en.wikipedia.org/wiki/solid_%28Object- orientado_design% 29

Un programador puede ignorar estos principios durante mucho tiempo, y los programas funcionarán, pero cuando crecen, y se expanden, encontrará que adherirse a estos principios puede ser muy útil. Afortunadamente, el 'principio de la responsabilidad única' es uno de los más fáciles de entender. Una mejor explicación se puede encontrar aquí:

http://www.codemag.com/article/1001061

 

You give us a very short piece of code, and two simple questions. I will not address the other issues of your code (or maybe I will), but concentrate on the two questions.

1. "Would it be better to start with an empty htmlCode and then concatenate all the code in the loop before finally using echo outside the loop?"

I guess the other alternative is echo'ing the html inside the loop? This is probably a question about performance? The best way to figure this out, is to test both cases. If the question is about coding I would not echo inside this method at all, but just return a string with the HTML. This allow you to decide later, in another part of the code, what to do with the HTML: Store it? Put it in an email? Or echo it?

2. "do I need to declare $boxOption, $paramKey and $paramValue as class variables or are they OK as is because they're only used in this method?".

Well, if they're only used in this method, then they should be local variables, NOT the class variables which you made them into now. So replace $this-> by $.

Just one remark about your method: A method should have one purpose, one thing to do. Yours does several: 1. retrieve data from the database using a query that's stored in a strange way. 2. Build HTML, but not even a whole <select>, only the options. 3. Output the HTML. This is not very flexible. Your data always has to come from a predetermined place, and your output will always be echoed. Any variation on this method will require a completely new method, probably doing almost the same thing.

You also seem to have a class that does many things. The 'single responsibility principle' doesn't seem to have been applied. These principles are here for a very good reason. See:

http://en.wikipedia.org/wiki/SOLID_%28object-oriented_design%29

A programmer can ignore these principles for a long time, and programs will work, but when they grow, and expand, you will find that sticking to these principles can be very useful. Luckily the 'single responsibility principle' is one of the easiest to understand. A better explanation can be found here:

http://www.codemag.com/article/1001061

 
 
   
   

Relacionados problema

2  Cargando imágenes en el fondo para una vista de tabla  ( Loading images in the background for a table view ) 
Tengo fetchData2 MÉTODO QUE LLENA MI imagesArray : func fetchData(){ let imageQuery = PFUser.query() imageQuery?.whereKey("username", contained...

6  Palindrome más largo en una matriz  ( Longest palindrome in an array ) 
Soy nuevo en la programación, y creo que este código podría mejorarse. ¿Alguna sugerencia? 'done'0 ...

6  Fusionando dos varias de clases  ( Merging two array of classes ) 
Tengo esta función que debe fusionar dos matriz de clases cuando id es igual a id de Array2. Para la simplicidad, convirtí una matriz en un arraylist pa...

7  Colecciones vacías en caché  ( Cached empty collections ) 
A menudo necesito devolver las colecciones vacías. Uno de esos días, escribí lo siguiente para devolver una instancia en caché: public static class Array<...

6  Clase de matriz multidimensional simple en C ++ 11  ( Simple multi dimensional array class in c11 ) 
La nueva versión del código se puede revisar en Clase de matriz multidimensional simple en C ++ 11 - Seguimiento . El siguiente código implementa una clas...

2  Devuelve verdadero si los elementos de una matriz no contienen uno u otro  ( Return true if the elements of an array do not contain one or the other ) 
Estoy completando gradualmente los ejercicios de codificación para Java. Aquí está el uno acabo de hacer: Dada una matriz de INTS, devuelva verdadera si ...

5  Encuentra el primer número único de la matriz  ( Find first unique number from array ) 
Se me pidió que creara una función que devuelva el primer entero único de la matriz de enteros. En un caso de éxito, la función devuelve el número único en un...

2  Importando datos en Excel  ( Importing data into excel ) 
¿Existe una forma más fácil de importar datos en una matriz de Excel u otra estructura de datos? He intentado investigar colecciones, pero he encontrado la D...

6  Buscar número de más en una matriz 2D  ( Find number of plus in a 2d array ) 
Problema Chargrid El CharGrid La clase encapsula una matriz de 2-D con una pareja de operaciones. INT APULUS () Busque un patrón '+' en la cuadrícu...

2  Mejora de la función que compara dos cadenas  ( Improving function that compares two strings ) 
Estoy aprendiendo C y he hecho esta función muy simple para comparar dos cuerdas. Me gustaría saber cómo se puede mejorar: int match(char* string1, char* s...




© 2022 respuesta.top Reservados todos los derechos. Centro de preguntas y respuestas reservados todos los derechos