2017-09-08 43 views
1

嗨,我已经创建了一个简单的插入到数据库的功能和上传自己的文件到数据库中,但没有被插入到数据库中则只会出现上传文件在上传文件上但不在数据库上。无法将信息插入到数据库所在的学生进入他/她的信息

的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="[email protected]"/><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

谢谢您的帮助

+0

请使用准备好的语句。这真的很有帮助。 Mysqli支持它。你现在拥有的是超出风险的,所以它不保存任何东西是一件幸事。此外,它不工作的原因很简单,因为你永远不执行查询 – Akintunde007

回答

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 
} 
+0

感谢您的留言,我将确保使用准备statments ......我增加了查询,得到的数据插入,但上传文件没有被插入数据库 –

+0

检查我的更新答案@abdallahalsawaqi – Akintunde007

+0

太感谢你了它的工作...我肯定会使用预准备statments太感谢你了 –

0

试试这个为您的连接,$conn = mysqli_connect($servername, $username, $password, $dbname);和你的$ SQL后mysqli_query($conn, $sql);,你现在可以做一些重定向。

+0

你不需要这样做。你可以采取程序化的方式或面向对象的方式。 OP选择了后者。唯一需要的是执行查询。那并修复安全漏洞 – Akintunde007

+0

好吧,我同意你的意见。 :) –

相关问题