简体   繁体   中英

Fatal error: Uncaught TypeError: Return value of safeQuery() must be of the type array or null, bool returned

I've been facing a problem. I'm getting this error

Fatal error: Uncaught TypeError: Return value of safeQuery() must be of the type array or null, bool returned in E:\Hosted\action\conn\dbc.php:69 Stack trace: #0 E:\Hosted\action\conn\dbc.php(6): safeQuery('INSERT INTO cu...', Array) #1 {main} thrown in E:\Hosted\action\conn\dbc.php on line 69

I'm not sure where is my bug. The code was working. But suddenly it stops. I may have made a mistake. My queries are right. I've double-checked on that. Here is my code:

<?php
// Test:
    $sql = "INSERT INTO `customers`(`name`, `email`, `phn_num`) VALUES (?, ?, ?)";
    $params = array("Assad Rajab", "email@gmail.com", "0123456789");
    $cus_id = safeQuery($sql, $params);
    

function safeQuery(string $sql, array $params = [], $db = NULL ): ?array {
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

    $conn = mysqli_connect("localhost", "phpmyadminuser", "Technik-Phone-Admin");
    if (!$conn) {
        die("no connection to database");
    } else {
        if (!mysqli_set_charset($conn, "utf8")) {
            die("Error loading character set utf8: </br>". mysqli_error($conn));
        } else {
            if (isset($db)) {
                // Use the given DB 
                mysqli_select_db($conn, $db);
            } else {
                // Use the default DB
                mysqli_select_db($conn, "technik-phone_mng");
            }
        }
    }

    // Prepare statement:
    $stmt = mysqli_prepare($conn, $sql);
    // If the statement has parameters then bind them all now
    if ($params) {
        mysqli_stmt_bind_param($stmt, str_repeat("s", count($params)), ...$params);
    }
    // Execute it and get results if there are any
    mysqli_stmt_execute($stmt);

    if ($result = mysqli_stmt_get_result($stmt)) {
        $row = mysqli_fetch_array($result, MYSQLI_BOTH);
        
        // echo $result->num_rows;
        // print_r($data);
        // echo $data[0]['name'];
        return $row;
    }
    // If the query was INSERT or UPDATE then return TRUE
    echo "Done";
    return TRUE;
}

?>

I want to be able to return the id of the new inserted column. The insert_id didn't work. It there anyway to get that returned without using another query?

Update

what im trying to do is safe on my self the writing of the

$sql = "sql stmt";
$result = mysqli_query($conn, $sql);
if(!$result){
  // do something
} else{
  // do something else
}

im tying to put the above block in a secure function and avoid using the mysqli_real_escape()

End goal my end goal is to get the returned array if my sql stmt was select. if the stmt was insert i want to get the id of the new inserted row. this information should be returned.

Update

the mistake is that the return have to be NULL. not True. the last problem is that im trying to get the id of the new iserted row. but i dont know how to do that without to exec another query to do that. any idea?

To get the ID you can just use $db1->insert_id; on the correct mysqli object.

Notes:

  1. Don't open the connection inside of the function. You need to open the connection only once . Then whenever you call this function you pass the right connection as an argument.

  2. This function should only return value or nothing at all. It should never return true or false.

  3. I don't recommend using more than one database in one script, but if you must you should have separate mysqli object for each.

<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
// db 1
$db1 = new mysqli('localhost', 'user', 'pass', 'db1');
$db1->set_charset('utf8mb4'); // always set the charset
// db 2
$db2 = new mysqli('localhost', 'user', 'pass', 'db2');
$db2->set_charset('utf8mb4'); // always set the charset

// Test:
$sql = "INSERT INTO `customers`(`name`, `email`, `phn_num`) VALUES (?, ?, ?)";
$params = array("Assad Rajab", "email@gmail.com", "0123456789");
$cus_id = fetchSingleRow($db1, $sql, $params);

// get the auto generated ID:
$id =  $db1->insert_id;
    
/**
 * Fetches a single row from the database
 *
 * @param \mysqli $conn This is the valid mysqli object with open connection to a DB
 * @param string $sql   Your SQL query with placeholders
 * @param array $params An array of parameters to be bound. [optional]
 * @return array|null   This function will return an array representing a single row from the result or nothing at all.
 */
function fetchSingleRow(\mysqli $conn, string $sql, array $params = []): ?array {
    // Prepare statement:
    $stmt = mysqli_prepare($conn, $sql);
    // If the statement has parameters then bind them all now
    if ($params) {
        mysqli_stmt_bind_param($stmt, str_repeat("s", count($params)), ...$params);
    }
    // Execute it and get results if there are any
    mysqli_stmt_execute($stmt);

    if ($result = mysqli_stmt_get_result($stmt)) {
        $row = mysqli_fetch_array($result, MYSQLI_BOTH);
        return $row;
    }

    // nothing to return
    return null;
}

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