PHP MySQL:检查值是否已存在

时间:2016-02-20 17:45:36

标签: php mysql

我一直在浏览stackoverflow和其他页面一段时间,并尝试了不同的方法。但似乎没有任何效果。

我有一个代码,它从表单中收集输入并将其发布到数据库中。这很有效。但在它发布之前,如果字段“短链接”已经存在,我希望它发痒。如果确实如此,我希望将用户重定向到另一个页面。

这是我现在正在尝试的代码。

编辑:完整的PHP代码

    class Db {
        // The database connection
        protected static $connection;

        /**
         * Connect to the database
         * 
         * @return bool false on failure / mysqli MySQLi object instance on success
         */
        public function connect() {    
            // Try and connect to the database
            if(!isset(self::$connection)) {
                // Load configuration as an array. Use the actual location of your configuration file
                $config = parse_ini_file('../config.ini'); 
                self::$connection = new mysqli('localhost',$config['username'],$config['password'],$config['dbname']);
            }

            // If connection was not successful, handle the error
            if(self::$connection === false) {
                // Handle error - notify administrator, log to a file, show an error screen, etc.
                return false;
            }
            return self::$connection;
        }

        /**
         * Query the database
         *
         * @param $query The query string
         * @return mixed The result of the mysqli::query() function
         */
        public function query($query) {
            // Connect to the database
            $connection = $this -> connect();

            // Query the database
            $result = $connection -> query($query);

            return $result;
        }

        /**
         * Fetch rows from the database (SELECT query)
         *
         * @param $query The query string
         * @return bool False on failure / array Database rows on success
         */
        public function select($query) {
            $rows = array();
            $result = $this -> query($query);
            if($result === false) {
                return false;
            }
            while ($row = $result -> fetch_assoc()) {
                $rows[] = $row;
            }
            return $rows;
        }

        /**
         * Fetch the last error from the database
         * 
         * @return string Database error message
         */
        public function error() {
            $connection = $this -> connect();
            return $connection -> error;
        }

        /**
         * Quote and escape value for use in a database query
         *
         * @param string $value The value to be quoted and escaped
         * @return string The quoted and escaped string
         */
        public function quote($value) {
            $connection = $this -> connect();
            return "'" . $connection -> real_escape_string($value) . "'";
        }
    }


    if ($_SERVER['REQUEST_METHOD'] == 'POST') {

    //Our database object
    $db = new Db();    

    // Quote and escape form submitted values

    $name = $db -> quote($_POST["name"]);
    $shortlink = $db -> quote($_POST["shortlink"]);
    $downloadurl = $db -> quote($_POST["downloadurl"]);
    $count = $db -> quote("0");
    $date = $db -> quote(date("Y-m-d H:i:s"));

$checkUserID = $db -> select("SELECT shortlink FROM test WHERE `shortlink` = '$shortlink'");

if ($checkUserID->rowCount()){
    header("Location: error.php?title=hovsa");
}


    // Insert the values into the database
    $result = $db -> query("INSERT INTO `test` (`name`,`shortlink`,`downloadurl`,`count`,`date`) VALUES (" . $name . "," . $shortlink . "," . $downloadurl . "," . $count . "," . $date . ")");

    //Upload image file
    if (isset($_POST['submit']))
    {
        $filename = $_FILES["file"]["name"];
        $file_basename = substr($filename, 0, strripos($filename, '.')); // get file extention
        $file_ext = substr($filename, strripos($filename, '.')); // get file name
        $filesize = $_FILES["file"]["size"];
        $allowed_file_types = array('.jpg','.jpeg');    

        if (in_array($file_ext,$allowed_file_types) && ($filesize < 20000000000))
        {   
            // Rename file
            $newfilename = $_POST['shortlink'] . $file_ext;
            if (file_exists("../gallery/" . $newfilename))
            {
                // file already exists error
                echo "You have already uploaded this file.";
            }
            else
            {       
                move_uploaded_file($_FILES["file"]["tmp_name"], "../gallery/" . $newfilename);
                echo "File uploaded successfully.";     
            }
        }
        elseif (empty($file_basename))
        {   
            // file selection error
            echo "Please select a file to upload.";
        } 
        elseif ($filesize > 20000000000)
        {   
            // file size error
            echo "The file you are trying to upload is too large.";
        }
        else
        {
            // file type error
            echo "Only these file typs are allowed for upload: " . implode(', ',$allowed_file_types);
            unlink($_FILES["file"]["tmp_name"]);
        }
    }
    header("Location: #users");
    }
        else{}; 
$checkUserID = $db -> select("SELECT shortlink FROM test WHERE `shortlink` = '$shortlink'");

if ($checkUserID == $shortlink) {
    header("Location: error.php?title=hovsa");
}

它不起作用。尽管已经存在短链接,但表格仍然存在于数据库中。

3 个答案:

答案 0 :(得分:1)

根据documentationmysqli::query成功进行SELECT查询会返回mysqli_result个对象。要从中提取对象或数组,您应该调用列出的fetch_*函数之一here。但是您只需要检查是否存在任何记录,因此最好使用$num_rows属性。所以你的代码看起来像是:

$checkUserID = $db -> query("SELECT shortlink FROM test WHERE `shortlink` = $shortlink");

if ($checkUserID === false) {
    die($db->error());
}

if ($checkUserID->num_rows) {
   header("Location: error.php?title=hovsa");
   exit(0);
}

答案 1 :(得分:0)

因此select方法的返回类型是一个数组,但是您将它与字符串进行比较。所以这总是错误的。检查数组是否为空以确定条目是否存在

$checkUserID = $db -> select("SELECT shortlink FROM test WHERE `shortlink` = '$shortlink'");

if ( !empty($checkUserID) ) {
   header("Location: error.php?title=hovsa");
}

//或检查长度是否大于0

if ( count($checkUserID) > 0 ) {
   header("Location: error.php?title=hovsa");
}

答案 2 :(得分:-1)

您需要查找数据库中是否存在任何结果,请尝试

$checkUserID= $db -> select("SELECT shortlink FROM test WHERE `shortlink` = '$shortlink'");

if ($checkUserID->rowCount()) { 
    header("Location: error.php?title=hovsa");
}