好的,我能够编写完整的代码,所以我现在可以将数据添加到我的数据库中。但我唯一的问题是,我希望我在html字段中输入的文本显示在数据库中。那么我如何将我输入html文件的数据转到php文件然后将数据发送到数据库呢?
代码:
<html>
<head>
<title>Tabelle</title>
<form action="phpRICHTIG.php" action="post"/>
Test1: <input type="text" name="Test1"/><br/>
Test2: <input type="text" name="Test2"/><br/>
Test3: <input type="text" name="Test3"/><br/>
Test4:<input type="text" name="Test4"/><br/>
<input type="submit" value="Absenden"/>
</form>
</body>
</html>
<?php
include "htmltest.php";
$link = mysqli_connect("localhost", "root", "", "vanille");
if($link === false){
die("Konnte nicht verbinden. " . mysqli_connect_error());
}
$sql = "INSERT INTO vanille (Test1, Test2, Test3, Test4) VALUES ('test', 'test', 'test', 'test')";
if(mysqli_query($link, $sql)){
echo "Hat geklappt.";
} else{
echo "Hat nicht geklappt und das hat nicht funktioniert: $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>
答案 0 :(得分:2)
以下是您的代码更新:
<?php
//if the code on phpRICHTIG.php and htmltest.php is the same then you did need this line
//include "htmltest.php";
$link = mysqli_connect("localhost", "root", "", "vanille");
if($link === false){
die("Konnte nicht verbinden. " . mysqli_connect_error());
}
//First we check if we have some data posted .
if(isset($_POST)){
//Then we set them to var
//You will have to securize that by yourself later, insert directly $_POST is a huge security breach
$test1 = $_POST['Test1'];
$test2 = $_POST['Test2'];
$test3 = $_POST['Test3'];
$test4 = $_POST['Test4'];
$sql = "INSERT INTO vanille (Test1, Test2, Test3, Test4) VALUES ('$test1', '$test2', '$test3', '$test4')";
if(mysqli_query($link, $sql)){
//It worked
echo "Hat geklappt.";
} else {
//It failed
echo "Hat nicht geklappt und das hat nicht funktioniert: $sql. " . mysqli_error($link);
}
}else{
echo 'No form submitted';
}
mysqli_close($link);
?>
答案 1 :(得分:1)
检查变量是否已设置,如果已设置,则定义它们。然后使用查询插入这些值。请参阅以下代码:
<?php
//include "htmltest.php"; you don't need to do this
$link = mysqli_connect("localhost", "root", "", "vanille");
if($link === false){
die("Konnte nicht verbinden. " . mysqli_connect_error());
}
if (isset($_POST['Test1']))//check if it's set
$test1 = $_POST['Test1'];//define it
if (isset($_POST['Test2']))
$test2 = $_POST['Test2'];
if (isset($_POST['Test3']))
$test3 = $_POST['Test3'];
if (isset($_POST['Test4']))
$test4 = $_POST['Test4'];
//make sure you escape values before inserting it to database
$sql = "INSERT INTO vanille (Test1, Test2, Test3, Test4) VALUES ('".$test1."', '".$test2."', '".$test3."', '".$test4."')";
//then insert it into your database through the query
if(mysqli_query($link, $sql)){
echo "Hat geklappt.";
} else{
echo "Hat nicht geklappt und das hat nicht funktioniert: $sql. " . mysqli_error($link);
}
mysqli_close($link);
?>
您最好在表单提交之前进行数据验证,以确保字段不为空。否则您将收到错误,或者您将空值插入数据库。