我希望通过他的电子邮件地址或用户名获取用户...但它不起作用。每当我使用字符串而不是数字时,我就会变错。
这是一个学校项目,所以我不能使用任何框架:(
这不起作用 $ objAcc-> getUser('email','example@gmail.com')
这有效
$objAcc->getUser('user_id', '1')
了Methode:
public function getUser($by = NULL, $value = NULL, $quantity = 0) {
global $database;
try {
$row = array();
if (isset($by) && isset($value)) {
$query = 'SELECT * FROM "user" WHERE :by=:value';
$stmt = $database->prepare($query);
$type = ($by == 'user_id' || $by == 'phone' || $by == 'fax' || $by == 'zip' || $by == 'admin') ? SQLITE3_INTEGER : SQLITE3_TEXT;
$stmt->bindValue(':by', $by, SQLITE3_TEXT);
$stmt->bindValue(':value', $value, $type);
$result = $stmt->execute();
} else {
$query = 'SELECT * FROM "user"';
$stmt = $database->prepare($query);
$result = $stmt->execute();
}
if ($quantity) {
for ($i = 0; $i < $quantity; $i++) {
$row[ $i ] = $result->fetchArray(SQLITE3_ASSOC);
}
} else {
$i = 0;
while ($entry = $result->fetchArray(SQLITE3_ASSOC)) {
$row[ $i ] = $entry;
$i++;
}
}
if (empty($row[0])) {
return FALSE;
}
return $row;
} catch (Exception $e) {
var_dump($e);
die();
}
}
我希望你能帮助我们。
答案 0 :(得分:1)
我认为您不能对列名使用绑定。我建议动态创建SQL语句,但只有在验证 $ by 参数与现有列名匹配后(避免SQL注入的风险):
$numFields = array("user_id", "phone", "fax", "zip", "admin");
$charFields = array("email");
$allFields = array_merge($numFields, $charFields);
$row = array();
if (isset($by) && isset($value) && in_array($by, $allFields)) {
$query = 'SELECT * FROM "user" WHERE ' . $by . '=:value';
$stmt = $database->prepare($query);
$type = in_array($numFields, $by) ? SQLITE3_INTEGER : SQLITE3_TEXT;
$stmt->bindValue(':value', $value, $type);
} else {
$query = 'SELECT * FROM "user"';
$stmt = $database->prepare($query);
}
$result = $stmt->execute();