当某些字段留空时,如何使用Prepared Statements更新MySQL数据库?

时间:2018-01-19 17:25:48

标签: php mysql

我使用bind_param更新SQL数据库中的数据。填写完所有字段后,表单会成功提交,但如果任何字段留空,则数据库不会更新。我不知道我的代码有什么问题。

这是我的html表单

<form id="msform" action="includes/cand-reg-dbs.php" method="POST">
<label>Your Full Name</label>
<input type="text" name="full-name"><br />
<label>Your Date of Birth</label>
<input type="date" name="dob"><br />
<label>Father's Name</label>
<input type="text" name="f-name"><br />
<label>Mother's Name</label>
<input type="text" name="m-name"><br />
<label>Address</label>
<input type="text" name="address"><br />
<label>City</label>
<input type="text" name="city"><br />
<label>Pincode</label>
<input type="text" name="pincode"><br />
<input type="submit" name="submit" id="submit-button" class="" value="Save" /></form>

以下是上述形式cand-reg-dbs.php的行动

session_start();

if (isset($_POST['submit'])) {

    $dbServername = "localhost";
    $dbUsername = "root";
    $dbPassword = "";
    $dbName = "jobin";

    $uid = $_SESSION['username'];

    $con = new mysqli($dbServername, $dbUsername, $dbPassword, $dbName);

if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}

$stmt = $con->prepare("UPDATE users SET Full_Name = ?, DOB = ?, f_Name = ?, m_Name= ?, Address = ?, City = ?, Pincode = ? WHERE Username = ?");
$stmt->bind_param("ssssssis", $fullName, $dob, $fName, $mName, $address, $city, $pincode, $uid);

    $fullName = $_POST['full-name'];
    $dob = $_POST['dob'];
    $fName = $_POST['f-name'];
    $mName = $_POST['m-name'];
    $address = $_POST['address'];
    $city = $_POST['city'];
    $pincode = $_POST['pincode'];

    echo "New records created successfully";

    $stmt->execute();
    $stmt->close(); 
    $con->close();
}

在users表中,默认值为 -

Full_Name VARCHAR(40) default value is set to ''
DOB date default value is set to 12-12-2012
f_Name VARCHAR(40) default value is set to ''
m_Name VARCHAR(40) default value is set to ''
Address VARCHAR(120) default value is set to ''
City VARCHAR(25) default value is set to ''
Pincode int(6) default value is set to 0

1 个答案:

答案 0 :(得分:0)

可能正在使用isset将有助于此

 $fullName = isset($_POST['full-name'])?$_POST['full-name']:'';
 $dob = isset($_POST['dob'])?$_POST['dob']:'2018-01-18';

和所有字段相同