简体   繁体   English

在表行中查找一个值,如果有,则对其进行更新

[英]Find a value in a table row, and if it is there, update it

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. 我对PHP和MySQL都是新手,所以这可能是一个基本错误。

Also, I already am connected to the database. 另外,我已经连接到数据库了。

Your immediate problem is that you don't have quotes around string values in your sql queries. 您的直接问题是您的sql查询中没有字符串值的引号。 Change 更改

"SELECT goals FROM goalscorers WHERE name=$name "

to

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

and

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

to

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

On a side note: learn and use prepared statements . 附带说明:学习和使用准备好的语句 Your code is vulnerable to sql injections. 您的代码容易受到sql注入的攻击。


UPDATE1: You can drastically simplify your code with INSERT ... ON DUPLICATE KEY UPDATE . UPDATE1:您可以使用INSERT ... ON DUPLICATE KEY UPDATE大大简化代码。 In order for it to work properly you have to have a UNIQUE (PRIMARY KEY) index on name column. 为了使其正常工作,您必须在name列上具有一个唯一(主键)索引。 Your insert statement then should look like 您的插入语句应如下所示

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

Here is SQLFiddle demo 这是SQLFiddle演示


UPDATE2: Now your code with INSERT ... ON DUPLICATE KEY UPDATE and prepared statement can look like this 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);    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM