# MySQLi Database Configuration & Integration Guide

The Google AI Studio "Tap +1" backend is completely implemented using the native PHP **MySQLi** (MySQL Improved) extension with secure, structured prepared statement structures.

Below is an overview of how MySQLi is configured and how you can run it on your own server.

---

## 1. Database Connection Configuration (`db_config.php`)

All requests are authenticated and run via standard connectivity definitions:

```php
<?php
header('Content-Type: application/json; charset=utf-8');

define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'tap_plus_db');
define('ADMIN_KEY', 'tapplus_secret_key_2026');

// Object-Oriented MySQLi connection instantiation
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

if ($conn->connect_error) {
    echo json_encode([
        "success" => false, 
        "error" => "MySQL Connection failed: " . $conn->connect_error
    ]);
    exit();
}

$conn->set_charset("utf8mb4");
?>
```

---

## 2. Secure MySQLi prepared statements usage example

Whenever a user executes Google Google-Auth backing inside `register_user.php` or `check_gmail.php`, we execute mysqli prepared statements. This is secure against SQL Injection:

### Checking Gmail mapping:
```php
$stmt = $conn->prepare("SELECT user_id, display_name FROM users WHERE gmail = ?");
$stmt->bind_param("s", $gmail);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
$stmt->close();
```

### Storing/Upserting registered User Details:
```php
$stmt_in = $conn->prepare("INSERT INTO users (user_id, gmail, display_name, created_at) VALUES (?, ?, ?, ?)");
$stmt_in->bind_param("sssi", $userId, $gmail, $displayName, $now);
$stmt_in->execute();
$stmt_in->close();
```

---

## 3. Creating tables structure (`database_schema.sql`)

You may run the following script on your SQL editor (e.g. phpMyAdmin, Adminer, or Command Prompt mysql client) to initialize the structure:

```sql
-- database_schema.sql
CREATE TABLE IF NOT EXISTS users (
    user_id VARCHAR(50) PRIMARY KEY,
    gmail VARCHAR(100) DEFAULT NULL,
    display_name VARCHAR(100) DEFAULT 'Tapper',
    avatar_url VARCHAR(255) DEFAULT NULL,
    fcm_token VARCHAR(255) DEFAULT NULL,
    created_at BIGINT DEFAULT 0
);

CREATE TABLE IF NOT EXISTS game_sessions (
    session_id VARCHAR(50) PRIMARY KEY,
    user_id VARCHAR(50) NOT NULL,
    game_mode VARCHAR(50) NOT NULL,
    score INT NOT NULL,
    duration_seconds INT NOT NULL,
    played_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    synced TINYINT DEFAULT 1
);
```
