1

I'm trying to find a person in my table and update their score. This is the code I have right now. For some reason it's not working. Instead of changing the person's score, it will just make a new row with the same name of the person.

$name = $_POST["strtolower(name)"];
$team = $_POST["team"];
$num = $_POST["number"];
$goals = $_POST["goals"];

if($query = mysqli_query("SELECT goals FROM goalscorers WHERE name=$name ", $db)){
  while($row = mysqli_fetch_assoc($query)){
    $origgoals = $row['goals'];
    $newgoals = (int)$origgoals + (int)$goals;
    mysqli_query($db, "UPDATE goalscorers SET goals=$newgoals WHERE name=$name ");
    echo "<h1>Thank you for submitting your details! <br /> <a href=\"goalscorers.php\">Add another</a></h1>";
  }
  mysqli_free_result($query);
}
else {
    $query = "INSERT INTO goalscorers (name, team, num, goals) VALUES ('$name','$team','$num','$goals') ";
    $result = mysqli_query($query, $db);
    if (mysqli_error()) { print "Database ERROR: " . mysql_error(); } 

    echo "<h1>Thank you for submitting your details! <br /> <a href=\"goalscorers.php\">Add another</a></h1>";
}

I'm very new to both PHP and MySQL so it's probably a basic mistake.

Also, I already am connected to the database.

4

1 回答 1

1

您的直接问题是您的 sql 查询中的字符串值没有引号。改变

"SELECT goals FROM goalscorers WHERE name=$name "

"SELECT goals FROM goalscorers WHERE name = '$name'"
                                            ^     ^

"UPDATE goalscorers SET goals=$newgoals WHERE name=$name "

"UPDATE goalscorers SET goals=$newgoals WHERE name = '$name'"
                                                     ^     ^

附带说明:学习和使用准备好的语句。您的代码容易受到 sql 注入的影响。


UPDATE1:您可以使用INSERT ... ON DUPLICATE KEY UPDATE. 为了使其正常工作,您必须在name列上有一个 UNIQUE (PRIMARY KEY) 索引。你的插入语句应该看起来像

INSERT INTO goalscorers (`name`, `team`, `num`, `goals`)
VALUES (?, ?, ?, ?)
ON DUPLICATE KEY UPDATE goals = goals + VALUES(goals)

这是SQLFiddle演示


UPDATE2:现在你的代码INSERT ... ON DUPLICATE KEY UPDATE和准备好的语句看起来像这样

$name  = $_POST['name'];
$team  = $_POST['team'];
$num   = $_POST['number'];
$goals = $_POST['goals'];

/* connect to the database*/
$db = new mysqli('localhost', 'user', 'userpwd', 'test');
/* check connection */
if ($db->connect_errno) {
    die('Connection failed: ' .$db->connect_error);
}

$sql = 'INSERT INTO goalscorers (`name`, `team`, `num`, `goals`)
        VALUES (?, ?, ?, ?)
        ON DUPLICATE KEY UPDATE goals = goals + VALUES(goals)';
/* create a prepared statement */
if ($stmt = $db->prepare($sql)) {
    /* bind parameters for markers */
    $stmt->bind_param("ssii", $name, $team, $num, $goals);
    /* execute query */
    if ($stmt->execute()) {
        echo '<h1>Thank you for submitting your details! <br /> <a href="goalscorers.php">Add another</a></h1>';
    } else {
        die('Insert failed: ' .$db->error);    
    }
    /* close statement */
    $stmt->close();
} else {
    die('Statement prepare failed: ' .$db->error);    
}
于 2013-07-01T03:08:25.337 回答