有人可以告诉我我的代码在将表格值添加到坐标表中的位置不正确吗?我让用户在此页面之前输入要输入的坐标数(在此页面上生成文本框),然后输入坐标值并填充到数据库中。我一直得到数组到字符串转换错误,但无法解决它。
如果盒子的数量可以改变,如何插入值?如果用户只输入4,每个生成4行三个坐标(x,y,z)怎么办?这是我不明白的地方。如果只使用静态表单值,我可以获取表的值。
我是初学者,但慢慢地逐渐学习,并感谢积极和建设性的答案。
<head>
<title>Add Coordinate to Database</title>
</head>
<body>
<?php
if(isset($_POST['add'])) {
$dbhost = 'localhost';
$dbname = 'your_db_name';
$dbuser = 'John';
$dbpass = 'johns##password';
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser,
$dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO coordTable (x, y, z) VALUES (?, ?, ?)");
$stmt->bindParam(1, $_POST['textx']);
$stmt->bindParam(2, $_POST['texty']); //what is difference between bindParam/bindValue
$stmt->bindParam(3, $_POST['textz']);
$stmt->execute();
}
if(! get_coordinates() ) {
$textx = filter_input($_POST['textx']);
$texty = filter_input($_POST['texty']);
$textz = filter_input($_POST['textz']);
}else {
$textx = $_POST['textx'];
$texty = $_POST['texty'];
$textz = $_POST['textz'];
}
$sql = "INSERT INTO coordTable". "(x, y, z)
) ". "VALUES('$textx','$texty',$textz)";
?>
<form method="post" action="output_process.php">
<?php for ($counter = 1; $counter <= $num_boxes; $counter++) { ?>
(x<?php echo $counter; ?>:<input name="textx[]<?php echo $counter; ?>" type="text" value="">,
y<?php echo $counter; ?>: <input name="texty[]<?php echo $counter; ?>" type="text" value"">,
z<?php echo $counter; ?>: <input name="textz[]<?php echo $counter; ?>" type="text" value"">)<br><br>
<?php } ?>
<input name="button2" type="submit" value="Submit">
</form>
答案 0 :(得分:1)
正如其他作者所说,mysql_函数已经过时且在PHP 7中不起作用,您应该选择不同的东西。此外,您没有清理POST变量,恶意用户可以对您的数据库执行任何操作。
以下是现代PDO的替代品:
<?php
if(isset($_POST['add'])) {
$dbhost = 'localhost';
$dbname = 'your_db_name';
$dbuser = 'John';
$dbpass = 'johns##password';
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// prepare sql and bind parameters
$stmt = $conn->prepare("INSERT INTO coordTable (x, y, z) VALUES (?, ?, ?)");
for ($i = 0; $i < count($_POST['textx']); $i++) {
$stmt->bindParam(1, $_POST['textx'][$i]);
$stmt->bindParam(2, $_POST['texty'][$i]);
$stmt->bindParam(3, $_POST['textz'][$i]);
$stmt->execute();
}
}
?>
<form method="post" action="output_process.php">
<?php for ($counter = 1; $counter <= 5; $counter++): ?>
(x<?= $counter ?>: <input name="textx[]" type="text" value="<?= $counter ?>">,
y<?= $counter ?>: <input name="texty[]" type="text" value"<?= $counter ?>">,
z<?= $counter ?>: <input name="textz[]" type="text" value"<?= $counter ?>">)<br><br>
<?php endfor ?>
<input name="button2" type="submit" value="Submit">
</form>
答案 1 :(得分:0)
您的查询字符串如下所示:
$sql = "INSERT INTO coordTable". "(x, y, z)
) ". "VALUES('$textX','$textY',$textZ)";
而查询字符串应如下所示:
$sql = "INSERT INTO coordTable". "(x, y, z)
) ". "VALUES('$textX','$textY','$textZ')";