Tags
Asked 2 years ago
9 Jun 2021
Views 185
steave

steave posted

How to call mysqli query in a function

How to call mysqli query in a function
css-learner

css-learner
answered Apr 26 '23 00:00

You can call a MySQLi query in a function by defining the query inside the function and passing any necessary parameters as function arguments. Here's an example:



function get_user_data($user_id) {
    $mysqli = new mysqli("localhost", "username", "password", "database");

    if ($mysqli->connect_errno) {
        return "Failed to connect to MySQL: " . $mysqli->connect_error;
    }

    $sql = "SELECT * FROM users WHERE id = ?";
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if (!$result) {
        return "Error executing query: " . $mysqli->error;
    }

    $data = array();

    while ($row = $result->fetch_assoc()) {
        $data[] = $row;
    }

    $stmt->close();
    $mysqli->close();

    return $data;
}

// Example usage
$user_data = get_user_data(123);

if (is_array($user_data)) {
    foreach ($user_data as $row) {
        echo $row["username"] . "<br>";
    }
} else {
    echo $user_data;
}

In this example, we define a function called get_user_data () that takes a single parameter $ user_id . Inside the function, we establish a database connection, prepare the query, bind the parameter, execute the query, and process the result set.

We store the results in an array called $ data and then close the statement and the database connection. Finally, we return the $ data array to the calling code.

To use the function, we call it with a user ID as the argument, and then check the return value. If it's an array, we loop through the rows and display the username. If it's not an array, we assume it's an error message and display it.
Post Answer