Also don't do this:
SELECT id,domain,word,phrase from $tbl WHERE $col_1 = ?
Because now it's easy for a hacker to do something like:
?col_1=1;DELETE FROM users WHERE id&input_1=1
Instead do something like:
/**
* @param array{col_1: string} $fields
* @param string $operator Possible values AND, OR
* @param int $limit Possible value between 0 and 100, if invalid defaults to 100
* @param int $offset
*
* @return array{items: array, total_items: int}
*/
function page_search(array $fields, string $operator, int $limit, int $offset = 0): array {
$where = $values = [];
$operator = in_array($operator, ['OR', 'AND']) ? $operator : 'AND';
$limit = 0 < $limit && $limit < 100 ? $limit : 100;
$offset = 0 <= $offset ? $offset : 0;
foreach ($fields as $field => $term) {
switch ($field) {
case 'col_1':
$where[] = 'col_1 = ?';
$values[] = $term;
break;
// other fields you want to allow to search on
}
$result = [
'items' => [],
'total_items' => 0,
];
if ([] === $where) {
return $result;
}
$result['items'] = db_fetch_all('SELECT * FROM some_table WHERE ' . implode($operator, $where) . " LIMIT $offset, $limit", $values);
if (count($result['items'])) {
// only execute a count() query if we have a result
$result['total_items'] = db_fetch_column('SELECT count(*) FROM some_table WHERE ' . implode($operator, $where), $values);
}
return $result;
}
By dividing your program into little pieces you reduce the cognitive load necessary to work on pieces of your application or to find and fix bugs.
The same goes for the database. I see you use mysqli_connect in the script with the values hardcoded. Instead you should create a file that holds your configuration values:
// bootstrap.php
define('DB_HOST', 'localhost');
define('DB_USER', 'the_username');
define('DB_PASS', 'the_password');
define('DB_NAME', 'the_database');
define('DB_PORT', 3306);
define('DB_CHARSET', 'utf8mb4');
define('EMERGENCY_EMAIL', 'some@email.com'); // in case of fatal errors
// other configuration values
Then in your database functions file:
function db_connect() {
static $connection;
if (null === $connection) {
$connection = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_PORT);
if ($connection) {
mysqli_set_charset($connection, DB_CHARSET);
}
}
return $connection;
}
All of this creates building blocks you can use to build upon further. The next step would be to create a db_fetch_all function that uses db_connect to get the active DB connection etc...