更新并插入mysqli表

时间:2013-12-27 18:48:22

标签: php mysql mysqli

我正在尝试检查leaguename名称是否已存在,如果确实存在,则检查它是否高于现有分数。如果它更高,则替换quizscore否则将leaguenamequizscore插入表league_quiz。

代码似乎在我的表中插入了值,但是如果名称等于previous并且分数更高,它似乎不会更新?

我收到此错误:

  

警告:mysqli_num_rows()期望参数1为mysqli_result,字符串在

中给出

我的代码:

<?php

$name = (string)$_POST['name'];
$score = (string) $_POST['score'];

$link = mysqli_connect("mysql12.gigahost.dk","username","password","dirts_mysql");

$query = "SELECT leaguename, quizscore FROM league_quiz WHERE  leaguename = '$name' AND quizscore < '$score'";

if(mysqli_num_rows($query)) {
    mysqli_query($link,"UPDATE league_quiz SET quizscore = '$score'");
} else {
    mysqli_query($link,"INSERT INTO league_quiz (leaguename, quizscore) VALUES ('$name', '$score')") or die(mysqli_error($link));
}

?>

3 个答案:

答案 0 :(得分:0)

在这两者之间:

$query = "SELECT leaguename, quizscore FROM league_quiz WHERE  leaguename = '$name' AND      quizscore < '$score'";

if(mysqli_num_rows($query)) {

您是否尝试过编写此代码?

$result = mysqli_query($query);

然后对查询结果使用mysqli_num_rows?

答案 1 :(得分:0)

mysqli_num_rows需要查询结果,而不是查询本身的字符串。 首先,您必须执行查询:

$result = mysqli_query($link,$query);

然后你可以计算行数

$numRows = mysqli_num_rows($result);

答案 2 :(得分:0)

尝试以下方法:

$result = mysqli_query($query);
if (mysqli_num_rows($result)) {
...