首先,使用
require("db-connect.php");
代替
include("db-connect.php");
现在,考虑使用准备好的语句,您的代码容易受到 sql 注入的影响。
考虑使用 PDO 代替 mysql 语法,从长远来看,我发现它更好用并且避免了很多无意义的问题,你可以这样做(你可以将它保存在 db-connect 文件中如果您愿意,甚至可以使数据库连接成为全局):
// 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 = '';
现在您可以通过以下方式访问您的数据库
$db = connectToDatabase($host, $databaseName, $user, $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% 确定它们是否有效。
您可以轻松地创建另一个插入到 tha 数据库中的函数,而不是更新它,或者将其保留在同一个函数中;如果您发现该条目存在,则插入它,否则更新它。