Raised This Month: $32 Target: $400
 8% 

[ISSUE] Problem while storing data in the database


Post New Thread Reply   
 
Thread Tools Display Modes
Author Message
SpirT
Senior Member
Join Date: Sep 2018
Location: Portugal
Old 05-08-2020 , 15:45   [ISSUE] Problem while storing data in the database
Reply With Quote #1

So,

What I am trying to do is really simple

Store the name, steamid and IP on the database when he joins the server. But, when connecting I want to the plugin to check if the player is already registered. So, we get the IP that is stored on the database for the player's steamid. If the database player's IP does not match to the actual player's IP, I want it to write a new line with new data, as such the name, steamID and iP.

The problem is that it is not storing any data.

PHP Code:
#pragma semicolon 1

#define DEBUG

#define PLUGIN_AUTHOR "SpirT"
#define PLUGIN_VERSION "1.0"

#include <sourcemod>
#include <sdktools>

Database DB null;
char Error[256];

#pragma newdecls required

public Plugin myinfo 
{
    
name "[SpirT - Database Query]",
    
author PLUGIN_AUTHOR,
    
description "",
    
version PLUGIN_VERSION,
    
url ""
};

public 
void OnPluginStart()
{
    
DB SQL_Connect("spirtdb"trueErrorsizeof(Error));
    
    if(
DB == null)
    {
        
PrintToServer("[DB] Cannot connect to MySQL Server: %s"Error);
        
CloseHandle(DB);
    }
    else
    {
        
PrintToServer("[DB] Connection Successful");
        
char squery[256];
        
Format(squerysizeof(squery), "CREATE TABLE IF NOT EXISTS players (name varchar(32) NOT NULL, steamid varchar(32) NOT NULL, ip varchar(64) NOT NULL)");
        if(!
SQL_FastQuery(DBsquery))
        {
            
char terror[256];
            
SQL_GetError(DBterrorsizeof(terror));
            
PrintToServer("[DB] Could not create db tables. Error: %s"terror);
        }
        else
        {
            
PrintToServer("[DB] Tables Created if they don't exist.");
        }
    }
}

public 
void OnClientPutInServer(int client)
{
    
char iname[32];
    
GetClientName(clientinamesizeof(iname));
    
    
char iid[32];
    
GetClientAuthId(clientAuthId_Steam2iidsizeof(iid));
    
    
char iip[64];
    
GetClientIP(clientiipsizeof(iip), true);
    
    
char squery[256];
    
Format(squerysizeof(squery), "SELECT ip FROM players WHERE steamid = '%s'"iid);
    
DBResultSet select SQL_Query(DBsquery);
    
    if(
select == null)
    {
        
PrintToServer("[DB] Could not get data from the database.");
        return;
    }
    
    
char dbIP[64];
    
SQL_FetchString(DB0dbIPsizeof(dbIP));
    
    if(
StrEqual(dbIPiip))
    {
        
PrintToServer("[DB] Player is already saved on the database.");
        return;
    }
    
    
char newquery[256];
    
Format(newquerysizeof(newquery), "INSERT INTO players (name, steamid, ip) VALUES ('%s', '%s', '%s')"inameiidiip);
    
DBResultSet query2 SQL_Query(DBnewquery);
    if(
query2 == null)
    {
        
PrintToServer("[DB] Could not save new player data.");
        return;
    }
    
    
PrintToServer("[DB] New player data was save in the database with success.");
    return;

Any solution for the plugin to fix my issue?

OBS: That plugin was storing the player data EVERYTIME he joined the server, so I tried to update it to a more NON-SPAMMING version. This "new update" on the source above is creating the tables but not storing data.

Best Regards,

SpirT.
__________________
SpirT is offline
8guawong
AlliedModders Donor
Join Date: Dec 2013
Location: BlackMarke7
Old 05-09-2020 , 10:03   Re: [ISSUE] Problem while storing data in the database
Reply With Quote #2

Your sql query is always inserting
You should update instead of insert if the player is already in the databse
And you should definetly use threaded query
__________________
8guawong is offline
SpirT
Senior Member
Join Date: Sep 2018
Location: Portugal
Old 05-09-2020 , 12:29   Re: [ISSUE] Problem while storing data in the database
Reply With Quote #3

Quote:
Originally Posted by 8guawong View Post
Your sql query is always inserting
You should update instead of insert if the player is already in the databse
And you should definetly use threaded query
Hey! Thanks for your reply. I did some changes and now it is storing the values but keeps storing everytime I join the server. Any idea to just store when he connects for the first time and when he changes the IP?

PHP Code:
#pragma semicolon 1

#define DEBUG

#define PLUGIN_AUTHOR "SpirT"
#define PLUGIN_VERSION "1.0"

#include <sourcemod>
#include <sdktools>

Database DB null;
char Error[256];

#pragma newdecls required

public Plugin myinfo 
{
    
name "[SpirT - Database Query]",
    
author PLUGIN_AUTHOR,
    
description "",
    
version PLUGIN_VERSION,
    
url ""
};

public 
void OnPluginStart()
{
    
DB SQL_Connect("spirtdb"trueErrorsizeof(Error));
    
    if(
DB == null)
    {
        
PrintToServer("[DB] Cannot connect to MySQL Server: %s"Error);
        
CloseHandle(DB);
    }
    else
    {
        
PrintToServer("[DB] Connection Successful");
        
char squery[256];
        
Format(squerysizeof(squery), "CREATE TABLE IF NOT EXISTS players (name varchar(32) NOT NULL, steamid varchar(32) NOT NULL, ip varchar(64) NOT NULL)");
        if(!
SQL_FastQuery(DBsquery))
        {
            
char terror[256];
            
SQL_GetError(DBterrorsizeof(terror));
            
PrintToServer("[DB] Could not create db tables. Error: %s"terror);
        }
        else
        {
            
PrintToServer("[DB] Tables Created if they don't exist.");
        }
    }
}

public 
void OnClientPutInServer(int client)
{
    
char iname[32];
    
GetClientName(clientinamesizeof(iname));
    
    
char iid[32];
    
GetClientAuthId(clientAuthId_Steam2iidsizeof(iid));
    
    
char iip[64];
    
GetClientIP(clientiipsizeof(iip), true);
    
    
char squery[256];
    
Format(squerysizeof(squery), "SELECT ip FROM players WHERE steamid = '%s'"iid);
    
DBResultSet select SQL_Query(DBsquery);
    
    if(
select == null)
    {
        
PrintToServer("[DB] Could not get data from the database.");
        return;
    }
    
    if(
select.FetchRow())
    {
        
char dbip[64];
        
int ipColumn;
        
select.FieldNameToNum("ip"ipColumn);
        
SQL_FetchString(selectipColumndbipsizeof(dbip));
        
        if(
StrEqual(dbipiip))
        {
            
PrintToServer("[DB] Player is already in the Database. Skipping...");
            return;
        }
        else
        {
            
char StoreAgain[256];
            
Format(StoreAgainsizeof(StoreAgain), "INSERT INTO players (name, steamid, ip) VALUES ('%s', '%s', '%s')"inameiidiip);
            
DBResultSet NewStore SQL_Query(DBStoreAgain);
            if(
NewStore == null)
            {
                
PrintToServer("[DB] Could not insert new data to the database.");
                return;
            }
            else
            {
                
PrintToServer("[DB] New player data was stored with success on the database.");
                return;
            }
        }
    }
    else
    {
        
char newquery[256];
        
Format(newquerysizeof(newquery), "INSERT INTO players (name, steamid, ip) VALUES ('%s', '%s', '%s')"inameiidiip);
        
DBResultSet query2 SQL_Query(DBnewquery);
        if(
query2 == null)
        {
            
PrintToServer("[DB] Could not save new player data.");
            return;
        }
        else
        {
            
PrintToServer("[DB] New player data was save in the database with success.");
            return;
        }
    }

Best Regards,

SpirT
__________________
SpirT is offline
8guawong
AlliedModders Donor
Join Date: Dec 2013
Location: BlackMarke7
Old 05-09-2020 , 13:30   Re: [ISSUE] Problem while storing data in the database
Reply With Quote #4

Quote:
Originally Posted by SpirT View Post
Hey! Thanks for your reply. I did some changes and now it is storing the values but keeps storing everytime I join the server. Any idea to just store when he connects for the first time and when he changes the IP?

PHP Code:
#pragma semicolon 1

#define DEBUG

#define PLUGIN_AUTHOR "SpirT"
#define PLUGIN_VERSION "1.0"

#include <sourcemod>
#include <sdktools>

Database DB null;
char Error[256];

#pragma newdecls required

public Plugin myinfo 
{
    
name "[SpirT - Database Query]",
    
author PLUGIN_AUTHOR,
    
description "",
    
version PLUGIN_VERSION,
    
url ""
};

public 
void OnPluginStart()
{
    
DB SQL_Connect("spirtdb"trueErrorsizeof(Error));
    
    if(
DB == null)
    {
        
PrintToServer("[DB] Cannot connect to MySQL Server: %s"Error);
        
CloseHandle(DB);
    }
    else
    {
        
PrintToServer("[DB] Connection Successful");
        
char squery[256];
        
Format(squerysizeof(squery), "CREATE TABLE IF NOT EXISTS players (name varchar(32) NOT NULL, steamid varchar(32) NOT NULL, ip varchar(64) NOT NULL)");
        if(!
SQL_FastQuery(DBsquery))
        {
            
char terror[256];
            
SQL_GetError(DBterrorsizeof(terror));
            
PrintToServer("[DB] Could not create db tables. Error: %s"terror);
        }
        else
        {
            
PrintToServer("[DB] Tables Created if they don't exist.");
        }
    }
}

public 
void OnClientPutInServer(int client)
{
    
char iname[32];
    
GetClientName(clientinamesizeof(iname));
    
    
char iid[32];
    
GetClientAuthId(clientAuthId_Steam2iidsizeof(iid));
    
    
char iip[64];
    
GetClientIP(clientiipsizeof(iip), true);
    
    
char squery[256];
    
Format(squerysizeof(squery), "SELECT ip FROM players WHERE steamid = '%s'"iid);
    
DBResultSet select SQL_Query(DBsquery);
    
    if(
select == null)
    {
        
PrintToServer("[DB] Could not get data from the database.");
        return;
    }
    
    if(
select.FetchRow())
    {
        
char dbip[64];
        
int ipColumn;
        
select.FieldNameToNum("ip"ipColumn);
        
SQL_FetchString(selectipColumndbipsizeof(dbip));
        
        if(
StrEqual(dbipiip))
        {
            
PrintToServer("[DB] Player is already in the Database. Skipping...");
            return;
        }
        else
        {
            
char StoreAgain[256];
            
Format(StoreAgainsizeof(StoreAgain), "INSERT INTO players (name, steamid, ip) VALUES ('%s', '%s', '%s')"inameiidiip);
            
DBResultSet NewStore SQL_Query(DBStoreAgain);
            if(
NewStore == null)
            {
                
PrintToServer("[DB] Could not insert new data to the database.");
                return;
            }
            else
            {
                
PrintToServer("[DB] New player data was stored with success on the database.");
                return;
            }
        }
    }
    else
    {
        
char newquery[256];
        
Format(newquerysizeof(newquery), "INSERT INTO players (name, steamid, ip) VALUES ('%s', '%s', '%s')"inameiidiip);
        
DBResultSet query2 SQL_Query(DBnewquery);
        if(
query2 == null)
        {
            
PrintToServer("[DB] Could not save new player data.");
            return;
        }
        else
        {
            
PrintToServer("[DB] New player data was save in the database with success.");
            return;
        }
    }

Best Regards,

SpirT
I already gave the answer above
Do an update query instead of insert query
https://www.w3schools.com/sql/sql_update.asp
__________________
8guawong is offline
Bacardi
Veteran Member
Join Date: Jan 2010
Location: mom's basement
Old 05-09-2020 , 13:45   Re: [ISSUE] Problem while storing data in the database
Reply With Quote #5

- This create table, which set timestamp on every record.
- When query player IP from database, plugin fetch first row only. Because we order query results by timestamp DESC.
- Plugin compare player IP with database IP. If not match, it makes new record.

PHP Code:


Handle MyDataBase
;

public 
void OnPluginStart()
{
    
SQL_TConnect(connect_callback"test");
}

public 
void connect_callback(Handle ownerHandle hndl, const char[] errorany data)
{
    
MyDataBase hndl;

    if(
MyDataBase == null)
    {
        
SetFailState("Error: %s"error);
    }

    
SQL_TQuery(MyDataBasecreatetable_callback"CREATE TABLE IF NOT EXISTS `players` (`name` varchar(64),`steamid` varchar(64),`ip` varchar(64),`timestamp` timestamp DEFAULT CURRENT_TIMESTAMP)");
}


public 
void createtable_callback(Handle ownerHandle hndl, const char[] errorany data)
{
    if(
hndl == null)
    {
        
LogError("Create table Error: %s"error);
        return;
    }
}

public 
void OnClientPostAdminCheck(int client)
{
    
char query[255], auth[30];
    
    if(!
GetClientAuthId(clientAuthId_Engineauthsizeof(auth))) return;
    
    
Format(querysizeof(query), "SELECT `ip` FROM `players` WHERE `steamid`='%s' ORDER BY `players`.`timestamp` DESC"auth);
    
SQL_TQuery(MyDataBasequery_callbackqueryGetClientUserId(client));
}


public 
void query_callback(Handle ownerHandle hndl, const char[] errorany data)
{
    
int client GetClientOfUserId(data);

    if(
client == || !IsClientInGame(client)) return;

    
char query[255], name[32], auth[30], ip[60];
    
    
GetClientName(clientnamesizeof(name));
    
char name2[64];
    
SQL_EscapeString(MyDataBasenamename2sizeof(name2)); // Don't save raw names in database!!
    
    
GetClientAuthId(clientAuthId_Engineauthsizeof(auth));
    
    
GetClientIP(clientipsizeof(ip));


    
// Query is not UPDATE, INSERT or DELETE
    
if(hndl != null && SQL_HasResultSet(hndl))
    {
        if(
SQL_GetRowCount(hndl))
        {
            if(!
SQL_FetchRow(hndl)) return;

            
char buffer[64];
            
SQL_FetchString(hndl0buffersizeof(buffer)); // fetch first row only (timestamp DESC)
            //PrintToServer("buffer %s", buffer);
            
            
if(StrEqual(bufferip))
            {
                return;
            }
        }


        
Format(querysizeof(query), "INSERT INTO `players` (`name`,`steamid`,`ip`) VALUES ('%s', '%s','%s')"name2authip);
        
SQL_TQuery(MyDataBasesave_callbackquery);

    }

}

public 
void save_callback(Handle ownerHandle hndl, const char[] errorany data)
{
    
PrintToServer("Done");



old
__________________
Do not Private Message @me

Last edited by Bacardi; 05-10-2020 at 01:29.
Bacardi is offline
Bacardi
Veteran Member
Join Date: Jan 2010
Location: mom's basement
Old 05-09-2020 , 13:52   Re: [ISSUE] Problem while storing data in the database
Reply With Quote #6

...unless, you want log history of ip changes, I think you need either to use timestamp to look latest IP record, or look bigest row ID number
*edit
Updated previous post
__________________
Do not Private Message @me

Last edited by Bacardi; 05-10-2020 at 01:29.
Bacardi is offline
Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -4. The time now is 00:16.


Powered by vBulletin®
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
Theme made by Freecode