通过PHP将日期值插入MySQL

时间:2017-05-03 16:23:45

标签: php mysql str-to-date

我正在尝试做的是标题意味着在创建的表中插入日期。

我完成了我的研究。我考虑过以下主题:

和其他人。

然而没有什么能真正解决这个问题。 $dob变量就是故意存在的。我需要确保它会随着用户的改变而改变。

这是我的PHP代码:

$firstName = $middleName = $lastName = $mobileNumber = $dob = $address = "";
$firstName0 = $middleName0 = $lastName0 = $mobileNumber0 = $dob0 = $address0 = "";
$dobErr = $addressErr = $mobilenumErr = $emailErr = $passwordErr = "";
$email = $password = $fnameErr = $mnameErr = $lnameErr = $conn = $data = "";
$email0 = $password0 = "";

require_once 'login.php';
$conn = new mysqli($hn, $un, $pw, $db);
if($conn->connect_error) die($conn->connect_error);

function test_input($data) {
    $data = trim($data);
    $data = stripslashes($data);
    $data = htmlspecialchars($data);
    return $data;
}

if(isset($_POST['submit'])) {
    // input validation

    if ($_SERVER["REQUEST_METHOD"] == "post") {
        if (empty($_POST["firstName"])) {
            $fnameErr = "Name is required";             
        } else {
            $firstName0 = test_input($_POST["firstName"]);              
        }
        if (empty($_POST["lastName"])) {
            $lnameErr = "Last name is required";        
        } else {
            $lastName0 = test_input($_POST["lastName"]);                
        }
        if (empty($_POST["dob"])) {
            $dobErr = "Date of birth is required";              
        } else {
            $dob0 = test_input($_POST["dob"]);              
        }
        if (empty($_POST["address"])) {
            $addressErr = "Address is required";                
        } else {
            $address0 = test_input($_POST["address"]);              
        }
        if (empty($_POST["mobileNumber"])) {
            $mobilenumErr = "Mobile number is required";                
        } else {
            $mobileNumber0 = test_input($_POST["mobileNumber"]);                
        }
        if (empty($_POST["email"])) {
            $emailErr = "Email is required";                
        } else {
            $email0 = test_input($_POST["email"]);
        }
        if (empty($_POST["password"])) {
            $passwordErr = "Password is required";              
        } else {
            $password0 = test_input($_POST["password"]);            
        }
    }
    if ($_SERVER["REQUEST_METHOD"] == "post") {
        // sanitizing the input
        $firstName = test_input($_POST["$firstName0"]);
        if (!preg_match("/^[a-zA-Z]*$/",$firstName)) {
            $nameErr = "Only letters are allowed";          
        }
        $middleName = test_input($_POST["$middleName0"]);
        $lastName = test_input($_POST["$lastName0"]);
        $dob = test_input($_POST["$dob0"]);
        $address = test_input($_POST["$address0"]);
        $mobileNumber = test_input($_POST["$mobileNumber0"]);
        $email = test_input($_POST["$email0"]);
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            $emailErr = "Invalid email format";         
        }
        $password = test_input($_POST["$password0"]);   
    }

    // sending valid data to the database   
    $query = "insert into details values" . "("$firstName","$middleName","$lastName",STR_TO_DATE("$dob","%Y/%m/%d"),"$address","$mobileNumber","$email", "$password")";
    $result = $conn->query($query);
    if(!$result) {
        echo 'Insert failed: $query<br>' . $conn->error . '<br><br>';
    } else { 
        echo 'Data saved !';
    }
}

我收到了这个错误:

  

插入失败:插入详细信息值('','','',STR_TO_DATE(“”,“%Y /%m /%d”),'','','','')   日期时间值不正确:''表示函数str_to_date

2 个答案:

答案 0 :(得分:1)

$query = "insert into details values ($firstName,$middleName,$lastName,STR_TO_DATE($dob,'%Y/%m/%d'),$address,$mobileNumber,$email, $password)";

答案 1 :(得分:0)

对于所有这些单独的字符串声明,我认为处理数组会更好。 PHP提供了一些很棒的数组函数。我将使用array_intersect_key()array_walk()implode()array_keys()。我已经留下了一些注释var_export(),以便您可以取消注释,看看过滤过程是如何工作的。

如果表单提交此$ _POST数组:

$_POST=array('firstName'=>'Mick','lastName'=>'MacKusa','dob'=>'2017/05/03',
             'address'=>'Home','mobileNumber'=>'v','email'=>'user@email.com',
             'password'=>'v','bogus'=>'Hacktastic');

到这个脚本:

<?php
require_once 'login.php';

$requireds=array('firstName'=>'Name is required','lastName'=>'Last name is required','dob'=>'Date of birth is required','address'=>'Address is required','mobileNumber'=>'Mobile number is required','email'=>'Email is required','password'=>'Password is required');

$inputs=array_intersect_key($_POST,$requireds);  // only handle desired elements in $_POST
// var_export($inputs);  // 'bogus'=>'Hacktastic' has beem removed

// create an array filled with empty elements
array_walk($inputs,function($v,$k)use(&$empties){if(empty($v)){$empties[$k]=$v;}});
// var_export($empties);

if(!is_null($empties)){  // if at least one required value is missing...
    $messages=array_intersect_key($requireds,$empties);  // create an array of "required" messages
    var_export($messages);  // handle this array however you wish
}else{  // all fields have a value
    //var_export($inputs);

    // do any necessary/specific validation or preparation on elements like: 

    // $inputs['password']=hash("sha256",$_POST["password"]); or something
    // never store anyone's unencrypted passwords
    // regarding data security, research AS MUCH AS POSSIBLE

    // check format of $inputs['dob'] and $inputs['email'], etc...

    // I prefer pdo where I can drop the $inputs array into the execute function,
    // but it may be less overwhelming for you to stay with mysqli for the time being

    if(!$conn=new mysqli($hn,$un,$pw,$db)){
        echo "Connection Error: ",$conn->connect_error;  // do not echo when live
    }elseif($stmt=$conn->prepare("INSERT INTO `details` (`".implode('`,`',array_keys($inputs))."`) VALUES (?,?,STR_TO_DATE(?,'%Y/%m/%d'),?,?,?,?)")){
        // to shrink bind_param code, use variadic expression or call_user_func_array
        if($stmt->bind_param('sssssss',$inputs['firstName'],$inputs['lastName'],$inputs['dob'],$inputs['address'],$inputs['mobileNumber'],$inputs['email'],$inputs['password']) && $stmt->execute()){
            echo "Success - New ID# is ",$stmt->insert_id;
        }else{
            echo "Statement Error: ",$stmt->error;  // do not echo when public
        }
        $stmt->close(); 
    }else{
        echo "Prepare Error: ",$conn->error;  // do not echo when public
    }
    $conn->close();
}
?>

数据库中的details表如下所示:

CREATE TABLE `details` (
  `id` int(10) NOT NULL,
  `firstName` varchar(100) NOT NULL,
  `lastName` varchar(100) NOT NULL,
  `dob` date NOT NULL,
  `address` varchar(255) NOT NULL,
  `mobileNumber` varchar(30) NOT NULL,
  `email` varchar(255) NOT NULL,
  `password` varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

ALTER TABLE `details`
  ADD PRIMARY KEY (`id`);

ALTER TABLE `details`
  MODIFY `id` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

然后屏幕输出将显示为:

Success - New ID# is 1

数据库表如下所示:

enter image description here

通过对数组函数进行一些轻量级验证和准备工作,并使用预处理语句来处理安全方面,您可以跳过正确的教育自己开发智能/安全登录系统。