Help - Search - Members - Calendar
Full Version: Help with MySQLi needed
HTMLHelp Forums > Programming > Databases
I am trying to learn Mysqli and have got as far as the following, but even though I've ironed out the connection issues it is not actually inserting the data into the relevent table.

Any help most appreciated.

In checklogin file:

// Insert the values into the database
$result = db_query("INSERT INTO `logs` (`email`,`logged`,`ip`) VALUES ('" . $user . "','" . $logged . "','" . $IP . "')");
if($result == false) {
echo "fault here";
// Handle failure - log the error, notify administrator, etc.
} else {
// We successfully inserted a row into the database
echo "log added";

In dbfuncs file:

function db_connect() {

// Try and connect to the database, if a connection has not been established yet
$config = parse_ini_file('../config.ini');
$con = new mysqli('localhost',$config['username'],$config['password'],$config['database']);

// If connection was not successful, handle the error
if($con == false) {
// Handle error - notify administrator, log to a file, show an error screen, etc.
return mysqli_connect_error();

function db_query($query) {
echo $query; //temp check for info sent
// Connect to the database
$con = db_connect();
// Query the database
return $con ? mysqli_query($con, $query) : mysqli_connect_error();

Output on screen:

INSERT INTO `logs` (`email`,`logged`,`ip`) VALUES ('xxx','2018-2-9 10:27:1','xxx')log added

However, no entry added to the actual dabatase.
In the 'db_query' function this line '$con = db_connect();' is never what you think it should be. Look at the 'db_connect' function and you see that it never returns a mysqli object. It only returns a mysqli error, it should return $con if no error.

Also, you need to study how PHP scope works. $con defined in a function will not be global. It will not be available in other functions unless you pass $con as a parameter in the function call.

If you are just learning I suggest you forget this approach. Instead study about mysqli parameterized queries and data binding (or PDO) to help fight SQL injection attacks.
The argument for PDO vs mysqli used to be debatable, but I think nowadays you should use PDO. It's really not much of a contest.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2022 Invision Power Services, Inc.