简体   繁体   中英

mysqli prepare returns false but SQL is valid

I'm using the prepare function from mysqli to create a query to my database but it fails on me even when I have many request working earlier in the same page.

My query looks like this :

if ($insert = $mysqli->prepare( "INSERT INTO table_name (id_user, token) VALUES (?, ?)")) {
    // Do some cool stuff here
} else {
    var_dump($mysqli->error);
    var_dump($insert->error);
}

During the execution, it goes into the else and the output is :

string(0) "" //var_dump($mysqli->error);
Notice: Trying to get property of non-object in // var_dump($insert->error);

I know that my $mysqli is working so I also tested out these strings inside the prepare statement. None of them worked ether. (I tested them in mysql/phpmyadmin and they work fine)

"INSERT INTO `table_name` (`id_user`, `token`) VALUES (?, ?)"
"INSERT INTO `table_name` (`table_name`.`id_user`, `table_name`.`token`) VALUES (?, ?)"
'INSERT INTO `table_name` (`id_user`, `token`) VALUES (50, "random_token")'

Can someone help me with this little headache?

Thanks

The error is actually complaining about $insert not being defined... Which makes sense, as it's hitting your else statement.

Notice: Trying to get property of non-object in // var_dump($insert->error);

Notice the error you yourself commented, and what it's actually complaining about. You shouldn't be referencing the $insert variable in the else statement

I finally figured it out. The problem is that I didn't closed my previous connections. One of them was already using the same name $insert

Two possible fixes I found for someone who could find this thread.

Fix 1 - CLOSE YOUR CONNECTIONS , it's as simple has

$connectionVariable->close();

Fix 2 - Name your variables differently. Although you should always do the Fix 1 first. I guess I had to find it the hard way.

PS Thanks to everyone who helped me

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM