【问题标题】:insert new value into phpmysql DB将新值插入 php mysql DB
【发布时间】:2017-05-17 10:26:47
【问题描述】:

花点时间看一下我的代码,我无法将变量 dbentry 放入数据库中。

受保护的函数 moveFile($file) {

    $filename = isset($this->newName) ? $this->newName : $file['name'];
    $success = move_uploaded_file($file['tmp_name'], $this->destination . $filename);
    if ($success) {
        $result = $file['name'] . ' was uploaded successfully';
        if (!is_null($this->newName)) {
            $result .= ', and was renamed ' . $this->newName;
            $dbentry = $this->newName;
                echo "$dbentry";

                        $mysqli = new mysqli("localhost", "DBNAME", "PASSWORD", "USERNAME"); 
                        // Check connection
                        if($mysqli === false){
                            die("ERROR: Could not connect. " . $mysqli->connect_error);
                        } 
                        // attempt insert query execution
                        $sql = "INSERT INTO files (file_name) VALUES ('$dbentry')";
                        if($mysqli->query($sql) === true){
                            echo "Records inserted successfully.";
                        } else{
                            echo "ERROR: Could not  execute " . $mysqli->error;
                        }
                        // Close connection
                        $mysqli->close();

                //
        }
        $result .= '.';
        $this->messages[] = $result;
    } else {
        $this->messages[] = 'Could not upload ' . $file['name'];
    }
}

【问题讨论】:

  • 您的代码容易受到 SQL 注入的攻击。请阅读有关在 MySQLi 中使用准备好的语句的信息。
  • 失败时返回什么错误?
  • 只有屏幕上新文件名的回显响应,我检查了数据库并且没有条目
  • 我现在已经解决了您发现的安全问题。

标签: php file upload


【解决方案1】:

根据documentation 创建连接的人:

$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'my_db');

你确定你的论点顺序正确吗?

那么官方检查连接状态的方法是:

if ($mysqli->connect_error) {
    die('Connect Error (' . $mysqli->connect_errno . ') '
            . $mysqli->connect_error);
}

【讨论】:

  • 感谢您的评论,不幸的是,在这样做之后它似乎仍然不起作用,我已经处理了 SQL 注入的问题,现在已经使用声明的变量将值传递到数据库连接中。跨度>
  • 我说的是参数的顺序——在你的示例代码中 DBNAME 是第二个参数,而它应该是最后一个——你检查了吗?剧本现在说了什么?是否成功通过die('Connect Error...
  • 感谢 Picard,代码现在如下所示,
  • 对不起,堆栈系统的新手,请参阅下面的条目。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-27
  • 1970-01-01
  • 1970-01-01
  • 2016-04-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多