xkevin Am I doing the right way? I used mysqli_close(); to disconnect. But I have an error: "mysqli_close() expects exactly 1 parameter, 0 given..."
What I have tried is to add the connection to my code e.g (mysqli_close(db::config($db))); but I got the same error.
No. One of the points of having a database class is so that all the interaction with the database is through that class. You should have a close() method in the class, assuming you even want to close the connection yourself (php will automatically close any database connection when the script ends.) If you did have a need to reference the connection in your main code, it would be in -
db:$db
xkevin And is there a way I can prevent an SQL injection on my code? Like using mysqli_real_escape_string? How to do it on my code structure?
As mentioned in your last thread on this forum, the surest and simplest way of protecting against sql injection is to use prepared queries and to use the php PDO extension.
You would modify the class's query() method to add an optional 2nd call time array parameter. If this parameter is empty, the code in the method would call the PDO query() method. If this parameter is not empty, the code in the method would call the PDO prepare() method, then call the PDO execute() method, supplying the array as a the call time parameter to the execute() method.
To convert the sql query into a prepared query, you would replace each php variable with a ? place-holder, removing any single-quotes and { } around the variables, then supply the variables that you just removed as the 2nd call time array parameter. The example you posted above would become -
$sql = "INSERT INTO transactions_in(
transact_in_date,
transact_in_note,
transact_in_by_user,
transact_in_date_added
)
VALUES (?,?,?,
NOW()
)";
db::query($sql,[$transact_date, $post['transact_note'], $_SESSION['user_name']]);
Any other methods in your class that execute a query, such as the select() and select_row() should not duplicate the query code, but should instead call the class's query() method.
Edit: Also, your error handling for the connection and query (and now prepare and execute) should not unconditionally output the raw error information onto the web page, as this gives hackers useful information. What you should do is use exceptions for errors (requires a single configuration statement), then let php catch any exception, where it will use its error_reporting, display_errors, and log_errors settings to control what happens with the actual error information. When learning, developing, and debugging code/queries, you would display all errors. When on a live/public server, you would log_all errors.