无法将信息插入数据库

时间:2017-09-08 06:32:04

标签: php mysqli upload insert

您好我创建了一个简单的插入数据库功能,学生输入他/她的信息并将他们的文档上传到数据库中,但没有任何内容插入到数据库中,只有上传的文件出现在上传文件中但不在数据库。

html代码:

<form  accept-charset="utf-8"  action="page.php"  enctype="multipart/form-data"  id="wb_Form1" name="form" method="post"  data-toggle="validator" role="form" >
<label>Student Name :</label>
<input type="text" name="stu_name" id="name" required="required" placeholder="Please Enter Name"/><br /><br />



<label>Student Email :</label>
<input type="email" name="stu_email" id="email" required="required" placeholder="john123@gmail.com"/><br/><br />
<label>Student City :</label>


<select name="stu_city">



<option value="works">test</option>

<option value="works3">test</option>



</select>

<label>Image:</label><input type="file" name="image">


<input type="submit" value=" Submit " name="submit"/><br />

</form>

php代码:

<?php
if(isset($_POST["submit"])){
$servername = "localhost";

$username = "root";

$password = "";

$dbname = "test";



$conn = new mysqli($servername, $username, $password, $dbname);



if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

}

  $fileinfo=PATHINFO($_FILES["image"]["name"]);


$newFilename=$fileinfo['filename'] ."_". time() . "." . $fileinfo['extension'];



move_uploaded_file($_FILES["image"]["tmp_name"],"upload/" . $newFilename);
$location="upload/" . $newFilename;



$sql = "INSERT INTO students (student_name, student_email, student_city,img_location)




VALUES ('".$_POST["stu_name"]."','".$_POST["stu_email"]."','".$_POST["stu_city"]."','".$_POST["location"]."')";

header('location:index.php');

}

?>

file hierarchy:

database structure

感谢您的帮助

3 个答案:

答案 0 :(得分:1)

您没有执行查询。你刚刚进行了查询。

注意:更好的方法是“准备”语句而不是创建自己的查询。这将使您免于SQL注入和意外中断查询。

检查出来:

https://www.w3schools.com/php/php_mysql_prepared_statements.asp

答案 1 :(得分:0)

您需要执行查询。你所拥有的只是一个字符串。根据我的评论,您需要使用预准备语句。您的代码存在风险。您还要为文件位置插入错误的变量。使用$location变量但要插入,请添加此

$conn->query($sql);

使用预准备语句,执行此操作

// prepare and bind
$stmt = $conn->prepare("INSERT INTO students (student_name, student_email, student_city,img_location) VALUES (?, ?, ?,?)");//prepares the query. This returns true/false
$stmt->bind_param("ssss", $_POST["stu_name"], $_POST["stu_email"], $_POST["stu_city"],$location);//bind the variables to placeholders to prevent SQL injections
if($stmt->execute() === TRUE){//check if everything went well(executed!)
  echo 'Record Saved';
} else {
  echo 'Error BEcause '.$stmt->error;//get error if something went wrong
}

答案 2 :(得分:0)

尝试使用此连接,$conn = mysqli_connect($servername, $username, $password, $dbname);并在$ sql为mysqli_query($conn, $sql);后,您现在可以进行重定向。