我该如何优化这个mysql查询?脚本已发布

时间:2017-01-31 21:55:30

标签: php mysql optimization pdo query-optimization

所以我在下面有这个代码用于连接和执行服务器上mysql的命令,它用于任何.NET项目的身份验证系统。现在,当我在网上吸引大约150多名用户时,它将开始减慢网站速度,并且mysql开始使用大量资源。有没有办法让这些mysql查询执行得更快或者没有挂断?

$bn123 = $_GET['bn'];
    $hwid = $_GET['hwid'];
    $ip = getRealIpAddr();
    $pcname = $_GET['pcname'];
    $country123 = "N/A";
    $time123 = time();

    $GetRows = $odb->query("SELECT * FROM `Account` WHERE bn = '$bn123'");
    $row_count = $GetRows->rowCount();
    $count = $row_count;
    if($count == 0){
        $odb->exec("INSERT INTO `logs` (id, bn, cpukey, ip, pcname, time, log) VALUES(NULL,'$bn123','$hwid','$ip','$pcname','$time123','SUCCESS - Bot Registered.')");
        $odb->exec("INSERT INTO `Account` (id, bn, cpukey, banned, ip, country, pcname, note, online, function, lastlogon) VALUES(NULL,'$bn123','$hwid','0','$ip','$country123','$pcname','','0','','')");
    }

    $SQLGetUsers = $odb -> query("SELECT * FROM Account WHERE `bn` = '$bn123'") or die(mysql_error()); 
    while ($getInfo = $SQLGetUsers -> fetch(PDO::FETCH_ASSOC))
    {
        $banned123 = $getInfo['banned'];
        if ($banned123 == 0) {
            $str = "Not Banned";
        } else {
            $str = "Banned";
        }
    }
    $response = $str;
    if ($response == "Not Banned")
    {
        $finaleresponse = "Success";
        $odb->exec("UPDATE Account SET `online` = '1', `lastlogon` = '$time123', `ip` = '$ip', `country` = '$country123', `pcname` = '$pcname' WHERE `bn` = '$bn123'");
    } 
    else if ($response == "Banned")
    {
        $finaleresponse = "Banned";
        $odb->exec("UPDATE Account SET `online` = '0', `lastlogon` = '$time123', `ip` = '$ip' WHERE `bn` = '$bn123'");
        $odb->exec("INSERT INTO logs (id, bn, cpukey, ip, pcname, time, log) VALUES(NULL,'$bn123','$hwid','$ip','$pcname','$time123','ERROR - User banned.')");
    }
    else
    {
        $finaleresponse = "Error";
        $odb->exec("UPDATE Account SET `online` = '0', `lastlogon` = '$time123', `ip` = '$ip' WHERE `username` = '$username1'");
        $odb->exec("INSERT INTO logs (id, username, cpukey, ip, pcname, time, log) VALUES(NULL,'$username1','$hwid','$ip','$pcname','$time123','ERROR - Something went wrong.')");
    }
    echo Encrypt($finaleresponse);

请告诉我任何优化此代码的方法,因为我认为它已经过优化,谢谢!这里还有db.php:

<?php
define('DB_HOST', 'localhost');
define('DB_NAME', '');
define('DB_USERNAME', '');
define('DB_PASSWORD', '');

$odb = new PDO('mysql:host=' . DB_HOST . ';dbname=' . DB_NAME, DB_USERNAME, DB_PASSWORD);
?>

1 个答案:

答案 0 :(得分:0)

INSERTs“不能”慢“。所以它必须是5 SELECTsUPDATEs。 5不是一个大数字,所以必须有一个缺失的索引。

所有5个人都需要bn Account上的索引? (请为所涉及的每个表提供SHOW CREATE TABLE,因此我不会提出已经完成的建议。)

此外,...不要从Account两次获取相同的行。