2016-02-20 112 views
-1

我一直在瀏覽一些計算器和其他頁面,現在嘗試了不同的方法。但似乎沒有任何工作。PHP MySQL:檢查值是否已經存在

我有一個代碼,收集表單的輸入並將其張貼到數據庫中。那是有效的。但在發佈之前,如果字段「shortlink」已經存在,我希望它能夠發揮作用。如果是這樣,我希望用戶被重定向到另一個頁面。

這是我現在正在嘗試的代碼。

編輯:全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"); 
} 

忽略了最低的工作。儘管短鏈接已經存在,表單仍然會插入到數據庫中。

+2

該代碼沒有插入到數據庫中。我認爲我們需要更多的代碼。還要檢查你的變量是你使用var_dump的想法。並在你的'header'調用後添加一個'exit()',而不是完全需要的,但是通常可以防止頭疼 – dan08

+0

你可以使用'if(mysqli_num_rows($ checkUserID)> 0)'來檢查這個查詢是否返回任何行 –

+1

'$ db - > select()'函數可以。更重要的是它返回了什麼,因爲我猜測它是**而不是你認爲的**! – RiggsFolly

回答

1

按照大於0 documentationmysqli::query成功SELECT查詢返回一個mysqli_result對象。要從中提取一個對象或數組,您應該調用列出的函數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); 
} 
+0

感謝您的迴應!即使當我發佈uniqe短鏈接時,這也會給我「錯誤」消息... – marwej

+0

這意味着查詢執行期間發生錯誤。我已更新代碼以輸出適當的錯誤消息。它應該解釋發生了什麼。 – max

+0

好的。現在它說:「你的SQL語法有錯誤;檢查對應於你的MySQL服務器版本的手冊,在第1行'1'附近使用正確的語法」 – marwej

-1

你需要找到如果任何結果存在於數據庫中,以便儘量

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

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

這給出了一個錯誤消息「致命的錯誤:調用未定義的方法Db :: num_rows()在C:\ wamp \ www \ webo \ admin \ index.php上106行」 – marwej

+0

嘗試'$ checkUserID-> rowCount()'而不是 –

+0

更新回答嘗試 –

0

所以你select方法的返回類型是一個數組,但你比較它與一個字符串。所以這總是錯誤的。檢查數組不爲空,以確定是否存在條目

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

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

// OR查詢的長度是

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

感謝您的答覆。試了兩次,但沒有重定向。相反,表單被髮布到數據庫中... – marwej

+0

您需要自己做一些基本的故障排除。添加'echo's。 'var_dump's和'print_r's來檢查你的變量。 – dan08