3 回答

TA貢獻1886條經驗 獲得超2個贊
正確的方法是使用準備好的語句并將結果提取到數組中。您可以使用以下命令將所有行提取到數組中fetch_all()
$stmt = $conn->prepare("SELECT * FROM images WHERE imageURL = ?");
$stmt->bind_param('s', $post["media_url"]);
$stmt->execute();
// Get result and then fetch all rows from the result object
$result = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
// Then check if you have any rows at all using a simple if statement
// Negate it using ! to check if the array is empty
if (!$result) {
// no results found
}

TA貢獻1890條經驗 獲得超9個贊
我猜,那$conn是一個 PDO 連接?在這種情況下,該方法$conn->query()返回 PDOStatement 類型的對象。請參閱https://www.php.net/manual/de/class.pdostatement.php
該方法不返回結果集。
相反,您可以使用 PDOStatement 對象來獲取結果:
$currentURL = $post["media_url"];
$sql = "SELECT * FROM images WHERE imageURL = '$currentURL'";
$result = $conn->query($sql)->fetchAll();
if(empty($result))
{ ... }
如果您使用 mysqli,返回的對象query()是這樣的: https: //www.php.net/manual/en/class.mysqli-result.php
所以代碼是:
$currentURL = $post["media_url"];
$sql = "SELECT * FROM images WHERE imageURL = '$currentURL'";
$result = $conn->query($sql)->fetch_all(MYSQLI_ASSOC);
if(empty($result))
{ ... }
另請注意:您的代碼非常不安全!您應該使用準備好的語句來防止 sql 注入:
$currentURL = $post["media_url"];
$sql = "SELECT * FROM images WHERE imageURL = :currentUrl";
$stmt = $conn->prepare($sql);
$stmt->execute(['currentUrl' => $currentURL]);
$result = $stmt->fetchAll();
if(empty($result))
{ ... }

TA貢獻1839條經驗 獲得超15個贊
清理輸入以防止 SQL 注入(或更好 - 使用準備好的語句和參數綁定)
$sql = "SELECT * FROM images WHERE imageURL = '".$conn->real_escape_string($currentURL)."'";
mysqli 查詢成功時返回 true(即使空數據集也成功),請使用 num_rows 代替:
if ( $result->num_rows === 0 ) { ... }
- 3 回答
- 0 關注
- 133 瀏覽
添加回答
舉報