0

I have these textarea generated by while loop:

<form id='form_tbl' action='include/value.inc.php' method="POST"><input type="hidden" name="intrebare" value="1">
    <?php
    $sql = "SELECT NUME, PRENUME, TIP, ID
        FROM personal
        WHERE TIP <> 'Inactiv'
        ORDER BY NUME ASC";
    $result = $conn->query($sql);
    echo "<table><tr><th>NUME</th><th>NOTA</th><th>SUGESTII</th></tr>";
    while($row = $result->fetch_assoc()) {
      echo "<tr><td><input type='hidden' name ='id_personal[". $row['ID'] ."]' value='". $row["ID"]."'>" . $row["NUME"]. ' '. $row["PRENUME"]. "</td>";
      echo "<td><select name='nota_pers[". $row['ID'] ."]' autocomplete='off'><option disabled selected>nota</option>";
      for($i=1; $i<=10; $i++){ 
        echo "<option value='$i'>$i</option>\n";
      };
      echo "</select></td>";
      echo "<td><textarea name='sugestie' form='form_tbl' maxlength='200'></textarea></td></tr>";
    }
    echo '</table><button>NEXT ></button>';
    ?>
</form>

And value.inc.php:

<?php
include "bd_cnx.inc.php";
$insert_str = null;
$nota_pers = $_POST ['nota_pers'];
$intrebare = $_POST ['intrebare'];
$sugestie = $_POST ['sugestie'];

foreach ($nota_pers as $key => $value){
    $insert_str [] = '(' . $key . ', ' . $value . ', ' . $intrebare . ', ' . $sugestie .')';
}

$var = implode(', ', $insert_str);
$sql = "INSERT INTO chestionar (ID_PERSONAL, NOTA, INTREBAREA, SUGESTII) VALUES " . $var;
?>

When I test with echo '<pre>'.print_r($insert_str,true).'</pre><br>'; the browser generated an array as: [0] => (55, 5, 1, Array). How can I replace the array with the text from each textarea?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
ster
  • 199
  • 3
  • 14
  • 2
    First I'd escape the values you are inserting. http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – Shira Oct 23 '16 at 17:22
  • To convert array to string you can use `json_encode` or `implode` depending on your needs. But I see your SQL will not work, because you do not escape your values – Justinas May 16 '23 at 11:41

1 Answers1

-1

Make the name of the textarea also an array

<textarea name='sugestie[". $row['ID'] ."]' form='form_tbl' maxlength='200'></textarea>

In the foreach, use the $key to call the right array value

$insert_str [] = '(' . $key . ', ' . $value . ', ' . $intrebare . ', ' . $sugestie[$key] .')';

Extra tip: Escape the ' before putting it in your SQL query.

addslashes($sugestie[$key])
Remco K.
  • 644
  • 4
  • 19