使用PHP将表单上载到数据库
我正在尝试使用PHP将数据从form plus上传文件上传到服务器路径。在这方面,我能够实现上传文件和数据的功能,但在这方面,我想增加一个功能,其中,如果电子邮件已经存在,那么应该抛出一个警告,即电子邮件已经存在,pnly pdf文件应该被接受。我尝试了一些编码,但不起作用 任何大师都可以在下面的代码中添加代码块,以实现唯一电子邮件id的功能,并将文件类型限制为仅pdf使用PHP将表单上载到数据库,php,file-upload,Php,File Upload,我正在尝试使用PHP将数据从form plus上传文件上传到服务器路径。在这方面,我能够实现上传文件和数据的功能,但在这方面,我想增加一个功能,其中,如果电子邮件已经存在,那么应该抛出一个警告,即电子邮件已经存在,pnly pdf文件应该被接受。我尝试了一些编码,但不起作用 任何大师都可以在下面的代码中添加代码块,以实现唯一电子邮件id的功能,并将文件类型限制为仅pdf <?php include_once 'dbconfig.php'; if(isset($_POST['btn-
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-upload']))
{
$name = trim($_POST["uname"]);
$email = trim($_POST["uemail"]);
$exp = trim($_POST["uexp"]);
$desig = trim($_POST["udesig"]);
$tech = trim($_POST["utech"]);
$file = rand(1000,100000)."-".$_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder="uploads/";
// new file size in KB
$new_size = $file_size/1024;
// new file size in KB
// make file name in lower case
$new_file_name = strtolower($file);
// make file name in lower case
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($file_loc,$folder.$final_file))
{
$sql="INSERT INTO tbl_uploads(name,email,exp,desig,tech,file,type,size) VALUES('$name','$email','$exp','$desig','$tech','$final_file','$file_type','$new_size')";
mysql_query($sql);
?>
<script>
window.location.href='success.php';
</script>
<?php
}
else
{
?>
<script>
alert('error while uploading file');
window.location.href='index.php?fail';
</script>
<?php
}
}
?>
尝试将代码更改为
$sql = "SELECT COUNT(*) AS count from tbl_uploads where email = :email_id";
try {
$stmt = $DB->prepare($sql);
$stmt->bindValue(":email_id", $email, PDO::PARAM_STR);
$stmt->execute();
//only grabbing one row so use fetch instead of fetchAll
$result = $stmt->fetch(PDO::FETCH_ASSOC);
/*
*check if result is an array
*check is count exists in the array
* check if result['count'] gt 0
*/
if (is_array($result) && array_key_exists('count', $result) && $result["count"] > 0) {
$msg = "Email already exist";
$msgType = "warning";
}
有许多方法可以计算行数,在您的情况下,请更改为:
$stmt->execute();
$result = $stmt->fetchAll();
if (count($result) > 0) {
$msg = "Email already exist";
$msgType = "warning";
}
或者使用fetch
或不获取:
$stmt->execute();
if ($stmt->rowCount() > 0) {
$msg = "Email already exist";
$msgType = "warning";
}
或者,由于PHP是松散类型的,您可能只需要将其转换为整数:
if ((int)$result[0]["count"] > 0)
确保将电子邮件设置为db表中的主键,或者在表模式中为其设置唯一约束,而不仅仅是尝试通过php强制执行。我已经将序列号作为主要和唯一约束。因此,他试图从php强制执行
if ((int)$result[0]["count"] > 0)