After creating a handful of functions for my new website, I quickly realized things were getting out of hand with all the include files using perpetual programming, so I decided to learn and convert my currently written functions into OOP classes and convert from mysql to mysqli. Hasn’t been too bad of a transition so far but I’ve reached a function that has/needs multiple queries, one a SELECT to check the data before I UPDATE it. What I’ve written so far, using a prepared statement, works like a charm but it only does the SELECT. Where I’m stuck is where it comes time to UPDATE the db. Here’s what I have so far:
public function ban() {
$connection = Database::getConnection();
$user_id = $_POST['user'];
$feedback = '';
$query = "SELECT banned, user_name
FROM users
WHERE user_id = ?";
$stmt = $connection -> prepare($query);
// Check for a multi-user selection on POST
if (count($user_id) > 1) {
foreach ($user_id as $value) {
$stmt -> bind_param('i', $value);
if (!$result = $stmt -> execute()) {
$feedback .= "Did not execute.";
} else {
$stmt -> bind_result($banned, $user);
$stmt -> fetch();
if ($banned == 1) {
$feedback .= $user . " is already banned.<br />";
} else {
// This is where I need the code to update the database
// with the users who aren't already banned.
}
}
}
$stmt -> close();
return $feedback;
} else {
// This is where the UPDATE will be for a single person ban
// if only one was selected on POST
}
}
Can I create/execute a second prepared statement for the UPDATE injection, running that inside another loop in the section I need the code or would it be best to avoid that, or would that even work? I’m sure a mysqli_multi_query is probably the best way to go, having to rewrite the function again, since I found out (after writing this much of the function) that you can’t use a prepared statement with a multi_query injection. Rewriting isn’t a big deal but the help for using multi_query is far and few between. PHP website has a lot of documentation but lets be honest, it’s pretty darn confusing.
The UPDATE query would look something like this:
$explain = mysql_real_escape_string($_POST['banExplain']);
UPDATE users
SET banned = '1', ban_reason = '$explain'
WHERE user_id = '$value'"
ANY help with this would be greatly appreciated. Hope I explained well enough with what I need to do. If not, let me know. THANKS!
The code sample is still very procedural.
You should have a method to check if a user is user_banned and a method to ban_user a user.
The user_banned method should take a user_id and return a boolean.
The ban_user method should take a reason and user_id.
There should be another function or method which does the loop.
Cast the user_id as an array and you can do one loop.
Use exceptions to handle errors.