Login
Username: Password:
Remember me

[Sign Up] / [Recover Password]

Theme / Language

Popular
New Torrents
new name
Size: 18.40 MB
Most active
new name
S: 74 L: 3
New Posters
SQL_Query_exec replacement?
Controls ·  Search New posts · Mark unread

You are in: Forum / Forum / General / Tutorials

2026-06-17 23:26:07
I have had this for some time and been using it where needed and it seems to work. Not all calls can automatically switched to this, but I been having good luck on some inserts, posts, etc. Trying to make it easier to move to prepared statements without rewriting every line of code. I will just share it and you can decide to test also. This goes in backend/mysql.class.php
function SQL_Query_prepared(string $query, string $types = '', array $params = [])
{
   $db = $GLOBALS['DBconnector'] ?? null;

   if (!$db instanceof mysqli) {
       error_log("SQL_Query_prepared Error: Database connection is not available.");
       return false;
   }

   $stmt = null;

   try {

       $stmt = mysqli_prepare($db, $query);

       if (!$stmt) {
           throw new Exception("Prepare failed: " . mysqli_error($db));
       }

       if ($types !== '') {

           if (strlen($types) !== count($params)) {
               throw new Exception("Parameter count does not match type definition.");
           }

           $bindParams = [$types];

           foreach ($params as $key => $value) {
               $bindParams[] = &$params[$key];
           }

           if (!call_user_func_array([$stmt, 'bind_param'], $bindParams)) {
               throw new Exception("bind_param failed: " . mysqli_stmt_error($stmt));
           }
       }

       if (!mysqli_stmt_execute($stmt)) {
           throw new Exception("Execute failed: " . mysqli_stmt_error($stmt));
       }

       $result = mysqli_stmt_get_result($stmt);

       if ($result instanceof mysqli_result) {
           return $result;
       }

       return mysqli_stmt_affected_rows($stmt) >= 0;

   } catch (Throwable $e) {

       error_log(
           "SQL_Query_prepared Error: " .
           $e->getMessage() .
           " | Query: " . $query
       );

       return false;

   } finally {

       if ($stmt instanceof mysqli_stmt) {
           mysqli_stmt_close($stmt);
       }
   }
}

TTv3 Micro Edition
Ubuntu 20.04.6 LTS Server
Mysql Version: 10.3.39-MariaDB-0ubuntu0.20.04.2
PHP Version: 7.4.3-4ubuntu2.20
Apache Version: Apache/2.4.59 (Ubuntu)
Last edited by MicroMonkey on 2026-06-17 23:28:35
2026-06-18 14:58:14
Thanks for sharing this, MicroMonkey.

I think the safest approach is to keep the existing SQL_Query() / SQL_Query_exec() system in place for backward compatibility, and add SQL_Query_prepared() as an extra function.

That way, nothing currently used by TorrentTrader breaks, but newer or sensitive code can slowly be moved to prepared statements.

Here is the version I would add without replacing the existing calls:


function SQL_Query_prepared(string $query, string $types = '', array $params = []) {
   $db = $GLOBALS['DBconnector'] ?? null;

   if (!$db instanceof mysqli) {
       error_log("SQL_Query_prepared Error: Database connection is not available.");
       return false;
   }

   $stmt = mysqli_prepare($db, $query);

   if (!$stmt) {
       error_log("SQL_Query_prepared Prepare failed: " . mysqli_error($db));
       return false;
   }

   if ($types !== '') {
       if (strlen($types) !== count($params)) {
           error_log("SQL_Query_prepared Error: Parameter count does not match type definition.");
           mysqli_stmt_close($stmt);
           return false;
       }

       $bindParams = [$types];

       foreach ($params as $key => $value) {
           $bindParams[] = &$params[$key];
       }

       if (!call_user_func_array([$stmt, 'bind_param'], $bindParams)) {
           error_log("SQL_Query_prepared bind_param failed: " . mysqli_stmt_error($stmt));
           mysqli_stmt_close($stmt);
           return false;
       }
   }

   if (!mysqli_stmt_execute($stmt)) {
       error_log("SQL_Query_prepared Execute failed: " . mysqli_stmt_error($stmt));
       mysqli_stmt_close($stmt);
       return false;
   }

   $result = mysqli_stmt_get_result($stmt);

   if ($result instanceof mysqli_result) {
       return $result;
   }

   $affected = mysqli_stmt_affected_rows($stmt);
   mysqli_stmt_close($stmt);

   return $affected;
}


Example:
======

SQL_Query_prepared(
   "INSERT INTO shoutbox (userid, text) VALUES (?, ?)",
   "is",
   [$userid, $message]
);


So yes, I think this is a good addition, but I would not replace every SQL_Query_exec() call at once. I would migrate slowly: login, registration, password changes, private messages, shoutbox, comments, uploads, and other user input areas first



2026-06-18 16:36:17
Yes, that is what I am doing. I just added it as a new function. internal calls dont need to be prepared, but user input does, so I have been testing. so far so good. thanks spirit. Here is what I am testing in my account-signup file. Intelliphense formats code weirdly to me lol, but ok. I rewrote my login and recover pages the long way and redid the code for prepared, but I wanted to see if this would be easier.
<?php
require_once "backend/functions.php";
dbconn();
if (session_status() !== PHP_SESSION_ACTIVE) {
   session_start();
}
$site_config["LEFTNAV"] = $site_config["MIDDLENAV"] = $site_config["RIGHTNAV"] = false;
$username_length = 40;
$password_minlength = 6;
$password_maxlength = 40;
$invite_row = null;

// Disable checks if signing up with an invite
$invite_id = $_GET['invite'] ?? 0;
$secret    = $_GET['secret'] ?? '';

if (!is_valid_id($invite_id) || strlen($secret) !== 32) {
   if ($site_config["INVITEONLY"]) {

       echo '<!DOCTYPE html>
<html>
<head>
   <title>Access Denied</title>
   <script>
       alert("This site is invite only.\\n\\nThe invite link you used is invalid or missing.");
       window.location.href = "index.php";
   </script>
</head>
<body>
   <noscript>
       <h2>This site is invite only</h2>
       <p>The invite link you used is invalid. <a href="index.php">Click here to return to the homepage</a>.</p>
   </noscript>
</body>
</html>';
       die();
   }

   // If not invite only, continue with normal signup but check if site is full
   $numsitemembers = get_row_count("users");
   if ($numsitemembers >= $site_config["maxusers"])
       show_error_msg(T_("SORRY") . "...", T_("SITE_FULL_LIMIT_MSG") . number_format($site_config["maxusers"]) . " " . T_("SITE_FULL_LIMIT_REACHED_MSG") . " " . number_format($numsitemembers) . " members", 1);
} else {
   $stmt = SQL_Query_prepared(
       "SELECT id
    FROM users
    WHERE id = ?
    AND MD5(secret) = ?",
       "is",
       [
           (int)$_REQUEST["invite"],
           $_REQUEST["secret"]
       ]
   );
   $invite_row = mysqli_fetch_assoc($stmt);

   if (!$invite_row) {
       show_error_msg(T_("ERROR"), T_("INVITE_ONLY_NOT_FOUND") . " " . ($site_config['signup_timeout'] / 86400) . " days.", 1);
   }
}

if ($_GET["takesignup"] == "1") {

   // RECAPTCHA v3 verification
   $recaptcha_token = $_POST['recaptcha_response'] ?? '';

   $verify_url = "https://www.google.com/recaptcha/api/siteverify";
   $secret = $site_config["RECAPTCHA_SECRET_KEY"];

   $recaptcha_response = file_get_contents($verify_url . "?secret=" . $secret . "&response=" . $recaptcha_token);
   $recaptcha_data = json_decode($recaptcha_response, true);

   $score = $recaptcha_data["score"] ?? 0;
   $action = $recaptcha_data["action"] ?? 'unknown';
   $ip = $_SERVER['REMOTE_ADDR'];
   $user_agent = $_SERVER['HTTP_USER_AGENT'];
   $user_id = null; // Will be null before account creation
   $email = $_POST['email'] ?? null;
   $username = $_POST['wantusername'] ?? null;

   // Insert log into database
   SQL_Query_prepared(
       "INSERT INTO recaptcha_logs
   (
       user_id,email,username,
       score,action,ip,
       user_agent,created_at
   )
   VALUES
   (
       ?,?,?,?,?,?,?,?
   )",
       "issdssss",
       [
           null,
           $email,
           $username,
           $score,
           $action,
           $ip,
           $user_agent,
           get_date_time()
       ]
   );

   // Block signup if score is too low
   if (!$recaptcha_data["success"] || $score < 0.5) {
       show_error_msg("Signup Failed", "reCAPTCHA verification failed. Your activity seems suspicious.", 1);
       die();
   }


   function validusername(string $username): bool
   {
       $length = strlen($username);
       return $length >= 3 && $length <= 40 && ctype_alnum($username);
   }

   $wantusername = $_POST["wantusername"];
   $email = $_POST["email"];
   $wantpassword = $_POST["wantpassword"];
   $passagain = $_POST["passagain"];
   $country = $_POST["country"];
   $gender = $_POST["gender"];
   $client = $_POST["client"];
   $age = (int) $_POST["age"];

   $message = '';
   if (empty($wantpassword) || (empty($email) && !$invite_row) || empty($wantusername))
       $message = T_("DONT_LEAVE_ANY_FIELD_BLANK");
   elseif (strlen($wantusername) > $username_length)
       $message = sprintf(T_("USERNAME_TOO_LONG"), $username_length);
   elseif ($wantpassword != $passagain)
       $message = T_("PASSWORDS_NOT_MATCH");
   elseif (strlen($wantpassword) < $password_minlength)
       $message = sprintf(T_("PASS_TOO_SHORT"), $password_minlength);
   elseif (strlen($wantpassword) > $password_maxlength)
       $message = sprintf(T_("PASS_TOO_LONG"), $password_maxlength);
   elseif ($wantpassword == $wantusername)
       $message = T_("PASS_CANT_MATCH_USERNAME");
   elseif (!validusername($wantusername))
       $message = "Invalid username.";
   elseif (!$invite_row && !validemail($email))
       $message = "That doesn't look like a valid email address.";

   if ($message == "") {
       if (!$invite_row) {
           $maildomain = (substr($email, strpos($email, "@") + 1));

           $stmt = SQL_Query_prepared(
               "SELECT COUNT(*)
    FROM email_bans
    WHERE mail_domain = ?",
               "s",
               [$email]
           );
           $a = mysqli_fetch_row($stmt);

           if ((int)$a[0] !== 0) {
               $message = sprintf(T_("EMAIL_ADDRESS_BANNED_S"), $email);
           }

           $stmt = SQL_Query_prepared(
               "SELECT COUNT(*)
    FROM email_bans
    WHERE mail_domain LIKE ?",
               "s",
               ["%{$maildomain}%"]
           );
           $a = mysqli_fetch_row($stmt);

           if ((int)$a[0] !== 0) {
               $message = sprintf(T_("EMAIL_ADDRESS_BANNED_S"), $email);
           }

           $stmt = SQL_Query_prepared(
               "SELECT COUNT(*)
    FROM users
    WHERE email = ?",
               "s",
               [$email]
           );
           $a = mysqli_fetch_row($stmt);

           if ((int)$a[0] !== 0) {
               $message = sprintf(T_("EMAIL_ADDRESS_INUSE_S"), $email);
           }

           $stmt = SQL_Query_prepared(
               "SELECT COUNT(*) AS total
    FROM users
    WHERE username = ?",
               "s",
               [$wantusername]
           );

           $row = mysqli_fetch_assoc($stmt);

           if ($row['total'] > 0) {
               $message = sprintf(T_("USERNAME_INUSE_S"), $wantusername);
           }
       }

       if ($site_config["ipcheck"] && $site_config["accountmax"] >= "1") {
           $ip = $_SERVER['REMOTE_ADDR'];
           $stmt = SQL_Query_prepared(
               "SELECT COUNT(*)
    FROM users
    WHERE ip = ?",
               "s",
               [$ip]
           );

           $row = mysqli_fetch_row($stmt);
           $ipq = (int)$row[0];
           if ($ipq >= $site_config["accountmax"])
               $message = $site_config["SITENAME"] . " only allows " . $site_config["accountmax"] . " user account per IP address. <br> If you want to create a new account, please contact an administrator.<br /><br /><font color=red> The limit for ip : $ip has been reached.</font><br /><br />Registration failed. <br /><a style='cursor: pointer;cursor:hand;' href='account-login.php'><font color=red>Click here to return to the login page.</font></a>";
       }

       $secret = mksecret();
       $wantpassword = passhash($wantpassword);

       if ($message != "")
           show_error_msg(T_("SIGNUP_FAILED"), $message, 1);

       if ($message == "") {

           if ($invite_row) {
               SQL_Query_prepared(
                   "UPDATE users
    SET username = ?,
        password = ?,
        secret = ?,
        status = 'confirmed',
        added = ?
    WHERE id = ?",
                   "ssssi",
                   [
                       $wantusername,
                       $wantpassword,
                       $secret,
                       get_date_time(),
                       (int)$invite_row['id']
                   ]
               );
               if ($site_config["WELCOMEPMON"]) {
                   $dt = sqlesc(get_date_time());
                   $msg = sqlesc($site_config["WELCOMEPMMSG"]);
                   SQL_Query_exec("INSERT INTO messages (sender, receiver, added, msg, poster) VALUES(0, $invite_row[id], $dt, $msg, 0)");
               }
               header("Refresh: 0; url=account-confirm-ok.php?type=confirm");
               die;
           }

           if ($site_config["CONFIRMEMAIL"]) {
               $status = "pending";
           } else {
               $status = "confirmed";
           }

           if ($numsitemembers == '0') {
               $signupclass = 8;
           } else {
               $signupclass = 1;
           }

           $seedbonus = 0.0;
           $selectedCountryName = $_POST["country"] ?? '';
           if (!empty($selectedCountryName)) {
               $stmt = SQL_Query_prepared(
                   "SELECT id
    FROM countries
    WHERE name = ?
    LIMIT 1",
                   "s",
                   [$selectedCountryName]
               );

               $countryData = mysqli_fetch_assoc($stmt);
               $countryValue = $countryData ? (int)$countryData['id'] : 0;
           } else {
               $countryValue = 0;
           }

           SQL_Query_prepared(
               "INSERT INTO users
   (
       username,
       password,
       seedbonus,
       secret,
       email,
       status,
       added,
       last_access,
       age,
       country,
       gender,
       client,
       stylesheet,
       uploaded,
       downloaded,
       language,
       invites,
       class,
       ip
   )
   VALUES
   (
       ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
   )",
               "ssdsssssiisssdisiss",
               [
                   $wantusername,
                   $wantpassword,
                   $seedbonus,
                   $secret,
                   $email,
                   $status,
                   get_date_time(),
                   get_date_time(),
                   $age,
                   $countryValue,
                   $gender,
                   $client,
                   $site_config["default_theme"],
                   $site_config["new_member_upload_ratio"],
                   0,
                   $site_config["default_language"],
                   $site_config["new_member_invites"],
                   $signupclass,
                   getip()
               ]
           );

           $id = mysqli_insert_id($GLOBALS["DBconnector"]);
           $psecret = md5($secret);
           $thishost = $_SERVER["HTTP_HOST"];
           $thisdomain = preg_replace('/^www\./is', "", $thishost);

           if ($site_config["ACONFIRM"]) {
               $body = T_("YOUR_ACCOUNT_AT") . " " . $site_config['SITENAME'] . " " . T_("HAS_BEEN_CREATED_YOU_WILL_HAVE_TO_WAIT") . "\n\n" . $site_config['SITENAME'] . " " . T_("ADMIN");
           } else {
               $body = T_("YOUR_ACCOUNT_AT") . " " . $site_config['SITENAME'] . " " . T_("HAS_BEEN_APPROVED_EMAIL") . "\n\n " . $site_config['SITEURL'] . "/account-confirm.php?id=$id&secret=$psecret\n\n" . T_("HAS_BEEN_APPROVED_EMAIL_AFTER") . "\n\n " . T_("HAS_BEEN_APPROVED_EMAIL_DELETED") . "\n\n" . $site_config['SITENAME'] . " " . T_("ADMIN");
           }

           if ($site_config["CONFIRMEMAIL"]) {
               sendmail($email, "Your $site_config[SITENAME] User Account", $body, "", "-f$site_config[SITEEMAIL]");
               header("Refresh: 0; url=account-confirm-ok.php?type=signup&email=" . urlencode($email));
           } else {
               header("Refresh: 0; url=account-confirm-ok.php?type=noconf");
           }

           if ($site_config["WELCOMEPMON"]) {
               $dt = sqlesc(get_date_time());
               $msg = sqlesc($site_config["WELCOMEPMMSG"]);
               $subject = sqlesc("Welcome");
               SQL_Query_exec("INSERT INTO messages (sender, receiver, subject, added, msg, poster) VALUES(0, $id, $subject, $dt, $msg, 0)");
           }

           die;
       }
   }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
   <meta charset="UTF-8">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title><?php echo $site_config['SITENAME']; ?></title>
   <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
   <link rel="stylesheet" type="text/css" href="css/fontawesome-all.min.css">
   <link rel="stylesheet" type="text/css" href="css/iofrm-style.css">
   <link rel="stylesheet" type="text/css" href="css/iofrm-theme14.css">

   <style>
       body {
           min-height: 100vh;
           background-image: url('images/reaper.jpg');
           background-size: cover;
           background-position: center;
           background-repeat: no-repeat;
           background-attachment: fixed;
       }

       .form-body {
           background: rgba(0, 0, 0, 0.7);
           min-height: 100vh;
           display: flex;
           align-items: center;
           justify-content: center;
       }

       .form-content {
           background: rgba(20, 20, 20, 0.9);
           border-radius: 10px;
           padding: 20px;
           box-shadow: 0 0 15px rgba(0, 255, 255, 0.2);
       }

       .form-items {
           color: #ccc;
       }

       .form-items h3,
       .form-items a {
           color: #e0e0e0;
       }

       .password-container {
           position: relative;
           width: 100%;
       }

       .form-control {
           width: 100%;
           padding-right: 40px;
           background: #333;
           border: 1px solid #555;
           color: #fff;
       }

       .password-toggle-icon {
           position: absolute;
           right: 10px;
           top: 50%;
           transform: translateY(-50%);
           cursor: pointer;
           color: #666;
           font-size: 18px;
       }

       .password-toggle-icon:hover {
           color: #0ff;
       }

       .btn-discord {
           background: #5865F2;
           color: white;
           border: none;
           border-radius: 8px;
           padding: 10px 20px;
           font-size: 16px;
           font-weight: bold;
           transition: 0.3s;
       }

       .btn-discord:hover {
           background: #4752C4;
       }

       .ibtn {
           background: #0a6c74;
           border: none;
       }

       .ibtn:hover {
           background: #0c8b96;
       }

       .project-honeypot {
           background: rgba(30, 30, 30, 0.8);
           padding: 12px;
           border-radius: 8px;
           border: 1px solid #0ff;
           max-width: 260px;
           margin: 0 auto;
       }

       .chacro {
           color: #ccc;
           font: bold 12px Arial;
           text-decoration: none;
       }

       .chacro:hover {
           color: #0ff;
           text-decoration: underline;
       }

       ::placeholder {
           color: #666;
       }
   </style>
</head>

<body>

   <div class="form-body container-fluid">
       <div class="row">
           <div class="form-holder">
               <div class="form-content">
                   <div class="form-items">
                       <h3>Can we be besties?</h3>
                       <p>You know the drill.</p>

                       <div class="page-links">
                           <a href="account-login.php">Login</a>
                           <a href="account-signup.php" class="active">Register</a>
                           <a href="account-recover.php">Recover Account</a>
                       </div>

                       <form method="post" action="account-signup.php?takesignup=1">

                           <?php if ($invite_row) { ?>
                               <input type="hidden" name="invite" value="<?php echo $_GET["invite"]; ?>">
                               <input type="hidden" name="secret" value="<?php echo htmlspecialchars($_GET["secret"]); ?>">
                           <?php } ?>

                           <!-- RECAPTCHA ADD -->
                           <input type="hidden" name="recaptcha_response" id="recaptcha_response">

                           <input class="form-control" type="text" name="wantusername" placeholder="Username" required>

                           <div class="password-container">
                               <input class="form-control" type="password" name="wantpassword" id="wantpassword" placeholder="Password" required>
                               <span class="password-toggle-icon" id="toggleWantPassword"><i class="fas fa-eye"></i></span>
                           </div>

                           <div class="password-container">
                               <input class="form-control" type="password" name="passagain" id="passagain" placeholder="Confirm Password" required>
                               <span class="password-toggle-icon" id="togglePassAgain"><i class="fas fa-eye"></i></span>
                           </div>

                           <input class="form-control" type="text" name="email" placeholder="E-mail Address" <?php echo $invite_row ? '' : 'required'; ?>>

                           <div class="form-button">
                               <button id="submit" type="submit" class="ibtn">Register</button>
                           </div>

                           <div class="discord-join">
                               <a href="https://discord.gg/r3B5mHEwfM" target="_blank" class="btn btn-discord">
                                   <i class="fab fa-discord"></i> Join Our Discord For Any Help
                               </a>
                           </div>

                           <div class="project-honeypot text-center mt-3">
                               <a href="http://www.projecthoneypot.org/" target="_blank" class="chacro d-block mb-1">MEMBER OF PROJECT HONEY POT</a>
                               <a href="http://www.unspam.com" target="_blank" class="chacro d-block">Spam Harvester Protection Network</a>
                           </div>

                       </form>
                   </div>
               </div>
           </div>
       </div>
   </div>

   <!-- Scripts -->
   <script src="js/jquery.min.js"></script>
   <!-- <script src="js/popper.min.js"></script> -->
   <script src="js/bootstrap.min.js"></script>
   <script src="js/main.js"></script>

   <script>
       document.getElementById("toggleWantPassword").addEventListener("click", function() {
           var input = document.getElementById("wantpassword");
           var icon = this.querySelector("i");
           input.type = input.type === "password" ? "text" : "password";
           icon.classList.toggle("fa-eye");
           icon.classList.toggle("fa-eye-slash");
       });

       document.getElementById("togglePassAgain").addEventListener("click", function() {
           var input = document.getElementById("passagain");
           var icon = this.querySelector("i");
           input.type = input.type === "password" ? "text" : "password";
           icon.classList.toggle("fa-eye");
           icon.classList.toggle("fa-eye-slash");
       });
   </script>


   <!-- RECAPTCHA v3 integration -->

   <script src="https://www.google.com/recaptcha/api.js?render=<?php echo $site_config["RECAPTCHA_SITE_KEY"]; ?>"></script>
   <script>
       grecaptcha.ready(function() {
           grecaptcha.execute('<?php echo $site_config["RECAPTCHA_SITE_KEY"]; ?>', {
               action: 'signup'
           }).then(function(token) {
               document.getElementById("recaptcha_response").value = token;
           });
       });
   </script>

</body>

</html>

TTv3 Micro Edition
Ubuntu 20.04.6 LTS Server
Mysql Version: 10.3.39-MariaDB-0ubuntu0.20.04.2
PHP Version: 7.4.3-4ubuntu2.20
Apache Version: Apache/2.4.59 (Ubuntu)
Last edited by MicroMonkey on 2026-06-18 17:41:12
2026-06-19 05:11:19
That makes perfect sense.

I like the approach of keeping the existing SQL_Query() / SQL_Query_exec() system intact and simply adding SQL_Query_prepared() for user input.

Looking through your signup example, it seems like a practical way to gradually migrate sensitive areas without rewriting an entire TorrentTrader codebase at once.

I also noticed you're already using it consistently for username, email, IP checks, country lookups, and account creation, which is exactly where prepared statements provide the most value.

For long-running TT sites, that kind of gradual migration feels much safer than a full replacement.

Thanks again for sharing your work and testing results. It's always interesting to see what other TT admins are experimenting with.
Last edited by spiritblue on 2026-06-19 05:14:51
Users online

No users online

Search



Statistics

    Torrents

  • Tracking: 3
  • Todays torrents: 0
  • Seeders: 0
  • Leechers: 0
  • Peers: 0
  • Downloaded: 89.96 GB
  • Uploaded: 9.86 GB

  • Members

  • We have: 838
  • New today: 0
  • Guest today: 9

  • Online

  • Total online: 10
  • Members: 0
  • Guests online: 10
  • Comments: 3
  • Messages: 1,728