简体   繁体   中英

executing a SELECT query and check if any row is returned and if empty resultset do an INSERT

been following this php/mysql tutorial i found online and now i can't get this query to work. The issue i believe is with using the insert query after null resultset is returned from the select query.

$new_start_no = isset($_POST['start_no']) ? $_POST['start_no'] : '';
$new_end_no = isset($_POST['end_no']) ? $_POST['end_no'] : '';
$new_job_no = isset($_POST['job_no']) ? $_POST['job_no'] : '';

$query = "SELECT COUNT (*)"; 
$query .= "FROM jobs";
$query .= "WHERE job_no=$new_job_no"; 
$query .= "AND start_no <= $new_end_no";
$query .= "AND end_no >= $new_start_no";
$result = mysqli_query($connection, $query);
$num_rows = mysqli_num_rows($result);
if (is_null) { 
$query = "INSERT INTO jobs (";
 $query .= " user_id, start_no, end_no, start_date, client_name, card_type, job_no, job_quantity, end_date, shred_option";
 $query .= ") VALUES (";
 $query .= " '{$user_id}', '{$start_no}', '{$end_no}', '{$start_date}', '{$client_name}', '{$card_type}', '{$job_no}', '{$job_quantity}', '{$end_date}', '{$shred_option}'";
 $query .= ")";
 $result = mysqli_query($connection, $query);
 if ($result) {
// success
   $_SESSION["message"] = "job created.";
   redirect_to("manage_job.php"); 
  } else {
// failure  
   $_SESSION["message"] = "job creation failed.";
   redirect_to("new_job.php");
  }  
}  

Your query always returns exactly 1 row, since it uses COUNT(*) to count the matching rows. You need to retrieve the row and get the count from it. You should assign an alias to the count so you can retrieve it. Then you need to test the count, not is_null .

$query = "SELECT COUNT (*) AS ct"; 
$query .= "FROM jobs";
$query .= "WHERE job_no=$new_job_no"; 
$query .= "AND start_no <= $new_end_no";
$query .= "AND end_no >= $new_start_no";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_assoc($result);
$num_rows = $row['ct'];
if ($num_rows == 0) {
    // INSERT code
} else {
    $_session["message"] = "job no is not available";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM