Reputation: 21
As the title says Im trying to do a simple insert, but nothing actually is inserted into the table. I try to print out errors, but nothing is reported.
My users table has many more fields than these 4, but they should all 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;
}
There are no errors given, but when I go to look at the table in phpmyadmin there is not a new row added. I know for sure that the types are correct (strings and integers). Is there something really wrong here or does it have something to do with the fact that I'm ignoring other columns. I have about 8 columns in the user table.
Upvotes: 2
Views: 5777
Reputation: 1109
If you have turned auto commit off, you will have to explicitly call the commit method after you execute the query.
$stmt->execute();
$db->commit();
$stmt->close();
Upvotes: 6
Reputation: 131
$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 query is executed successfully it show the "Inserted Successfully" otherwise it shows the error.
Upvotes: 1
Reputation: 360572
You have to check for errors at each stage of the process: When you connect, when you prepare the statement, when you bind, when you execute, and when you close. In your code, assuming the $db
handle was properly created, the error check happens after the ->close()
call, which should succeed, so there won't be any error at that point.
Something along these lines will show where things blew up:
$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....
Upvotes: 2
Reputation: 131
Do u initialize the values of $username, $password, $newlevel, $realname before the $stmt -> execute(); statement. Otherwise you have to initialize and try
Upvotes: 1
Reputation: 48897
Check if the string "Any Errors" is being printed. If not, then the statement:
if ($stmt = $db->prepare($query))
is returning false. You should move echo 'Any Errors: '.$db->error.PHP_EOL;
outside of the conditional block.
Upvotes: 1