首先,使用替代
require("db-connect.php");
include("db-connect.php");
而現在,考慮使用準備好的語句,你的代碼很容易受到SQL注入。
考慮使用PDO而不是mysql語法,從長遠來看,我發現它使用起來好多了,它避免了很多無意義的問題,你可以這樣做(你可以把它保留在如果你想DB-連接文件,甚至使數據庫conncetion成爲全球性的):
// Usage: $db = connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword);
// Pre: $dbHost is the database hostname,
// $dbName is the name of the database itself,
// $dbUsername is the username to access the database,
// $dbPassword is the password for the user of the database.
// Post: $db is an PDO connection to the database, based on the input parameters.
function connectToDatabase($dbHost, $dbName, $dbUsername, $dbPassword)
{
try
{
return new PDO("mysql:host=$dbHost;dbname=$dbName;charset=UTF-8", $dbUsername, $dbPassword);
}
catch(PDOException $PDOexception)
{
exit("<p>An error ocurred: Can't connect to database. </p><p>More preciesly: ". $PDOexception->getMessage(). "</p>");
}
}
然後初始化變量:
$host = 'localhost';
$user = 'root';
$databaseName = 'databaseName';
$pass = '';
現在,你可以通過
訪問數據庫現在
,這裏是你如何能夠解決您的問題(使用預處理語句,避免SQL注入):
function userId($db, $user_username)
{
$query = "SELECT * FROM members WHERE username = :username;";
$statement = $db->prepare($query); // Prepare the query.
$statement->execute(array(
':username' => $user_username
));
$result = $statement->fetch(PDO::FETCH_ASSOC);
if($result)
{
return $result['user_id'];
}
return false
}
function updateProfile($db, $userId, $name, $location, $about)
{
$query = "UPDATE profile_members SET name = :name, location = :location, about = :about WHERE id = :userId;";
$statement = $db->prepare($query); // Prepare the query.
$result = $statement->execute(array(
':userId' => $userId,
':name' => $name,
':location' => $location,
':about' => $about
));
if($result)
{
return true;
}
return false
}
$userId = userId($db, $user_username); // Consider if it is not false.
$name = $_REQUEST["name"];
$location = $_REQUEST["location"];
$about = $_REQUEST["about"];
$updated = updateProfile($db, $userId, $name, $location, $about);
您應該檢查查詢,雖然,我固定的他們一點點,但不是100%肯定,如果他們工作。
您可以輕鬆地進行其插入到塔數據庫,而不是更新它,或保持它在同功能的其他功能;如果你發現有條目存在,那麼你插入它,否則你更新它。
返回什麼值?錯誤是什麼? – sachleen 2013-03-22 20:30:30
您是否在數據庫端驗證了它? – Kermit 2013-03-22 20:31:32
它不運行更新到數據庫中並返回受影響的行 – user2200771 2013-03-22 20:32:11