在不使用fetch的情况下检查空字段

时间:2014-10-16 07:56:59

标签: php mysql

在使用PHP而不使用mysql_fetch_array()的SQL中检查字段是否为空时,我遇到了一些问题。

我有这个代码:

date_default_timezone_set('Asia/Taipei');
$remarks = $_POST['remarks'];
$date_added = date ("Y-m-d");
$time_added = date ("h:i:s a");
$lname = $_SESSION['user']['last_name'];
$fname = $_SESSION['user']['first_name'];
$minitial = $_SESSION['user']['middle_initial'];
$con = mysqli_connect("localhost", "root", "", "thisdb");


if(empty(`TIME_IN_1`)) {
$query = "INSERT INTO time_logs (LAST_NAME, FIRST_NAME, MIDDLE_INITIAL, DATE, TIME_IN_1, TIME_IN_1_REMARKS) VALUES('$lname', '      $fname', '$minitial', '$date_added', '$time_added', '$remarks')";
}

else {
$query =  "UPDATE time_logs SET TIME_IN_2 = '$time_added' where LAST_NAME = '$lname' AND DATE = '$date_added'";
}

$save = mysqli_query($con, $query);
header("Location: time_in_complete.php");

我基本上想要完成的是,如果TIME_IN_1字段为空,则会在那里添加数据。如果它不为空,则数据将被添加到TIME_IN_2。

显然,这一行:

if(empty(`TIME_IN_1`))

似乎不起作用。

2 个答案:

答案 0 :(得分:2)

$first_query = "SELECT TIME_IN_1 FROM time_logs WHERE LAST_NAME = '" . $lname . "' AND FIRST_NAME = '" . $fname . "'";
$data = mysqli_query($con, $first_query);
$num_row = mysqli_num_rows($data);

if($num_row == 0) {
$query = "INSERT INTO time_logs (LAST_NAME, FIRST_NAME, MIDDLE_INITIAL, DATE, TIME_IN_1, TIME_IN_1_REMARKS) VALUES('$lname', '      $fname', '$minitial', '$date_added', '$time_added', '$remarks')";
}

else {
$query =  "UPDATE time_logs SET TIME_IN_2 = '$time_added' where LAST_NAME = '$lname' AND DATE = '$date_added'";
}

$save = mysqli_query($con, $query);
header("Location: time_in_complete.php");

答案 1 :(得分:0)

尝试查询:

SELECT TIME_IN_1 from time_logs where LAST_NAME = '$lname' AND DATE = '$date_added'

然后:

// Default to true and set this false if we find a value
$bIsEmpty = true;

// Check if any rows match
if ($result->num_rows > 0){

  // Yes a row matches, so check if we have a value
  $row = $result->fetch_object();
  if ($row->TIME_IN_1 != "")
       $bIsEmpty = false;
}

if ($bIsEmpty === true){
    // Do your insert
} else {
    // Do your update
}