PHP 私有方法没有赋值参数

PHP Private method is not assept a parameter

我想制作一个 class 来显示数据库中的随机数据并计算它显示的次数。

下一个顺序。

  1. 我从数据库中获取随机数据。
  2. 我增加了它的观看次数。
  3. 我在页面上显示获取(和增加)的数据。

我的代码:

class Translate

private $db ;
private $result ;
private $foreign;
private $translation;

function __construct()
{
    $this->db = new PDO('mysql:host=localhost;dbname=translate;charset=utf8', 'root', '');
}

private function increaseView($word)   
{
    $sql = $this->db->prepare("UPDATE admin_words SET was_shown = was_shown + 1  WHERE in_english=   ' " . $word . " ' ");
    $sql->execute();        
}

public function getNewWord()
{
    $this->result = $this->db->query('SELECT * FROM admin_words ORDER BY RAND() LIMIT 1');
    $this->result = $this->result->fetchAll();

    // next string is not working
    $this->increaseView('book');

    return $this->result;
} 

我接下来使用它:

$word = new Translate();
$texts = $word->getNewWord();

问题不在于$texts。效果很好。但是我无法将参数发送到

private function increaseView($word)    
{
    $sql = $this->db->prepare("UPDATE admin_words SET was_shown = was_shown + 1  WHERE in_english=   ' " . $word . " ' ");
    $sql->execute();        
}

来自

// next string is not working
$this->increaseView('book');

当前行为: 我的随机数据也显示了,但计数没有增加。 显示任何错误。 但是如果我使用 $sql = $this->db->prepare("UPDATE admin_words SET was_shown = was_shown + 1 WHERE in_english= 'book' "); 'book' 而不是变量,它更新 table。(效果很好)

我做错了什么?

首先,您可能希望将准备好的语句与 bindParam 一起使用,而不是直接在 sql 中嵌入变量 - 尽管 sql 注入的机会很小。更新方法 increaseView 应该使用从 select 查询返回的值,如果不是——也许像这样?

class Translate{

    private $db;
    private $result;
    private $foreign;
    private $translation;

    function __construct()
    {
        $this->db = new PDO('mysql:host=localhost;dbname=translate;charset=utf8', 'root', '');
    }

    private function increaseView($word)   
    {
        $sql = $this->db->prepare("UPDATE admin_words SET was_shown = was_shown + 1 WHERE in_english=:word");
        $sql->bindParam( ':word', $word );
        $sql->execute();        
    }

    public function getNewWord()
    {
        $this->result = $this->db->query('SELECT * FROM admin_words ORDER BY RAND() LIMIT 1');
        $this->result = $this->result->fetchAll();
        $this->increaseView( $this->result['in_english'] ); /* is this the field / column ?? */
        return $this->result;
    }
}

$word = new Translate;
$texts = $word->getNewWord();