SQL Injection ni moja ya most common web vulnerabilities ambapo attacker anaweza kuingiza malicious SQL commands kwenye input fields na kudhuru database.

Solution: Use prepared statements na parameterized queries ili ku-separate data na SQL commands.

Faida:

Input haiwezi affect SQL structure.

Safe to use user input directly.

Improves security na maintainability.

⚙️ 2. Example Using PDO
<?php
// Database connection
$host = 'localhost';
$db = 'testdb';
$user = 'root';
$pass = '';
$dsn = "mysql:host=$host;dbname=$db;charset=utf8mb4";

try {
$pdo = new PDO($dsn, $user, $pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e){
die("Database connection failed: " . $e->getMessage());
}

// User input
$username = $_POST['username'];
$password = $_POST['password'];

// Prepared statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username AND password = :password");
$stmt->execute(['username' => $username, 'password' => $password]);

$user = $stmt->fetch();

if($user){
echo "✅ Login successful!";
} else {
echo "❌ Invalid credentials!";
}
?>


💡 Maelezo:

:username na :password ni placeholders.

PDO automatically escapes user input.

No attacker can inject SQL because input is treated as data.

🧩 3. Example Using MySQLi
<?php
$conn = new mysqli("localhost", "root", "", "testdb");

if($conn->connect_error){
die("Connection failed: " . $conn->connect_error);
}

$username = $_POST['username'];
$password = $_POST['password'];

// Prepare statement
$stmt = $conn->prepare("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
$result = $stmt->get_result();

if($result->num_rows > 0){
echo "✅ Login successful!";
} else {
echo "❌ Invalid credentials!";
}

$stmt->close();
$conn->close();
?>


? ni placeholder, bind_param() inashika input.

SQL structure haibadiliki hata input ni malicious.

🔑 4. Best Practices

Always use prepared statements – never directly concatenate user input.

Sanitize inputs – extra layer of protection.

Use strong password hashing – never store plain passwords.

Limit database privileges – principle of least privilege.

Enable error reporting only in development – hide sensitive info in production.

✅ 5. Hitimisho

Prepared statements ni must-have kwa secure database queries.

PDO na MySQLi zote zinatoa parameterized queries kwa SQL injection prevention.

Combine with input sanitization na password hashing kwa maximum security.

🔗 Tembelea:

👉 https://www.faulink.com/

Kwa mafunzo zaidi ya PHP, prepared statements, na secure database development.