简体   繁体   中英

multiple save from result php

this form will store the same data in the amount of the result

 <form method="post" action="multi_insert.php">

  <input type="text" name="nis" placeholder="NIS"/>
  <input type="text" name="nama" placeholder="Nama"/>
    <input type="number" name="result" >

  <br/>

  <input type="submit" value="Post"/>
 </form>

"and this is source code for save named multi_insert.php "

include "koneksi.php";

for($i=0;$i<$_POST['result'];$i++){
 $nis = $_POST['nis'.$i];
 $nama= $_POST['nama'.$i];
 $query = "insert into SISWA(NIS,NAMA)values('$nis','$nama')";
 $mysqli->query($query);
}
$mysqli->close();

and this connectiondb or koneksi.php

$host = "localhost";
$username = "root";
$password = "";
$db_name = "SEKOLAH";
$mysqli = new mysqli($host, $username, $password, $db_name);
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;

$_POST['nis'.$i] is not exist..

you should use only $_POST['nis'] ..

i do correction for your code:

include "koneksi.php";

for($i=0;$i<$_POST['result'];$i++){
 $nis = $_POST['nis'];
 $nama= $_POST['nama'];
 $query = "insert into SISWA(NIS,NAMA)values('$nis','$nama')";
 $mysqli->query($query);
}
$mysqli->close();

 <form method="post" action="multi_insert.php"> <input type="text" name="nis" placeholder="NIS"/> <input type="text" name="nama" placeholder="Nama"/> <input type="number" name="result" > <br/> <button type="submit" >submit</button> </form> 

if($_POST['nis'] && $_POST['nama']) {
    $nis = $_POST['nis'];
    $nama= $_POST['nama'];
    $query = "insert into SISWA(NIS,NAMA)values('$nis','$nama')";
    $mysqli->query($query);
}
$mysqli->close();

if you need save multiple input value with same name you should use

 <input name="nama[]" /> <input name="nama[]" /> <input name="nama[]" /> 

instead of

 <input name="nama" /> 
and the value $_POST['nama'] will be an array

 if($_POST['nama']) { foreach($_POST['nama'] as $i => $v) { $query = "insert into SISWA(NAMA)values('$v')"; $mysqli->query($query); } } $mysqli->close(); 

If you use <input type="text" name="nama[]" /> , $_POST['nama'] is not an input value but an array.To get the value you should rather say

for($i=0;$i<count($_POST['nama']);$i++){
   $nama= $_POST['nama'][$i];
 }

That way u can the use $nama or whatever variable as a paramaeter in your PREPARED STATEMENT. Your method of using of using $_POST['nama'.$i] will work if you create manually or through javascript your inputs to be

<input type="text" name="name1"/>
<input type="text" name="name2"/> et.c

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM