PHP mysqli Insert does not work, but gives no errors

As the title says, I'm trying to make a simple insert, but nothing has been added to the table. I am trying to print errors, but nothing is reported.

My users table has many more fields than these 4, but they should all be by default.

$query = 'INSERT INTO users (username, password, level, name) VALUES (?, ?, ?, ?)'; if($stmt = $db -> prepare($query)) { $stmt -> bind_param('ssis', $username, $password, $newlevel, $realname); $stmt -> execute(); $stmt -> close(); echo 'Any Errors: '.$db->error.PHP_EOL; } 

No data, but when I look at the table in phpmyadmin, a new row is not added. I know for sure that the types are correct (strings and integers). Something is really wrong here, or is it because I ignore the other columns. I have about 8 columns in the user table.

+2
source share
5 answers

If you turned off auto-commit, you will have to explicitly call the commit method after the request has completed.

 $stmt->execute(); $db->commit(); $stmt->close(); 
+6
source

You should check for errors at every step of the process: when you connect, when you prepare instructions, when you bind, when you execute, and when you close. In your code, assuming that the $db descriptor was created correctly, an error check occurs after a call to ->close() , which should be successful, so there will be no error at this point.

Something in these lines will show where things exploded:

 $query = 'INSERT INTO users (username, password, level, name) VALUES (?, ?, ?, ?)'; $stmt = $db->prepare($query); echo 'prepare error: ', $db->error, PHP_EOL; $stmt->execute(); echo 'execute error: ', $db->error etc.... 
+2
source

Check if the string "Any Errors" is printed. If not, then the statement:

 if ($stmt = $db->prepare($query)) 

returns false. You must move echo 'Any Errors: '.$db->error.PHP_EOL; outside the conditional block.

+1
source

Initialize the values โ€‹โ€‹of $ username, $ password, $ newlevel, $ realname before $ stmt โ†’ execute (); expression. Otherwise, you should initialize and try

+1
source
 $query = 'INSERT INTO users (username, password, level, name) VALUES (?, ?, ?, ?)'; if($stmt = $db -> prepare($query)){ $stmt -> bind_param('ssis', $username, $password, $newlevel, $realname); $username='testname';$password='testpwd';$level=5;$realname='testrealname'; $stmt -> execute(); echo "inserted SuccessFully"; $stmt -> close(); } else { printf("Prepared Statement Error: %s\n", $mysqli->error);} 

try this code. If the request is successful, it shows "Paste successfully", otherwise it shows an error.

+1
source

All Articles