I have a ‘users’ SQL table structure like this (the ID is randomly generated for certain reasons, it is not auto-incremented):
ID name deleted lastActive
3242 Joe 0 20-6-2012 23:14
2234 Dave 0 20-6-2012 23:13
2342 Simon 1 20-6-2012 23:02
9432 Joe 1 20-6-2012 22:58
In one query (to avoid concurrent queries adding the same name twice), I need to add a new user to the table IF there is not already a record with that name AND deleted = 0. I then need to know the result of the query (if the user was added) so that I can report back saying if the user was added or not. Is this possible using PHP?
I could do this (but as a prepared statement, of course!):
INSERT INTO users (ID, name) VALUES ($id, $name)
WHERE NOT EXISTS (SELECT 1 FROM users WHERE name = $name AND deleted = 0)
But how can I know if the user was added or not?
If you’re using mysqli, you can use the
mysqli_stmt_affected_rows()function to determine how many rows were inserted.Similarly, you can use the
PDOStatement::rowCount()method to determine how many rows were inserted for PDO.Both functions will tell you the number of rows that were inserted as a result of the query.