I’m learning PHP and wanted to create two simple reusable functions for MySQL database access —
one for selecting data, and one for modifying data.
I’m not sure if this is a good and safe way to handle it.
Can this structure cause any issues (for example: performance, error handling, or security problems)?
Here’s my code:
<?php
function getData($sql) {
$db = new mysqli("localhost", "root", "", "cars");
if ($db->connect_errno != 0) {
return $db->connect_errno;
}
$result = $db->query($sql);
if ($db->errno != 0) {
return $db->error;
}
if ($result->num_rows == 0) {
return [];
}
return $result->fetch_all(MYSQLI_ASSOC);
}
function setData($sql) {
$db = new mysqli("localhost", "root", "", "cars");
if ($db->connect_errno != 0) {
return $db->connect_errno;
}
$db->query($sql);
if ($db->errno != 0) {
return $db->error;
}
return $db->affected_rows > 0 ? true : false;
}
?>
I expected these two functions to simplify my database access:
adatel()
should return all selected rows as an arrayadatVal()
should return true/false depending on whether the query affected rows
It seems to work, but I want to make sure this is a good approach.
Should I use prepared statements instead, or is this fine for small school projects?