简体   繁体   中英

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

I have custom made MVC. I am using PDO. I want to save image in server and save link to database.

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;
}

With thiscode image is saving in the server but I am getting nothing in database. when I remove image insertion code all the other data stores fine. How Can I upload image in server and save link in database table?

I get the following error

Notice: Undefined index: upic in C:\\xampp\\htdocs\\test3\\models\\share.php on line 36

You are doing wrong here. You can try this .

    $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,
    ));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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