如何创建“找不到记录”错误消息

时间:2018-10-13 07:34:48

标签: php

我正尝试在下面的示例中添加一些代码,这将允许生成“找不到记录”错误-如果未找到记录:

    <?php   
    header('Content-type=application/json; charset=utf-8');
    //database constants
    define('DB_HOST', 'localhost');
    define('DB_USER', 'root');
    define('DB_PASS', '');
    define('DB_NAME', 'test');

    //connecting to database and getting the connection object
    $conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

    //Checking if any error occured while connecting
    if (mysqli_connect_errno()) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
        die();
    }   



    $stmt = $conn->prepare('SELECT * FROM donor WHERE city =? AND gender=? AND 
    bloodgroup=? AND age=?;');
    $stmt->bind_param('ssss',$_GET['city'],$_GET['gender'],$_GET['bloodgroup'],$_GET['age']);
    $stmt->execute();


    //binding results to the query 
    $stmt->bind_result($id, $name, $gender, $city, $contact, $bloodgroup,$age);

    $donors = array(); 

    //traversing through all the result 
    while($stmt->fetch()){
        $temp = array();
        $temp['id'] = $id; 
        $temp['name'] = $name; 
        $temp['gender'] = $gender; 
        $temp['city'] = $city; 
        $temp['contact'] = $contact; 
        $temp['bloodgroup'] = $bloodgroup; 
        $temp['age'] = $age; 
        array_push($donors, $temp);
    }


    //displaying the result in json format 
    echo json_encode($donors);
?>

您建议我在哪里放置代码以启用“找不到错误”错误?

1 个答案:

答案 0 :(得分:0)

您可以使用$ stmt-> num_rows,也可以使用以下代码进行检查

    if (empty($donors)) {
       echo json_encode(array('msg' => 'Record Not Found'));
    }else{
      echo json_encode($donors);
    }