2017-10-11 174 views
0

我有一个web应用程序,当单击文档的链接时,会调用一个PHP脚本,用于更新数据库中文档的“已查看”状态。这是脚本时,点击碰巧被称为:“子查询返回多于1行”,没有子查询MySQL?

<?php 
include '../../variables.php'; 

// The document that is passed through POST 
$document = $_POST['document']; 

$conn = new mysqli($dbhost, $dbuser, $dbpassword, $db); 

if (!$conn){ 
    die('Could not connect to db: '.mysqli_error($conn)); 
} 

$sql = "UPDATE files 
     SET docViewed = '1' 
     WHERE fileloc = '$document'"; 
$query = mysqli_query($conn, $sql); 

if (!$query){ 
    die('Could not update docViewed: '.mysqli_error($conn)); 
} 
?> 

正如你所看到的,我在MySQL查询,更新我想现场没有子查询,但我仍然很收到此错误:

Could not update docViewed: Subquery returns more than 1 row

我试图附加到查询:

"... 
WHERE fileloc = '$document' 
LIMIT 1"; 

不过,我还是得到同样的结果。

要清楚,每个$document必须在数据库中是唯一的,因此没有重复的条目。

更新:本文不是建议的文章的副本,因为OP使用的是子查询。在这个例子中,我没有在任何地方使用子查询。

这里是我使用的files表的结构。

enter image description here

更新2:也表明不存在$document式两份,由我fileloc这是30294/1506012960606.pdf过滤表我缩小了正在发生,产生这种错误的实际MySQL查询:

UPDATE files 
SET docViewed = '1' 
WHERE fileloc = '30294/1492682311085.pdf' 
+0

Wierd错误你确定文件是表格而不是视图吗? –

+0

文件确实是它自己的表 – Jodo1992

+0

它不是重复的,因为在该文章中,OP实际上是使用子查询。我不是 – Jodo1992

回答

1

这不会有太大变化,但增加了一些记录点可能向下钻取,其中问题。我将你的mysqli用法更新为面向对象的方法,以及使用预先准备好的语句参数化查询(总是很好避免sql注入,但在这种情况下更加实用,因为它允许我们在几个步骤中测试查询)。

<?php 
try { 
    include '../../variables.php'; 

    // The document that is passed through POST 
    $document = filter_input(INPUT_POST, 'document', FILTER_SANITIZE_STRING); 

    $conn = new mysqli($dbhost, $dbuser, $dbpassword, $db); 

    if ($conn->connect_error){ 
     throw new Exception("({$conn->errno}) {$conn->error}"); 
    } 

    $sql = "UPDATE files 
      SET docViewed = '1' 
      WHERE fileloc = ?"; 
    $stmt = $conn->prepare($sql); 

    if (!$stmt) { 
     throw new Exception("({$conn->errno}) {$conn->error}"); 
    } 
    $stmt->bind_param('s', $document); 
    $exec = $stmt->execute(); 

    if (!$exec) { 
     throw new Exception($stmt->error); 
    } else if ($stmt->affected_rows === 0) { 
     throw new Exception('No file location found'); 
    } 


} catch (Exception $e) { 
    error_log($e); 
    die($e->getMessage()); 
} 
?>