如何使用php变量查询sqlite3

ato*_*eki 0 php sqlite

<?php
/**
 * Simple example of extending the SQLite3 class and changing the __construct
 * parameters, then using the open method to initialize the DB.
 */
class MyDB extends SQLite3
{
    function __construct()
    {
        $this->open('wifin.db');
    }
}
$db = new MyDB();

$mac = 'test';
$ssid = $_POST['ssid'];
$lat = $_POST['lat'];
$lon = $_POST['lon'];

$db->exec("INSERT INTO wifinTb (mac,ssid,lat,lon) VALUES ($mac,$ssid,$lat,$lon)");

$result = $db->query('SELECT * FROM wifinTb WHERE mac=$mac');

var_dump($result->fetchArray());

?>
Run Code Online (Sandbox Code Playgroud)

我不知道如何在php5中使用变量,$mac应该是一个字符串,当我直接使用时mac=$mac,它返回bool(false),这意味着找不到,但是当我使用时mac='test',它给了我结果。

CL.*_*CL. 5

切勿使用字符串连接或替换将值放入 SQL 语句中;这会给你带来格式化问题(如你所见)并允许SQL 注入攻击

相反,使用参数:

$stmt = $db->prepare('INSERT INTO wifinTb(mac,ssid,lat,lon) VALUES (?,?,?,?)');
$stmt->bindValue(1, 'test');
$stmt->bindValue(2, $_POST['ssid']);
$stmt->bindValue(3, $_POST['lat']);
$stmt->bindValue(4, $_POST['lon']);
$stmt->execute();

$stmt = $db->prepare('SELECT * FROM wifinTb WHERE mac = :mac');
$stmt->bindValue(':mac', $mac);
$result = $stmt->execute();
Run Code Online (Sandbox Code Playgroud)