这是 plain MySQL
,请仔细看看我在那里做了什么,不建议再使用mysql_*
function ,因为它们已被弃用。注意引用的$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));
}
}
?>