Maa
Maa

Reputation: 31

Is it a good practice and safe way to create user defined function with mysqli?

Am trying to change my project from mysql to mysqli. I have my db connection as:

$link = mysqli_connect($hostname, $username, $password, $database);
if(mysqli_connect_errno()) {
    echo "Opps! Connection could not be established: ", mysqli_connect_error();
    exit();
}

Then I have a user defined function as:

function get_name($id) {
    $query = mysqli_query($link, "select name from staff where id='$id'");
    $result = mysqli_fetch_assoc($query);
    return $data = $result['name'];
}

I understand that I have to declare $link as global (as shown below) which work fine.

function get_name($id) {
    global $link;
    $query = mysqli_query($link, "select name from staff where id='$id'");
    $result = mysqli_fetch_assoc($query);
    return $data = $result['name'];
}

My question here is: Is it a good practice and is it safe?

Upvotes: 1

Views: 228

Answers (2)

Your Common Sense
Your Common Sense

Reputation: 157880

Taken literally, this question makes very little sense. User-defined functions almost always are good practice, no matter if you are using them with mysqli or any other API. Yet functions in general have nothing to do with safety.

While speaking of the code provided, it is not safe because of lack of prepared tatements.

So, to make your code proper, you have to create functions to handle mysqli queries with parameters first. And then employ these functions in your own helper functions, to make them look like this:

function get_name($id) {
    return dbgetOne("select name from staff where id=?",[$id]);
}

as you can see it will not only make your queries safe, but also shorten your code.

Upvotes: 1

Travesty3
Travesty3

Reputation: 14479

I wouldn't necessarily call it a good or bad practice to write a function with such a specific purpose, just what fits your needs. If you plan to do this exact task in multiple places throughout your code, a function is useful to make your code easier to read and avoid repeating yourself.

As far as safety goes, you need to sanitize inputs before using them in a query. For the case of an integer $id field, you could simply cast it as an integer $id = (int)$id;. For other data types, you would want to escape it by using $id = mysqli_real_escape_string($link, $id);. Then you'll be safe.

I would also advise that you look into PDO instead of mysqli. I believe it's much more commonly used these days.

Upvotes: 1

Related Questions