我有定制的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
答案 0 :(得分:0)
你这里做错了。你可以试试这个。
$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,
));