【问题标题】:Problems passing variable to private class in PHP在 PHP 中将变量传递给私有类的问题
【发布时间】:2015-01-01 00:44:12
【问题描述】:

我正在处理的脚本处理表单数据:3 个文本字段和两个文件上传(一个是图像,另一个是 pdf 文档)。该脚本已成功将两个文件保存并命名到服务器,并将 3 个文本字段保存到 sql db。但是,图像和文档的 url 没有保存到 sql。

脚本使用两个 sql statememtns:第一个用于文本字段,第二个用于文件 url。第一个 sql 在我的 CropAvatar 类之外执行。我的理性是传递第一个sql执行后获得的var $id(sql中的自动增量),然后将其传递给第二个语句。我想我是通过在构造函数中定义 $id 并在第二个 sql 语句中使用它来实现的。

没有成功,第二条sql语句似乎没有执行。关于如何获取提交给 sql 的这两个文件的 URL 的任何建议?或者这里有什么调试建议?

我不高兴我在这里发布了 150 多行代码,我只是不知道哪里出了问题。我仍在尝试正确使用这些私有函数,我有一种感觉,我的错误被包含在其中的某个地方。提前感谢您的任何建议。

    <?php
$title = $_POST['title'];
$titlee = mysql_real_escape_string($title);
$address = $_POST['address'];
$addresse = mysql_real_escape_string($address);
$sale_price = $_POST['sale_price'];
    $sale_pricee= mysql_real_escape_string($sale_price);
require('../dbcon.php');
$sql="INSERT INTO listings (title, comment,transaction, date_added) VALUES ('$titlee', '$addresse, '$sale_pricee, now())";
mysqli_query($con,$sql);
$id = mysqli_insert_id();
    class CropAvatar {
        private $src;
        private $data;
        private $file;
        private $dst;
        private $type;
        private $extension;
        private $srcDir = '../0images/listimg/orig';
        private $dstDir = '../0images/listimg/mod';
        private $msg;
function __construct($src, $data, $file, $id) {
    $this -> setSrc($src);
    $this -> setId($id);
    $this -> setData($data);
    $this -> setFile($file);
    $this -> crop($this -> src, $this -> dst, $this -> data);
}
        private $id;
        public function setId($id) {
                 $this->id = $id;
}
        private function setSrc($src) {
            if (!empty($src)) {
                $type = exif_imagetype($src);
                if ($type) {
                    $this -> src = $src;
                    $this -> type = $type;
                    $this -> extension = image_type_to_extension($type);
                    $this -> setDst();
                }
            }
        }
        private function setData($data) {
            if (!empty($data)) {
                $this -> data = json_decode(stripslashes($data));
            }
        }
        private function setFile($file) {
            $errorCode = $file['error'];
            if ($errorCode === UPLOAD_ERR_OK) {
                $type = exif_imagetype($file['tmp_name']);

                if ($type) {
                    $dir = $this -> srcDir;

                    if (!file_exists($dir)) {
                        mkdir($dir, 0777);
                    }
$currdate=date('YmdHis');
                    $extension = image_type_to_extension($type);
                    $src = $dir . '/' . $currdate . $extension;
                    if ($type == IMAGETYPE_GIF || $type == IMAGETYPE_JPEG || $type == IMAGETYPE_PNG) {

                        if (file_exists($src)) {
                            unlink($src);
                        }
                        $result = move_uploaded_file($file['tmp_name'], $src);
$listing_img="http://www.website.com/0images/listimg/mod/" . $currdate . $extension;
$allowedExtsf = array("pdf");
$tempf = explode(".", $_FILES["flyer"]["name"]);
$extensionf = end($tempf);

if (($_FILES["flyer"]["type"] == "application/pdf")
&& ($_FILES["flyer"]["type"] <2000000000)
&& in_array($extensionf, $allowedExtsf)) 
{
    $flyername=$_FILES["flyer"]["name"];

    if ($_FILES["flyer"]["error"] > 0) 
    {
    echo "Return Code: " . $_FILES["flyer"]["error"] . "<br>";
    }   
        else 
        {
            if (file_exists("../flyers/" . $_FILES["flyer"]["name"])) 
            {
             echo $_FILES["flyer"]["name"] . " already exists. ";
            }
                else 
                {
                move_uploaded_file($_FILES["flyer"]["tmp_name"],"../flyers/" . $_FILES["flyer"]["name"]);
                 }
        }
      $ad_link="http://www.website.com/flyers/" . $_FILES["flyer"]["name"];
      require('../dbcon.php');
$sql="update listings SET ad_link='$ad_link', listing_img='$listing_img' WHERE id=$ID";
mysqli_query($con,$sql);
mysqli_close($con);
}
                        if ($result) {
                            $this -> src = $src;
                            $this -> type = $type;
                            $this -> extension = $extension;
                            $this -> setDst();
                        } else {
                             $this -> msg = 'Failed to save file';
                        }
                    } else {
                        $this -> msg = 'Please upload image with the following types: JPG, PNG, GIF';
                    }
                } else {
                    $this -> msg = 'Please upload image file';
                }
            } else {
                $this -> msg = $this -> codeToMessage($errorCode);
            }
        }

        private function setDst() {
            $dir = $this -> dstDir;

            if (!file_exists($dir)) {
                mkdir($dir, 0777);
            }
            $this -> dst = $dir . '/' . date('YmdHis') . $this -> extension;
        }
        private function crop($src, $dst, $data) {
            if (!empty($src) && !empty($dst) && !empty($data)) {
                switch ($this -> type) {
                    case IMAGETYPE_GIF:
                        $src_img = imagecreatefromgif($src);
                        break;
                    case IMAGETYPE_JPEG:
                        $src_img = imagecreatefromjpeg($src);
                        break;
                    case IMAGETYPE_PNG:
                        $src_img = imagecreatefrompng($src);
                        break;
                }
                if (!$src_img) {
                    $this -> msg = "Failed to read the image file";
                    return;
                }
                $dst_img = imagecreatetruecolor(220, 220);
                $result = imagecopyresampled($dst_img, $src_img, 0, 0, $data -> x, $data -> y, 220, 220, $data -> width, $data -> height);
                if ($result) {
                    switch ($this -> type) {
                        case IMAGETYPE_GIF:
                            $result = imagegif($dst_img, $dst);
                            break;

                        case IMAGETYPE_JPEG:
                            $result = imagejpeg($dst_img, $dst);
                            break;

                        case IMAGETYPE_PNG:
                            $result = imagepng($dst_img, $dst);
                            break;
                    }

                    if (!$result) {
                        $this -> msg = "Failed to save the cropped image file";
                    }
                } else {
                    $this -> msg = "Failed to crop the image file";
                }
                imagedestroy($src_img);
                imagedestroy($dst_img);
            }
        }

        private function codeToMessage($code) {
            switch ($code) {
                case UPLOAD_ERR_INI_SIZE:
                    $message = 'The uploaded file exceeds the upload_max_filesize directive in php.ini';
                    break;               
                default:
                    $message = 'Unknown upload error';
            }
            return $message;
        }
        public function getResult() {
            return !empty($this -> data) ? $this -> dst : $this -> src;
        }
        public function getMsg() {
            return $this -> msg;
        }
    }
$crop = new CropAvatar($_POST['avatar_src'], $_POST['avatar_data'], $_FILES['avatar_file'], $id);
    $response = array(
        'state'  => 200,
        'message' => $crop -> getMsg(),
        'result' => $crop -> getResult()
    );
    echo json_encode($response);
?>

【问题讨论】:

  • 警告:当使用mysqli 时,您应该使用参数化查询和bind_param 将用户数据添加到您的查询中。 请勿使用字符串插值来完成此操作,因为您将创建严重的SQL injection bugs
  • 调查一下谢谢@tadman
  • 你的整个代码都不好。你不应该仅仅因为使用类。一个类包装某些功能并将其隔离。然后开发人员使用该类(以及它的public 方法)来执行特定 的工作。你正在混合一切。您也不知道访问控制对方法的作用。你在这 150 行左右所做的就是将过程代码包装到一个几乎不可用的类中。我建议您使用 PDO 进行数据库访问并废弃此代码并重新开始。这个想法是让代码更容易阅读和维护。并不难。
  • @N.B.日子不好过

标签: php mysql private public


【解决方案1】:

我浏览了您的代码,您可能应该打印您的查询以确保,但在:

$sql="update listings SET ad_link='$ad_link', listing_img='$listing_img' WHERE id=$ID";

我看不到变量 $ID 的来源,因此更新将不起作用。 您可以而且应该使用mysqli_error,这样下次您更容易找到您的 sql 错误。

希望能解决。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-20
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 2016-07-03
    • 1970-01-01
    • 1970-01-01
    • 2020-01-24
    相关资源
    最近更新 更多