我正在尝试从我的Android应用程序中获取一个字符串用户名,并使用该用户名为该特定用户帐户添加5个点。
Example:
My database now: user_id name username password points
1 test test test 0
What I want: user_id name username password points
1 test test test 5
这是我正在使用的PHP代码,它必定是错误的:
<?php
$con = mysqli_connect("localhost", "id177667_root", "***", "id177667_loginb");
$username = $_POST["username"];
$sql = "UPDATE user ". "SET points = points + 5 ". "WHERE username = $username" ;
$response = mysqli_query($sql, $con);
?>
答案 0 :(得分:3)
你混淆了mysqli_query的参数。它应该是mysqli_query($con, $sql);
。还有一些其他问题 - 这应该有效:
<?php
$con = mysqli_connect("localhost", "id177667_root", "***", "id177667_loginb");
$username = mysqli_real_escape_string($con, $_POST["username"]);
$sql = "UPDATE user SET points = points + 5 WHERE username = '$username'" ;
$response = mysqli_query($con, $sql);
?>
正如所建议的那样,准备好的陈述是首选方式。所以你可以这样做...现在测试它,它适用于我:
<?php
$points = 5;
// Connect to database (credentials should not be stored in code...)
$con = new mysqli("localhost", "id177667_root", "***", "id177667_loginb");
// Check if connection succeeded
if ($con->connect_error)
die("Connection error: " . $con->connect_error);
// Prepare statement
if ($st = $con->prepare("UPDATE user SET points = points + ? WHERE username = ?")) {
// Bind parameters (i for integer value, s for string)
$st->bind_param("is", $points, $_POST["username"]);
// Execute statement
$st->execute();
// Close statement
$st->close();
} else {
// Prepare failed: report error
die("Prepare failed: " . $con->error);
}
// Close DB connection
$con->close();
?>