使用PHP将图像上传到MySQL数据库的问题

时间:2016-11-27 13:08:37

标签: php mysql

我有这个PHP代码将图像上传到数据库,我有问题 用它而我不知道它是什么,数据库表名是 图片和字段为idname VARCHAR()photo LONGBLOB

<?php
ini_set('display_errors', '1');
$servername = "";
$username = "";
$password = "";
//$host = "";

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";
?>
<html>
<body>
    <form method="post" enctype="multipart/form-data">
        <input type="file" name="image"/>
        </br>
        </br>
        </br>
        <input type="submit" name="go" value="Upload"/>
    </form>
    <?php
        if(isset($_POST['go'])){
            if(getimagesize($_FILES['image']['tmp_name']) == FALSE){
                echo "Select a photo please";
            }else {
                $image = addslashes($_FILES['image']['tmp_name']);
                $name = addslashes($_FILES['image']['name']);
                $image = file_get_contents($image);
                $image = base64_encode($image);
                save_image($image , $name);
            }
        }
        function save_image($image , $name){
            $servername = "localhost";
            $username = "cl60-shooters";
            $password = "dbsjcNs-b";
            $conn = new mysqli($servername, $username, $password);
            $qry = "insert into images (photo , name) VALUES ('$image','$name')";
            $result = mysqli_query($conn,$qry);

            if($result){
                echo "Successfull upload";
            }else{
                echo "try Again";
                print_r($result);
            }



        }

        ?>
</body>
</html>

结果如附图截图所示: Result

2 个答案:

答案 0 :(得分:0)

您的功能忽略了提及数据库 - 您需要将其作为参数之一提供,例如:

var webPage = require('webpage');

webPage.create().open('http://example.com', function (status) {
  var base64 = page.renderBase64('PNG');
  console.log(base64);
  phantom.exit();
});

FYI表示您的代码容易受到SQL注入攻击 - 最好使用预处理语句!

答案 1 :(得分:0)

您未在mysqli构造函数中使用数据库名称。它应该如下:

$servername = "localhost";
$username = "cl60-shooters";
$password = "dbsjcNs-b";
$database = "database_name_here";
$conn = new mysqli($servername, $username, $password, $database);

希望它现在能够奏效。