dsg435665475 2016-02-20 17:45
浏览 44
已采纳

PHP MySQL:检查值是否已存在

I've been surfing around stackoverflow and other pages for a while now and tried different approaches to this. But nothing seems to work.

I have a code which collect the inputs from a form and posts it into a database. And that works. But before it posts, i want it to chek if the field "shortlink" already exist. And if it does, i want the user to be redirected to another page.

This is the code i'm trying out right now.

EDIT: Full PHP code

    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");
}

It dosen't work. The form is postet into the database despite shortlink already exists.

  • 写回答

3条回答 默认 最新

  • douyan8772 2016-02-20 18:17
    关注

    As per documentation, mysqli::query for successful SELECT queries returns a mysqli_result object. To extract an object or array from it you should call one of the fetch_* functions listed here. But you just need to check if there any record exists so it's preferrable to use $num_rows property. So your code would look like:

    $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);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)
  • ¥20 怎么在stm32门禁成品上增加查询记录功能
  • ¥15 Source insight编写代码后使用CCS5.2版本import之后,代码跳到注释行里面
  • ¥50 NT4.0系统 STOP:0X0000007B
  • ¥15 想问一下stata17中这段代码哪里有问题呀