2013-11-09 19 views
0

我目前正在通過mysql/php生成一個表單。我有超過1500輸入具有獨特的價值,我想將它們插入到一個MySQL表(1個值/行)MySQL插入 - 來自使用名稱數組的輸入的值。 (PHP)

我創建的形式是這樣的:

echo "<input type='text' name='combination[]' value='justsometext". $row['name'] ."'><br />"; 

我有1500倍左右的投入像這樣,我想將它們插入一列,我該怎麼辦?

我使用下面的代碼插入,但它僅將0而不是實際值:

extract($_POST); 
foreach ($combination as $comb) { 
    //if your table has only one field inside: 
    $query = mysql_query("INSERT INTO tablename VALUES('".$comb."')"); 
} 

又如:

foreach ($_POST['combination'] as $combination) { 
$sql="INSERT INTO alphabet_combination (combination) 
VALUES 
('$combination')"; 
} 
if (!mysqli_query($con,$sql)) 
{ 
die('Error: ' . mysqli_error($con)); 
} 
+1

聽起來像一個可怕的想法,1500個輸入到1列?你想用這個做什麼? – Jonast92

+0

爲什麼你有1500個輸入??你必須認爲更好 –

+0

我是基於來自另一個數據庫的值生成這些輸入,所以每個輸入都有不同的值。我有一個名爲組合的列,我希望每個輸入值都存儲在其中,所以基本上1500個輸入將生成具有不同值的1500行。 – alexisdevarennes

回答

1

首先:How can I prevent SQL injection in PHP?

第二:1500個輸入?哇...你必須仔細檢查你的php.ini配置是否可以處理它。

如果你真的想在一列中放1500個值 - 也許你應該考慮serialize數組並保持這種方式?

在準備好的聲明,這將是這樣的:

$combinations = serialize($_POST['combination']); 

$q = mysqli_prepare($con, 'INSERT INTO alphabet_combination (combination) VALUES (?)'); 
mysqli_stmt_bind_param($q, 's', $combinations); 
mysqli_stmt_execute($q); 

如果你想爲每個值單INSERT進行提交,之後在數據庫將於明年1500行:

$q = mysqli_prepare($con, 'INSERT INTO alphabet_combination (combination) VALUES (?)'); 
mysqli_stmt_bind_param($q, 's', $combination); 

foreach ($_POST['combination'] as $combination) { 
    mysqli_stmt_execute($q); 
} 
+0

這樣做了,非常感謝!太棒了。 – alexisdevarennes

0

提交表單後,試試這個代碼隨着形式的另一種想法:

<?php 
if(isset($_POST['btnsubmit'])){ 
    extract($_POST); 
    foreach ($sample as $samp) { 
     $query = mysql_query("INSERT INTO tablename VALUES('".$samp."')"); 
    } 
} 
?> 
<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Sample</title> 
</head> 
<body> 
    <form action="<?php echo $_SERVER['PHP_SELF']?>" method="post"> 
     <input type="text" name="sample[]" value="hello1"><br> 
     <input type="text" name="sample[]" value="hello2"><br> 
     <input type="text" name="sample[]" value="hello3"><br> 
     <input type="text" name="sample[]" value="hello4"><br> 
     <input type="text" name="sample[]" value="hello5"><br> 
     <input type="submit" name="btnsubmit" value="Submit"> 
    </form> 
</body> 
</html> 
+0

這似乎是工作,但它只是插入最後一次輸入的值。所以我最終得到1499行,其中0和1500行的正確值,即thistextwascombined。 – alexisdevarennes