Publicar datos de matriz

  • jordonshaw
  • Student
  • Student
  • Avatar de Usuario
  • Registrado: Dic 30, 2008
  • Mensajes: 91
  • Loc: Tennessee
  • Status: Offline

Nota Junio 9th, 2009, 11:23 pm

Ok chicos, Im seguro de que puedo entender esto si que paso mucho tiempo trabajando en ello, sin embargo, me preguntaba si tal vez alguien sería muy, muy bueno y me dicen rápidamente cómo hacerlo. Tengo un script de Java que al hacer clic en un botón para agregar un nuevo tema, que crea nuevos cuadros de texto en la página, una con un nombre de textbx [] y el otro con un nombre de readbx [], así que cuando los datos es tipos en los cuadros de texto, se lo puso en una matriz. ¿Cómo puedo tirar de que los datos de la matriz en mi script de acción para enviar a la base de datos? Aquí está mi código del formulario.

Código: [ Select ]
<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<script type='text/javascript'>

var inival=0; // Initialise starting element number

// Call this function to add textbox
function addTextBox()
{
var newArea = add_New_Element();
var htcontents = "<input type='text' name='textbx[]' size='50'/> <input type='text' name='readbx[]' size='50'/>";
document.getElementById(newArea).innerHTML = htcontents; // You can any other elements in place of 'htcontents'
}


function add_New_Element() {
inival=inival+1; // Increment element number by 1
var ni = document.getElementById('area');
var newdiv = document.createElement('div'); // Create dynamic element
var divIdName = 'my'+inival+'Div';
newdiv.setAttribute('id',divIdName);
ni.appendChild(newdiv);
return divIdName;
}

</script>
<html>
<head>
<title>SNP Intranet</title>
</head>
<body>
<center>
<form action="topics.php" method="post">
<table width="670">
    <tr>
        <td colspan="2">
            Please list each topic in the white boxes below, separately and in order. List every topic that you intend to discuss in your lecture and you may use as many as needed. For each new topic, click the "Add New Topic" button and a new line will appear in which you can add your next topic. Next to the topic, list the chapter(s) or the text book where this topic is most prominent. In addition, you may suggest an appendix from the text or an article from an outside source that the student should read in addition to the chapter reading assignment that will further their knowledge on the topic.<p />Use the topics below to write your script and/or prepare your lecture notes that you will use in the recording phase. <br /><strong>(Limit 20 Topics)</strong>
        </td>
    </tr>
    <tr>
        <td colspan="2">
            <hr />
        </td>
    </tr>
    <tr>
        <td colspan="2">Course title: <input type="text" name="c_name" size="93" /></td>
    </tr>
    <tr>
     <td width="300">Topics</td>
     <td>Text Chapters, Articles, and Appendices</td>
    </tr>
        <tr>
        <td colspan="2"><div id='area'></div></td>
    </tr>
    <tr>
        <td><input type="button" name="add" onclick="addTextBox()" value="Add New Topic"></td>
    </tr>

</table>
<input type="submit" name="submit" value="Update" /> <input type="button" name="cancel" id="cancel" value="Cancel" onclick="history.back()" />
</form>
</body>
</html>
<?php
    if (isset($connection)) {
        mssql_close($connection);
    }
?>
    
  1. <?php require_once("includes/connection.php"); ?>
  2. <?php require_once("includes/functions.php"); ?>
  3. <script type='text/javascript'>
  4. var inival=0; // Initialise starting element number
  5. // Call this function to add textbox
  6. function addTextBox()
  7. {
  8. var newArea = add_New_Element();
  9. var htcontents = "<input type='text' name='textbx[]' size='50'/> <input type='text' name='readbx[]' size='50'/>";
  10. document.getElementById(newArea).innerHTML = htcontents; // You can any other elements in place of 'htcontents'
  11. }
  12. function add_New_Element() {
  13. inival=inival+1; // Increment element number by 1
  14. var ni = document.getElementById('area');
  15. var newdiv = document.createElement('div'); // Create dynamic element
  16. var divIdName = 'my'+inival+'Div';
  17. newdiv.setAttribute('id',divIdName);
  18. ni.appendChild(newdiv);
  19. return divIdName;
  20. }
  21. </script>
  22. <html>
  23. <head>
  24. <title>SNP Intranet</title>
  25. </head>
  26. <body>
  27. <center>
  28. <form action="topics.php" method="post">
  29. <table width="670">
  30.     <tr>
  31.         <td colspan="2">
  32.             Please list each topic in the white boxes below, separately and in order. List every topic that you intend to discuss in your lecture and you may use as many as needed. For each new topic, click the "Add New Topic" button and a new line will appear in which you can add your next topic. Next to the topic, list the chapter(s) or the text book where this topic is most prominent. In addition, you may suggest an appendix from the text or an article from an outside source that the student should read in addition to the chapter reading assignment that will further their knowledge on the topic.<p />Use the topics below to write your script and/or prepare your lecture notes that you will use in the recording phase. <br /><strong>(Limit 20 Topics)</strong>
  33.         </td>
  34.     </tr>
  35.     <tr>
  36.         <td colspan="2">
  37.             <hr />
  38.         </td>
  39.     </tr>
  40.     <tr>
  41.         <td colspan="2">Course title: <input type="text" name="c_name" size="93" /></td>
  42.     </tr>
  43.     <tr>
  44.      <td width="300">Topics</td>
  45.      <td>Text Chapters, Articles, and Appendices</td>
  46.     </tr>
  47.         <tr>
  48.         <td colspan="2"><div id='area'></div></td>
  49.     </tr>
  50.     <tr>
  51.         <td><input type="button" name="add" onclick="addTextBox()" value="Add New Topic"></td>
  52.     </tr>
  53. </table>
  54. <input type="submit" name="submit" value="Update" /> <input type="button" name="cancel" id="cancel" value="Cancel" onclick="history.back()" />
  55. </form>
  56. </body>
  57. </html>
  58. <?php
  59.     if (isset($connection)) {
  60.         mssql_close($connection);
  61.     }
  62. ?>
  63.     
  • Anonymous
  • Bot
  • No Avatar
  • Registrado: 25 Feb 2008
  • Mensajes: ?
  • Loc: Ozzuland
  • Status: Online

Nota Junio 9th, 2009, 11:23 pm

  • yomi
  • Graduate
  • Graduate
  • Avatar de Usuario
  • Registrado: Abr 02, 2008
  • Mensajes: 117
  • Loc: Nigeria
  • Status: Offline

Nota Junio 10th, 2009, 1:26 am

Hi, Im no estoy seguro de entender sus necesidades. ¿Qué puedo hacer de ella es que se quiere recoger un conjunto de valores que desea almacenar en el mismo campo en su databse. Si es así, tengo algo así, pero lo hice con casillas de verificación.

A mi me han formulario:

Código: [ Select ]
<input type="checkbox" value="saved money" name="checkbox[]">Company</label><br />
<label><input type="checkbox" value="money" name="checkbox[]"/>Money</label><br />
<label><input type="checkbox" value="business" name="checkbox[]"/>Business</label> <br />
<label><input type="checkbox" value="ambassador" name="checkbox[]"/>Ambassador</label><br />
<label><input type="checkbox" value="customer" name="checkbox[]"/>Customer </label>
  1. <input type="checkbox" value="saved money" name="checkbox[]">Company</label><br />
  2. <label><input type="checkbox" value="money" name="checkbox[]"/>Money</label><br />
  3. <label><input type="checkbox" value="business" name="checkbox[]"/>Business</label> <br />
  4. <label><input type="checkbox" value="ambassador" name="checkbox[]"/>Ambassador</label><br />
  5. <label><input type="checkbox" value="customer" name="checkbox[]"/>Customer </label>


luego en mi script:

Código: [ Select ]
if (isset($_POST['checkbox']) ) {
$_POST['checkbox'] = implode(', ', $_POST['checkbox']); }

$text_chptrs = $_POST ['checkbox'];
  1. if (isset($_POST['checkbox']) ) {
  2. $_POST['checkbox'] = implode(', ', $_POST['checkbox']); }
  3. $text_chptrs = $_POST ['checkbox'];


Entonces usted puede leer $ text_chptrs en su base de datos con SQL
Moderator Remark: Added [code] tags
  • jordonshaw
  • Student
  • Student
  • Avatar de Usuario
  • Registrado: Dic 30, 2008
  • Mensajes: 91
  • Loc: Tennessee
  • Status: Offline

Nota Junio 10th, 2009, 9:02 am

Que las obras grandes, con una excepción. Que pone todo en mi primera serie en un campo de un todo y en mi segunda serie en otro campo. Lo que necesitamos es que cada posición de estar en un campo diferente.

Lo que quiero decir es, tengo un cuadro en el que se ha ID, textbx, y readbx campos. Por lo tanto, si mediante el formulario que tengo que generar los nuevos temas, cuando alguien puesto algo en el primer tema, va a su puesto en conjunto la ubicación 0, por lo que en la fila 1 en mi base de datos, necesito textbx [0] para enviar en textbx el campo y readbx [0] para enviar readbx en el campo. Entonces, si la persona addes otro tema, lo que significa que ahora tengo algo en la posición 0 y la posición 1 de mi serie, necesito la textbx [0] y readbx [0] para enviar textbx en campo y readbx campo en la misma base de datos de la fila , pero entonces yo también necesitan textbx [1] y readbx [1] para crear un mensaje en el textbx y readbx ámbito de la siguiente fila. Así que, básicamente, Im que quieren dividir a las posiciones de las matrices, en las filas de la base de datos. Sé que su posible, Im justo teniendo dificultades para calcular hacia fuera.

Gracias por cualquier ayuda que puede ofrecer!

Jordon
  • jordonshaw
  • Student
  • Student
  • Avatar de Usuario
  • Registrado: Dic 30, 2008
  • Mensajes: 91
  • Loc: Tennessee
  • Status: Offline

Nota Junio 10th, 2009, 1:35 pm

Esto es lo más cercano que Ive consiguió hasta ahora con él. Im intentando ejecutar un bucle a través de mi matriz y después en una nueva fila para cada posición. Im sólo se ocupan de un arreglo en este momento y sólo intentando escribir un mensaje en el campo de tp_topic. Cada vez que esta prueba con más de un temas, es decir, más de una cosa en mi matriz, me da un error y sólo después lo primero en mi serie en mi base de datos. Aquí está el código:

Código: [ Select ]
foreach($topics as $topic) {
    $query = "INSERT INTO SNP_topics (tp_topic)
        VALUES ('$topic')";
            $results1 = mssql_query($query, $connection);
            if ($results) {
            } else {
            die("Database query failed: " . mssql_error());
            }
}
  1. foreach($topics as $topic) {
  2.     $query = "INSERT INTO SNP_topics (tp_topic)
  3.         VALUES ('$topic')";
  4.             $results1 = mssql_query($query, $connection);
  5.             if ($results) {
  6.             } else {
  7.             die("Database query failed: " . mssql_error());
  8.             }
  9. }
  • jordonshaw
  • Student
  • Student
  • Avatar de Usuario
  • Registrado: Dic 30, 2008
  • Mensajes: 91
  • Loc: Tennessee
  • Status: Offline

Nota Junio 10th, 2009, 1:37 pm

No importa, gracias por toda su ayuda, me imaginé que fuera. Mis resultados varible estaba equivocado, en un lugar que se llama results1 y en otro lugar, sólo resultados. Una vez que me fijo, funcionó como un encanto!
  • jordonshaw
  • Student
  • Student
  • Avatar de Usuario
  • Registrado: Dic 30, 2008
  • Mensajes: 91
  • Loc: Tennessee
  • Status: Offline

Nota Junio 10th, 2009, 2:59 pm

Ok, soy simplemente tener una congelación de cerebro completo aquí. Im ejecuta un bucle, que se presentará el tema de mi en el campo tp_topic y no importa cuántos temas que tengo, siempre lo hará, sin embargo, quiero también en la fila misma base de datos para presentar la lectura en el campo tp_read. Cada vez que intento correr dos lazos en ambos matriz, la matriz textbx y la matriz readbx, termino con los datos del anuncio dos veces, porque su funcionamiento dos bucles, sin embargo, no puedo encontrar la manera de conseguir que sólo después de un registro para tanto el textbx y el readbx que están en la posición misma matriz. Así que, si tengo la Ciencia en textbx [0] y yo tenemos el capítulo 1 en readbx [0], quiero que ambos estar en el mismo registro en la base de datos para los campos de tp_topic y tp_read. Aquí está mi caja de entrada:

Código: [ Select ]
<input type='text' name='textbx[]' size='49'/> <input type='text' name='readbx[]' size='49'/>


Y hasta ahora, aquí está mi script de acción y #058;

Código: [ Select ]
if (isset($_POST['submit'])){
     $topics = $_POST['textbx'];
     $reads = $_POST['readbx'];


foreach($topics as $topic) {
    $query = "INSERT INTO SNP_topics (tp_topic, tp_read)
        VALUES ('$topic', '$read')";
            $results = mssql_query($query, $connection);
            if ($results) {
            } else {
            die("Database query failed: " . mssql_error());
            }
}
    }
  1. if (isset($_POST['submit'])){
  2.      $topics = $_POST['textbx'];
  3.      $reads = $_POST['readbx'];
  4. foreach($topics as $topic) {
  5.     $query = "INSERT INTO SNP_topics (tp_topic, tp_read)
  6.         VALUES ('$topic', '$read')";
  7.             $results = mssql_query($query, $connection);
  8.             if ($results) {
  9.             } else {
  10.             die("Database query failed: " . mssql_error());
  11.             }
  12. }
  13.     }



¿Alguna sugerencia????

¡Gracias!

Jordon
  • Dorky
  • Novice
  • Novice
  • No Avatar
  • Registrado: Jun 08, 2009
  • Mensajes: 15
  • Status: Offline

Nota Junio 10th, 2009, 3:28 pm

i bien, así estoy teniendo algunos problemas de la eliminación de las barras del primer bucle en esto, pero creo que el primer bucle hace algo así como que usted está buscando. Tengo algo de código adicional para los comentarios sobre mi variables, de modo que usted querrá tener esto en cuenta al revisar esto.

Código: [ Select ]
<?php

$pspell_link = pspell_new("en");
if(isset($_GET['text'])) {
$words = stripslashes($_GET['text']) ; }
echo "<form method='get' action='spell.php'>";


if (isset($_GET['0'])) echo "0";
{
foreach($proces as $key0 => $marker) 
{
$value = split('[ ]', $marker ); echo "Value : |0| $value[0] |1| $value[1] |Key| $key0 <hr>";
$value0[] = $value[0] ; $value1[] = $value[1] ;
echo "Print Value Stage 1:"; print_r($value0); print_r($value1); echo "<hr>";
}
$print = str_replace( $value0 , $value1 , $words );

}


if(!isset($_GET['0']))
{
$print = $words;
}







if (isset($_GET['check']))
{ echo "<b><i> $words </i></b><hr>";
$string = split('[ ]', $words); foreach($string as $key1 => $word)
if (!pspell_check($pspell_link, $word))
{
echo "<hr><b><i>$word</i></b><br>"; $suggestions = pspell_suggest($pspell_link, $word);
foreach($suggestions as $key2 => $suggestion)
{
    $send = "$word $suggestion"; echo "<input type='checkbox' name='$key1' value='$send'>$suggestion<br>";
}
}
}


echo "<hr><textarea name='text'class='textarea' type='text/plain' rows='15' cols='40'>$print</textarea><hr>";
if(!isset($_GET['check'])) { echo "<button name='check' value='check check' type='submit'>Check Spelling</button>"; }
if(isset($_GET['check'])) { echo "<button name='done' value='done done' type='submit'>Done</button>"; }
echo "</form>";

unset($print);

?>
  1. <?php
  2. $pspell_link = pspell_new("en");
  3. if(isset($_GET['text'])) {
  4. $words = stripslashes($_GET['text']) ; }
  5. echo "<form method='get' action='spell.php'>";
  6. if (isset($_GET['0'])) echo "0";
  7. {
  8. foreach($proces as $key0 => $marker) 
  9. {
  10. $value = split('[ ]', $marker ); echo "Value : |0| $value[0] |1| $value[1] |Key| $key0 <hr>";
  11. $value0[] = $value[0] ; $value1[] = $value[1] ;
  12. echo "Print Value Stage 1:"; print_r($value0); print_r($value1); echo "<hr>";
  13. }
  14. $print = str_replace( $value0 , $value1 , $words );
  15. }
  16. if(!isset($_GET['0']))
  17. {
  18. $print = $words;
  19. }
  20. if (isset($_GET['check']))
  21. { echo "<b><i> $words </i></b><hr>";
  22. $string = split('[ ]', $words); foreach($string as $key1 => $word)
  23. if (!pspell_check($pspell_link, $word))
  24. {
  25. echo "<hr><b><i>$word</i></b><br>"; $suggestions = pspell_suggest($pspell_link, $word);
  26. foreach($suggestions as $key2 => $suggestion)
  27. {
  28.     $send = "$word $suggestion"; echo "<input type='checkbox' name='$key1' value='$send'>$suggestion<br>";
  29. }
  30. }
  31. }
  32. echo "<hr><textarea name='text'class='textarea' type='text/plain' rows='15' cols='40'>$print</textarea><hr>";
  33. if(!isset($_GET['check'])) { echo "<button name='check' value='check check' type='submit'>Check Spelling</button>"; }
  34. if(isset($_GET['check'])) { echo "<button name='done' value='done done' type='submit'>Done</button>"; }
  35. echo "</form>";
  36. unset($print);
  37. ?>
Moderator Remark: Added [code] tags
  • jordonshaw
  • Student
  • Student
  • Avatar de Usuario
  • Registrado: Dic 30, 2008
  • Mensajes: 91
  • Loc: Tennessee
  • Status: Offline

Nota Junio 11th, 2009, 12:43 pm

Gracias a todos por su ayuda!!! Terminé averiguar la solución y quería compartir, en caso de que alguien más estaba teniendo el mismo problema. Básicamente, he añadido un campo en mi base de datos llamada tp_num. Luego a las variables establecidas en la parte superior de mi script = 0. Entonces corrió dos bucles, el primer bucle de la matriz textbx. Al comienzo de mi ciclo, me puse mi varible que fue = 0 para agregar cada vez que en bucle. Entonces se me consulta para insertar la varible al campo tp_num y los datos de la matriz en el campo de tp_topic. Entonces corrió un segundo bucle que se sumaba a mi otra varible que se = 0, cada vez que en bucle y en lugar de hacer una inserción, hice una actualización de la tabla, donde las dos variables tp_num en el mismo. Básicamente, el script se veía así:

Código: [ Select ]
$topicnm = 0;
$readnm = 0;

foreach($topics as $topic) {
    $topicnm++;
    $query2 = "INSERT INTO SNP_topics (tp_num, tp_topic)
        VALUES ('$topicnm', '$topic')";
            $results2 = mssql_query($query2, $connection);
            if ($results2) {
            } else {
            die("Database query failed: " . mssql_error());
            }
        }

foreach($reads as $read) {
    $readnm++; 
    $query3 = "UPDATE SNP_TOPICS SET
                tp_read = '{$read}'
            WHERE tp_num = '{$readnm}'";
            $results3 = mssql_query($query3, $connection);
            if ($results3) {
            } else {
            die("Database query failed: " . mssql_error());
            }
    }
  1. $topicnm = 0;
  2. $readnm = 0;
  3. foreach($topics as $topic) {
  4.     $topicnm++;
  5.     $query2 = "INSERT INTO SNP_topics (tp_num, tp_topic)
  6.         VALUES ('$topicnm', '$topic')";
  7.             $results2 = mssql_query($query2, $connection);
  8.             if ($results2) {
  9.             } else {
  10.             die("Database query failed: " . mssql_error());
  11.             }
  12.         }
  13. foreach($reads as $read) {
  14.     $readnm++; 
  15.     $query3 = "UPDATE SNP_TOPICS SET
  16.                 tp_read = '{$read}'
  17.             WHERE tp_num = '{$readnm}'";
  18.             $results3 = mssql_query($query3, $connection);
  19.             if ($results3) {
  20.             } else {
  21.             die("Database query failed: " . mssql_error());
  22.             }
  23.     }


No sé si esta era la solución ideal, pero funciona. Bascially, soy capaz de publicar los datos de la matriz de dos, y mantener los datos de las matrices que están en la misma posición, en el mismo registro de la base de datos.

He pasado tanto tiempo en esto que casi me caiga una lágrima cuando efectivamente trabajadas! :lol:

Una vez más, gracias por toda la ayuda!

Jordon
  • yomi
  • Graduate
  • Graduate
  • Avatar de Usuario
  • Registrado: Abr 02, 2008
  • Mensajes: 117
  • Loc: Nigeria
  • Status: Offline

Nota Junio 12th, 2009, 7:58 am

gran :idea: ! congrats!
  • Dorky
  • Novice
  • Novice
  • No Avatar
  • Registrado: Jun 08, 2009
  • Mensajes: 15
  • Status: Offline

Nota Junio 15th, 2009, 7:00 am

sin problemas amigo. alegro de que pude ayudar. cual es aún más asombroso es que sólo han sido en php por aproximadamente 3 semanas. jajaja.

Publicar Información

  • Total de mensajes en este tema: 10 mensajes
  • Usuarios navegando por este Foro: No hay usuarios registrados visitando el Foro y 180 invitados
  • No puede abrir nuevos temas en este Foro
  • No puede responder a temas en este Foro
  • No puede editar sus mensajes en este Foro
  • No puede borrar sus mensajes en este Foro
  • No puede enviar adjuntos en este Foro
 
 

© 2011 Unmelted, LLC. Ozzu® es una marca registrada de Unmelted, LLC