鉴于此查询
$query = "SELECT * FROM products WHERE category = {category} AND price = '{price}'"
使用这些$ _GET参数:category = 10和price = $ 60
我想用实际的GET值替换{}内的内容 得到像这样的SQL查询:
"SELECT * FROM products WHERE category = 10 AND price = '$60'"
但如果缺少一个或多个或参数,我想替换{}的内容 与不同的东西,以避免执行。例如:
"SELECT * FROM products WHERE category = category AND price = price"
注意:我知道sql注入。这是一个不同的主题。我想知道如果不存在值(来自get)如何避免执行sql stamente。 例如,从id = id的产品中选择*返回所有产品,但从id = 100的产品中选择*只返回一个(ID为100)
答案 0 :(得分:0)
关于评论,我建议您将查询更改为类似的内容。
//variables
if(isset($_GET['category']) && isset($_GET['price'])) {
$category = $_GET['category'];
$price = $_GET['price'];
//create server instance
$mysqli = new mysqli("server", "username", "password", "database_name");
//make sure there was no errors with the connection
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
//create a parameterized query
$query = $mysqli->prepare("SELECT * FROM products WHERE category = ? AND price = '?'");
//bind query params
$query->bind_param("s", $category, $price);
//execute the query and then clean up
$query->execute();
$query->close();
$mysqli->close();
}
有关详情,请参阅我的POST
答案 1 :(得分:0)
对于一个简单的查询,这是OP方式,但请看Doctrine,它是处理查询的完美图层
答案 2 :(得分:0)
由于SQL注入,这不是解决此问题的正确方法。试试这个:
if(isset($_GET['category']) && isset($_GET['price'])) {
// you might want to consider validating user input
//use either PDO or MySQLi with parametized Query e.g.
$stmt = $pdo_instance->prepare("SELECT * FROM products WHERE category = :category AND price = :price");
$stmt->bindValue(":category", $_GET['category']);
$stmt->bindValue(":price", $_GET['category']);
} else if(isset($_GET['category'])) {
//use either PDO or MySQLi with parametized Query e.g.
$stmt = $pdo_instance->prepare("SELECT * FROM products WHERE category = :category");
$stmt->bindValue(":category", $_GET['category']);
} else if(isset($_GET['price'])) {
//use either PDO or MySQLi with parametized Query e.g.
$stmt = $pdo_instance->prepare("SELECT * FROM products WHERE price = :price");
$stmt->bindValue(":price", $_GET['price']);
}