我正在尝试将数据插入到我的数据库中,但它不起作用,我没有错误。我想我的PHP代码出了问题,但是我在网上尝试了一些适用于其他人的解决方案,但不适合我。
我的HTML代码:
<!Doctype HTML>
<html>
<title>Neues Projekt</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="UTF-8">
<head>
<h1>Neues Projekt anlegen</h1>
</head>
<body>
<form action="php_skript.php" method="post">
<p>Name des Projekts:</p>
<input type="text" name="name">
<p>Ort des Projekts:</p>
<input type="text" name="ort">
<p>Straße des Projekts:</p>
<input type="text" name="strasse">
<p>Projektleiter:</p>
<input type="text" name="projektleiter">
<br>
<input type="submit" value="Submit">
</form>
Bilder hinzufügen:
<form method="post" enctype="multipart/form-data">
<input type="file" name="image_data" multiple>
</form>
</form>
</body>
</html>
这里是我的PHP代码:
<?php
$user = 'root';
$password = 'root';
$db = 'projekte_db';
$host = 'localhost';
$port = 3306;
$name=mysqli_real_escape_string($mysqli, $_POST['name']);
$ort=mysqli_real_escape_string($mysqli, $_POST['ort']);
$strasse=mysqli_real_escape_string($mysqli, $_POST['strasse']);
$projektleiter=mysqli_real_escape_string($mysqli, $_POST['projektleiter']);
$mysqli=new mysqli($host, $user, $password, $db);
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$mysqli->query("INSERT INTO Projekt (name,ort,straße,projektleiter) VALUES ('$name','$ort','$strasse','$projektleiter')");
$mysqli->close();
?>
答案 0 :(得分:1)
您的$mysqli
变量需要之前:
$mysqli=new mysqli($host, $user, $password, $db); //put here
$name=mysqli_real_escape_string($mysqli, $_POST['name']);
$ort=mysqli_real_escape_string($mysqli, $_POST['ort']);
$strasse=mysqli_real_escape_string($mysqli, $_POST['strasse']);
$projektleiter=mysqli_real_escape_string($mysqli, $_POST['projektleiter']);
//$mysqli=new mysqli($host, $user, $password, $db); remove here
另外,我建议您使用参数化查询,它更安全。
答案 1 :(得分:1)
由于您正在插入数据,请尝试使用预准备语句
$user = 'root';
$password = 'root';
$db = 'projekte_db';
$host = 'localhost';
$mysqli = new mysqli($host, $user, $password, $db);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$name=$_POST['name'];
$ort=$_POST['ort'];
$strasse=$_POST['strasse'];
$projektleiter=$_POST['projektleiter'];
/* create a prepared statement */
if ($stmt = $mysqli->prepare("INSERT INTO `Projekt` (`name`,`ort`,`straße`,`projektleiter`) VALUES (?,?,?,?)")) {
/* bind parameters for markers */
/* use s for strings, i for integer,d for double, b for blob */
$stmt->bind_param("ssss", $name,$ort,$strasse,$projektleiter);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
$mysqli->close();