2012-09-01 126 views
0

我創建了一個函數,它不起作用。在盯着它15分鐘嘗試不同的方式後,我無法實現它的工作。任何人都可以告訴我我的語法有什麼問題嗎?變量$user_id是一個數字,$input是一個字符串。我知道,mysql已被棄用,這是我正在處理的事情。我只想知道sql有什麼問題,因爲畢竟它是一個sql問題。語法問題與SQL語句

function insert_what_i_do($user_id, $input) 
{ 
    if (mysql_result(mysql_query("SELECT `user_id` FROM `profile` WHERE `user_id` = $user_id"), 0) !== 1) 
    { 
     mysql_query("INSERT INTO `profile` (user_id, what_i_do) VALUES ($user_id, '$input')");  
    } 
    else 
    { 
     mysql_query("UPDATE `profile` SET `what_i_do` = '$input' WHERE `user_id` = $user_id"); 
    } 
}; 
+0

請,不要使用'mysql_ *'函數來獲取新代碼。他們不再被維護,社區已經開始[棄用流程](http://goo.gl/KJveJ)。請參閱[**紅框**](http://goo.gl/GPmFd)?相反,您應該瞭解[準備好的語句](http://goo.gl/vn8zQ)並使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli的)。如果你不能決定,[本文](http://goo.gl/3gqF9)將有助於選擇。如果你關心學習,[這是一本很好的PDO教程](http://goo.gl/vFWnC)。 – PeeHaa

+1

當你說*不工作*你是什麼意思?任何錯誤? – Fluffeh

+0

那麼你得到的錯誤是什麼?它是SELECT,INSERT還是UPDATE? – andrewsi

回答

6

這是用普通MySQL,請取我做什麼有一個良好的外觀,這是不建議再使用mysql_*功能,因爲它們已被棄用。注意引用$input

<?php 
    function insert_what_i_do($user_id, $input) { 
     $input = mysql_real_escape_string($input); 
     $query = mysql_query("SELECT `user_id` FROM `profile` WHERE `user_id` = '".(int)$user_id."'"); 
     $num = mysql_num_rows($query); 
     if($num) { 
      $query = mysql_query("UPDATE `profile` SET `what_i_do` = '".$input."' WHERE `user_id` = '".(int)$user_id."'"); 
     } else { 
      $query = mysql_query("INSERT INTO `profile` (`user_id`, `what_i_do`) VALUES ('".(int)$user_id."', '".$input."')"); 
     } 
    } 
?> 

你需要學會使用PDO:

<?php 
    $db = new PDO('mysql:host=localhost;dbname=testdb;charset=UTF-8', 'username', 'password', array(PDO::ATTR_EMULATE_PREPARES => false, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION)); 
    function insert_what_i_do($user_id, $input) { 
     global $db; 
     $stmt = $db->query("SELECT `user_id` FROM `profile` WHERE `user_id` = :user_id"); 
     $stmt->execute(array(':user_id' => $user_id)); 
     $num = $stmt->rowCount(); 
     if($num) { 
      $stmt = $db->query("UPDATE `profile` SET `what_i_do` = :input WHERE `user_id` = :user_id"); 
      $stmt->execute(array(':user_id' => $user_id, ':input' => $input)); 
     } else { 
      $stmt = $db->query("INSERT INTO `profile` (`user_id`, `what_i_do`) VALUES (:user_id, :input)"); 
      $stmt->execute(array(':user_id' => $user_id, ':input' => $input)); 
     } 
    } 
?> 
+0

我知道'real_escape_string'問題並計​​劃通過mysqli預處理語句和參數化查詢來解決此問題。我只想首先找出sql代碼有什麼問題。 – jason328

1

你似乎已經錯過了在更新查詢單引號$input

mysql_query("UPDATE `profile` SET `what_i_do` = '$input' WHERE `user_id` = $user_id"); 

但我也不能看到你的任何地方使得的mysql連接。

+0

Mysql連接是在別處進行的。我已經將問題縮小到了功能上。另外,添加單引號仍然不起作用。 – jason328

3

解決PHP的問題後,請注意什麼您正在嘗試在3個MySQL查詢/報表做,可以在一個完成 - 假設user_id是主要或唯一鍵:

INSERT INTO profile 
    (user_id, what_i_do) 
VALUES 
    ('$user_id', '$input') 
ON DUPLICATE KEY UPDATE 
    what_i_do = VALUES(what_i_do) ;