繁体   English   中英

将图像保存在服务器中,并链接到数据库PHP Data Objecta PDO OOP中

[英]Save image in Server and link in database PHP Data Objecta PDO OOP

我已定制MVC。 我正在使用PDO。 我想将图像保存在服务器中并保存到数据库的链接。

public function add(){
    // Sanitize POST
    $post = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

    if($post['submit']){
        if($post['title'] == '' || $post['body'] == '' || $post['link'] == ''){
            Messages::setMsg('Please Fill In All Fields', 'error');
            return;
        }

        $images=$_FILES['upic']['name'];
    $tmp_dir=$_FILES['upic']['tmp_name'];
    $imageSize=$_FILES['upic']['size'];

    $upload_dir='uploads/';
    $imgExt=strtolower(pathinfo($images,PATHINFO_EXTENSION));
    $valid_extensions=array('jpeg', 'jpg', 'png', 'gif', 'pdf');
    $picProfile=rand(1000, 1000000).".".$imgExt;
    move_uploaded_file($tmp_dir, $upload_dir.$picProfile);

        // Insert into MySQL
        $this->query('INSERT INTO shares (title, body, link, user_id, upic) VALUES(:title, :body, :link, :user_id, :upic)');
        $this->bind(':title', $post['title']);
        $this->bind(':body', $post['body']);
        $this->bind(':link', $post['link']);

        $this->bind(':user_id', 1);
        $this->bind(':upic', $post['upic']);
        $this->execute();
        // Verify
        if($this->lastInsertId()){
            // Redirect
            header('Location: '.ROOT_URL.'shares');
        }
    }
    return;
}

使用此代码图像可以保存在服务器中,但是数据库中什么也没有。 当我删除图像插入代码时,所有其他数据存储都很好。 如何在服务器中上传图像并将链接保存在数据库表中?

我收到以下错误

注意:未定义的索引:第36行的C:\\ xampp \\ htdocs \\ test3 \\ models \\ share.php中的upic

您在这里做错了。 你可以试试看。

    $dbhost = "localhost";
    $dbname = "mypdo";
    $dbusername = "root";
    $dbpassword = "123456";

    $link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);

    $statement = $link->prepare("INSERT INTO shares (title, body, link, user_id, upic) VALUES(:title, :body, :link, :user_id, :upic)");

    $statement->execute(array(
        "title" => $post['title'],
        "body" => $post['body'],
        "link" => $post['link'],
        "user_id" => 1,
        "upic" => $upload_dir.$picProfile,
    ));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM