Php 如何将图像插入数据库?
我创建CMS,我想在数据库中插入一个图像。当我单击“提交”按钮时,程序会将标题、内容插入数据库,但不会插入图像。在注册之前,程序会在数据库中插入一个图像。我不知道为什么我不知道。我可能会犯一些文字错误,但我找不到Php 如何将图像插入数据库?,php,mysql,Php,Mysql,我创建CMS,我想在数据库中插入一个图像。当我单击“提交”按钮时,程序会将标题、内容插入数据库,但不会插入图像。在注册之前,程序会在数据库中插入一个图像。我不知道为什么我不知道。我可能会犯一些文字错误,但我找不到 require_once('database.php'); 类dodawanie扩展了数据库 { 私有$errors=''; 私人$img; 公共函数get_image() { 返回$this->img; } 公共功能集图像($img) { $this->img=$img; } 公共
require_once('database.php');
类dodawanie扩展了数据库
{
私有$errors='';
私人$img;
公共函数get_image()
{
返回$this->img;
}
公共功能集图像($img)
{
$this->img=$img;
}
公共职能插入()
{
$field1=$this->get_title();
$field2=$this->get_content();
$field3=$this->get_image();
$field4=日期('Y-m-d H:i:s');
if(空($this->errors))
{
$sql=“插入wiadomosci(`tytul`、`news`、`zdjecie`、`data_dodania`)值(''$field1'、'$field2'、'$field3'、'$field4')”);
$result=$this->connect()->query($sql);
}
}
如果(isset($_POST['submit']))
{
$add=新的dodawanie();
$fault3=$add->set_image($_POST['avatar']);
echo$abc3=$add->get_image();
$inser=$add->insert();
首先要在MySQL中插入图像,我们必须在数据库中创建一个表
运行MYSQL命令
CREATE TABLE `image` (
`image` LONGBLOB NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
然后,如果index.php包含允许用户选择要上载的图像文件的HTML表单,请将其插入其中
<!DOCTYPE html>
<html>
<head>
<title>Insert Image in MySql using PHP</title>
</head>
<body>
<?php
$msg = '';
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_FILES['image']['tmp_name'];
$img = file_get_contents($image);
$con = mysqli_connect('localhost','root','','admin') or die('Unable To connect');
$sql = "insert into images (image) values(?)";
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt, "s",$img);
mysqli_stmt_execute($stmt);
$check = mysqli_stmt_affected_rows($stmt);
if($check==1){
$msg = 'Image Successfullly UPloaded';
}else{
$msg = 'Error uploading image';
}
mysqli_close($con);
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<button>Upload</button>
</form>
<?php
echo $msg;
?>
</body>
</html>
save as index.php and run
使用PHP在MySql中插入图像
上传
另存为index.php并运行