I'm kind of new to PHP and I'm trying to build a REST API for an app. For some reason I got stuck at something that should be trivial. What I want to do is to be able to insert a new row into the Score-table which is defined like this:
CREATE TABLE Scores(
score_id INT AUTO_INCREMENT,
user_id INT NOT NULL,
item_id INT,
score DOUBLE UNSIGNED,
PRIMARY KEY (score_id),
FOREIGN KEY (item_id) REFERENCES Items(internal_id),
FOREIGN KEY (user_id) REFERENCES Users(user_id) ON DELETE CASCADE
);
Below is the PHP code I use. The function setScore
is a member in a class which also has the db
and response
-members which you will see. But I have debugged the code enough to see that everything apart form the below function works.
The POST-variables have the correct values and the sendResponse(200, "SCORE_INSERTED_SUCCESSFULLY")
is executed properly. And I do not try to insert duplicate rows.
The problem is that I don't get a new row in the Score-table. However, strangely enough I can see that the primary key is auto incremented each time I try to insert a new row even though no new row appears!
I can insert the row manually by running the exact same query in mysql manually. For example, this works if I run it manually in mysql:
INSERT INTO Scores (user_id, item_id, score) VALUES (1,2,6.0);
So why does the below not work?
function setScore() {
if (isset($_POST["user_id"]) && isset($_POST["item_id"]) && isset($_POST["score"]))
{
$user = $_POST["user_id"];
$item = $_POST["item_id"];
$score = $_POST["score"];
$query = 'INSERT INTO Scores (user_id, item_id, score) VALUES (?,?,?)';
$stmt = $this->db->prepare($query) or trigger_error($this->db->error."[$query]");
$stmt->bind_param("iid", $user, $item, $score);
$stmt->execute();
$stmt->close();
$this->response->sendResponse(200, "SCORE_INSERTED_SUCCESSFULLY");
return true;
}
$this->response->sendResponse(400, "Invalid request");
return false;
}
I really appreciate any feedback, this is driving me mad!
Thanks in advance
EDIT:
This is the value of the $stmt-variable before execute:
mysqli_stmt Object
(
[affected_rows] => 0
[insert_id] => 0
[num_rows] => 0
[param_count] => 3
[field_count] => 0
[errno] => 0
[error] =>
[error_list] => Array
(
)
[sqlstate] => 00000
[id] => 1
)
and after execute:
mysqli_stmt Object
(
[affected_rows] => 1
[insert_id] => 30
[num_rows] => 0
[param_count] => 3
[field_count] => 0
[errno] => 0
[error] =>
[error_list] => Array
(
)
[sqlstate] => 00000
[id] => 1
)
But I have debugged the code enough to see that everything apart form the below function works.
I had to eat my own words this time. It turned out I should have posted the whole class because I had forgot that I set $this->db->autocommit(FALSE);
. When I commited everything worked as expected!
Thank you for all your comments
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.