如何分离数据并将其注册到数据库中
Posted
技术标签:
【中文标题】如何分离数据并将其注册到数据库中【英文标题】:How to separate data and register it in a database 【发布时间】:2016-04-02 08:35:08 【问题描述】:我正在尝试分离我在此处获得的数据并尝试将其注册到数据库中。
我使用如下所示的表单获取数据。
var max_input_fields=10;
var delimiter='|';
function http( data, callback )
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function()
if( xhr.readyState==4 && xhr.status==200 ) callback.call( this, xhr.response );
;
xhr.open( 'POST', document.location.href, true );
xhr.send( data );
function cbhttp(r)
document.querySelectorAll('output')[0].innerhtml=r
function bindEvents()
var oBttnAdd=document.getElementById('bttnadd');
var oBttnSub=document.getElementById('bttnsub');
var oForm=document.getElementById('dynelems');
var oParent=document.getElementById('loopdiv');
oBttnSub.onclick=function(e)
/* scan the form and get values from all elements ( including dynamcially added ) and submit the form via xhr */
var col=oForm.querySelectorAll('input[type="text"],textarea,select');
var data=new FormData();
data.append('delimiter',delimiter);
for( var n in col ) if( col[n] && col[n].nodeType==1 )
data.append( col[n].name, col[n].value.replace( delimiter, '' ) + delimiter );
http.call( this, data, cbhttp );
;
oBttnAdd.onclick=function(e)
/* Add new rows based upon selected option from dropdown menu */
var col=oParent.querySelectorAll('section[data-id]');
var length=col.length;
if( length < max_input_fields )
var newid=parseInt( col[ length-1 ].dataset.id ) + 1;
var clone=oParent.childNodes[1].cloneNode( true );
clone.dataset.id=newid;
/* Set new name for the textarea */
clone.childNodes[3].childNodes[1].name='videolink'+newid;
oParent.appendChild( clone );
document.addEventListener('DOMContentLoaded', bindEvents,false);
<form action="adddilemman.php" id="dynelems" method="post" enctype="multipart/form-data">
<br>
<div id='loopdiv'>
<?php
/* Data-id is used by js to determine next suitable id */
echo "
<section data-id=1>
<h2>Dilemma</h2>
<div>Video länk:<br><textarea rows='1' cols='40' name='videolink1'></textarea></div>";
for( $i=1; $i <= 4; $i++ )
/* Add four text fields and four select menus */
echo "
<div>
Answer: <input type='text' name='answer$i[]'/>
<select name='options$i[]'>";
/* Add options to each select menu */
for( $j=1; $j <= 10; $j++ )
echo "<option value=$j>$j";
/* Close each nested div & select menu */
echo "
</select>
</div>";
/* Close initial section */
echo "
</section>";
?>
</div>
<div class='input_fields_wrap'>
<div></div>
</div>
<input id='bttnadd' type='button' name='add_field_button' value='Lägg till fler svar'/>
<input id='bttnsub' type='submit' name='sub' value='Submit'/>
</form>
<output></output>
我使用“adddilemman.php”来显示数据只是为了看看它是否正常工作。但我现在知道如何在数据库中注册这些数据。 PS我想在两个不同的表中注册它(一个表中的textarea和另一个表中的答案)
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' )
ob_clean();
/* This is here only to simplify development and display here */
$delimiter=isset( $_POST['delimiter'] ) ? $_POST['delimiter'] : '|';
/* process form submission: for testing purposes just echo out data sent */
foreach( $_POST as $field => $value )
if( $field!='delimiter' )
if( is_array( $value ) ) echo 'Array values: '.$field.'='.rtrim( str_replace( $delimiter, ',', implode( ' ', $value ) ), ',' ).'<br />';
else echo 'String value: '.$field.'='.trim( str_replace( $delimiter, '', $value ) ).'<br />';
exit();
?>
有什么建议我可以如何分离这些数据并将其注册到数据库中?
【问题讨论】:
你的 mysql 表是什么样的?请提供您需要使用的数据的示例。您希望使用哪个:PDO 或 MySQLi?你试过什么代码? @Twisty 你可以在下一条评论中看到我的代码 【参考方案1】:您可能希望这样设置表单:
<textarea rows='1' cols='40' name='videolink1'><?php echo isset($_POST['videolink1'])?$_POST['videolink1']:""; ?></textarea>
<?php
for( $i=1; $i < 5; $i++ )
/* Add four text fields and four select menus */
?>
<div>
<label>Answer:</label>
<input type='text' name='answer[<?php echo $i; ?>]' value="<?php echo isset($answer[$i])?$answer[$i]:''; ?>" />
<select name='options[<?php echo $i; ?>]'>
<?php
for( $j=1; $j <= 10; $j++ )
if($options[$i] == $j)
echo "\t\t\t\t\t<option selected='selected' value=$j>$j</option>\r\n";
else
echo "\t\t\t\t\t<option value=$j>$j</option>\r\n";
?>
</select>
</div>
<?php
?>
我会像这样准备帖子数据:
<?php
$vidlink = "";
$answers = array();
$options = array();
if(isset($_POST['sub']))
$vidlink = htmlentities($_POST['videolink1']);
for($i=1;$i<=count($_POST['answer']);$i++)
$answer[$i] = $_POST['answer'][$i];
$options[$i] = $_POST['options'][$i];
?>
这会将答案和选项的内容放在它们自己的数组中,但具有相同的索引。您可以以任何您喜欢的方式循环并将它们放置在数据库中。这是一个例子:
$con = mysqli_connect("localhost", "root", "", "wildfire");
if($con === false)
die("ERROR: Could not connect. " . mysqli_connect_error());
for($i=1;$i<=$count($answer);$i++)
if ($stmt = mysqli_prepare($con, "INSERT INTO answer_det ('aid', 'answer', 'points') VALUES (?, ?, ? )"))
mysqli_stmt_bind_param($stmt, "isi", $i, $answer[$i], $options[$i]);
mysqli_stmt_execute($stmt);
这是我在 phpfiddle.org 上用于测试的所有代码:
<?php
$vidlink = "";
$answers = array();
$options = array();
if(isset($_POST['sub']))
$vidlink = htmlentities($_POST['videolink1']);
for($i=1;$i<=count($_POST['answer']);$i++)
$answer[$i] = $_POST['answer'][$i];
$options[$i] = $_POST['options'][$i];
?>
<html>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" id="dynelems" method="post" enctype="multipart/form-data">
<div id='loopdiv'>
<section data-id=1>
<h2>
Dilemma
</h2>
<div>
Video länk:
<br />
<textarea rows='1' cols='40' name='videolink1'><?php echo isset($_POST['videolink1'])?$_POST['videolink1']:""; ?></textarea>
</div>
<?php
for( $i=1; $i < 5; $i++ )
/* Add four text fields and four select menus */
?>
<div>
<label>Answer:</label>
<input type='text' name='answer[<?php echo $i; ?>]' value="<?php echo isset($answer[$i])?$answer[$i]:''; ?>" />
<select name='options[<?php echo $i; ?>]'>
<?php
for( $j=1; $j <= 10; $j++ )
if($options[$i] == $j)
echo "\t\t\t\t\t<option selected='selected' value=$j>$j</option>\r\n";
else
echo "\t\t\t\t\t<option value=$j>$j</option>\r\n";
?>
</select>
</div>
<?php
?>
</section>
</div>
<div class='input_fields_wrap'>
<div>
</div>
</div>
<input id='bttnadd' type='button' name='add_field_button' value='Lägg till fler svar'/>
<input id='bttnsub' type='submit' name='sub' value='Submit'/>
</form>
<output>
<?php
if(isset($_POST['sub']))
htmlentities(var_export($_POST));
var_export($answer);
var_export($options);
</output>
</html>
【讨论】:
以上是关于如何分离数据并将其注册到数据库中的主要内容,如果未能解决你的问题,请参考以下文章
如何在laravel中为每个用户生成唯一的随机值并将其添加到数据库中
如何在 laravel 中为每个用户生成唯一的自动增量值并将其添加到数据库中