Jump to content
Larry Ullman's Book Forums

Insert Statement Works Directly From Phpmyadmin But Not From Php Script


Recommended Posts

I can't understand why a certain INSERT statement I am trying to perform from a PHP script isn't working.

At first, I thought it might be the syntax, but I wasn't getting any errors in my PHP script, and when I copied and pasted the INSERT statement (without editing it) directly into the SQL window in phpMyAdmin, it worked perfectly fine.

 

Next, I thought that there might be a problem with the DB connection being established in my PHP script, but again, I'm not getting any errors, and any SELECT or UPDATE statements I run from the PHP script work perfectly fine.

 

However, whenever I run an INSERT statement from the PHP script, nothing is inserted into the DB, and I get a value of -1 returned by echo mysqli_affected_rows($dbc);.

Has anyone ever encountered this problem, and more importantly, found a solution? I'm so stumped, especially since I'm not getting any errors.

 

Finally, to try and localize the problem, I wrote the following simple PHP script that simply attempts a DB insert, but still, I get -1 returned by the echo mysqli_affected_rows($dbc); statement at the end (even though any SELECT or UPDATE statements executed from the script work fine):

 

<?php

 $dbc = mysqli_connect(/*Credentials here. These are definitely fine.*/);

 $q = "INSERT INTO chatDB_messages (poster, content) VALUES ('Me', 'Hello.')";

 $r = mysqli_query($dbc, $q);

 echo mysqli_affected_rows($dbc); // Returns -1 every time.

?>

Link to comment
Share on other sites

Could you try adding

$r = @mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc)); // Dont know if @ is needed befor the query

to your query?

 

I too have been stumped many times trying to figure out MYSQL Problems...

  • Upvote 2
Link to comment
Share on other sites

Yeah! I totally figured it out (and I feel like such an idiot).

 

Jaepee, your advice was great by the way, and I will definitely use it in the future, but in this case, I ended up figuring out the problem by just sitting here at work, thinking about it.

 

I forgot that way back when, I set the DB user up to only have the SELECT and UPDATE privileges. As soon as I enable the INSERT privilege as well, it should be fine, especially since the site was working fine on XAMPP with the same exact code.

 

Man! I feel like such an idiot! It's so easy to forget about those types of things; I created the DB user ages ago.

 

Edit: I just added the INSERT privilege, and that was indeed the problem. It works like a charm now.

  • Upvote 2
Link to comment
Share on other sites

 Share

×
×
  • Create New...