gpt4 book ai didi

php - 使用foreach循环传递两个变量

转载 作者:行者123 更新时间:2023-11-29 03:27:19 26 4
gpt4 key购买 nike

这是一个动态添加文本字段的代码。当我们单击一个链接时,它会自动添加文本字段并将数据传递给数据库。但是现在我希望单击链接时有两个文本字段并将值传递给数据库。如何实现这一点?
代码如下所示
index.php索引

 <?php 
require("dbconn.php");
?>

<html>
<head>
<title></title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var counter = 0;
$(function(){
$('p#add_field').click(function(){
counter += 1;
$('#container').append(
'<strong>Hobby No. ' + counter + '</strong><br />'
+ '<input id="field_' + counter + '" name="dynfields[]' + '" type="text" /><br />'
+'<input id="field_' + counter + '" name="name[]' + '" type="text" /><br />' );

});
});
</script>

<body>

<?php
if (isset($_POST['submit_val'])) {
if ($_POST['dynfields']) {
foreach ( $_POST['dynfields'] as $key=>$value ) {
$values = mysql_real_escape_string($value);
$query = mysql_query("INSERT INTO my_hobbies (hobbies) VALUES ('$values')", $connection );

}
}

echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Hobbies Added</h2></i>";

mysql_close();
}
?>
<?php if (!isset($_POST['submit_val'])) { ?>
<h1>Add your Hobbies</h1>
<form method="post" action="">


<div id="container">
<p id="add_field"><a href="#"><span>Click To Add Hobbies</span></a></p>
</div>

<input type="submit" name="submit_val" value="Submit" />
</form>
<?php } ?>

</body>
</html>

index.php页面中,单击添加文本字段将提供动态文本字段。我要添加两个或多个文本字段并将值传递给数据库

最佳答案

可能是您的mysql连接字符串不正确(如果您将$values设置为空,请通过删除mysql_real_escape_stringecho "INSERT INTO my_hobbies (hobbies) VALUES ('$value')"来测试替代项,并查看这是否是所需的sql字符串)。
注意:由于mysql已被弃用,请开始使用mysqli或pdo。
你可以这样尝试:

    <?php

if (isset($_POST['submit_val'])) {
$mysqli = new mysqli('localhost','root','root','hobby');//make sure your connection is made
if (mysqli_connect_errno()) {
echo "Problem in connection";
exit();
}
if ($_POST['dynfields']) {
foreach ( $_POST['dynfields'] as $key=>$value ) {
$values = $mysqli->real_escape_string($value);
// echo $values;
$sql= "INSERT INTO my_hobbies (hobbies) VALUES ('$values')";
//echo $sql;
$mysqli->query($sql);
if($mysqli->errno > 0){
echo "PROBLEM WHILE SAVING";
exit;
}
}
}

echo "<i><h2><strong>" . count($_POST['dynfields']) . "</strong> Hobbies Added</h2></i>";

mysql_close();
}
?>

关于php - 使用foreach循环传递两个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34408396/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com