页数功能

时间:2016-11-08 11:21:47

标签: javascript php mysql html5

每次访问我的索引页面时,我都需要检查数据库中是否已存在记录,如果存在,则需要更新字段'count',否则会添加一行。

我设法让它在访问时创建一行,但如果行已经存在,似乎无法更新计数。

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// Check to see if record exists
$sql = "SELECT * FROM page_tracking where name ="index.php"";
if (mysqli_query ($conn, $sql)) {
	$sql= "UPDATE page_tracking SET count=count+1 where name= "index.php")";
}

else if {
//Insert Query
$sql = "INSERT INTO page_tracking (name, count)
VALUES ('index.php', '1')"; 
}
if (mysqli_query($conn, $sql)) {
    echo "Thanks for visiting! Your visit has been recorded";
} else {
    echo "Unfortunately we were unable to record your visit: " . $sql . "<br>" . mysqli_error($conn);
}

可能有一个非常简单的解释!问题肯定是'检查记录是否存在'的代码

4 个答案:

答案 0 :(得分:0)

在您的代码中,您从未执行过查询。只在字符串中创建它。

if (mysqli_query ($conn, $sql)) {
    $sql= "UPDATE page_tracking SET count=count+1 where name= "index.php")";
    # execute the query
}

另外,不确定为什么这个松散else if没有条件:

else if {
    //Insert Query

您可能想要查看INSERT ... ON DUPLICATE KEY UPDATE语句,如果文件名是您的唯一键,则可以将整个代码减少为单个查询:

mysqli_query ($conn, "
    INSERT INTO page_tracking (name, count)
         VALUES ('index.php', 1)
    ON DUPLICATE KEY UPDATE count=count+1
");

答案 1 :(得分:0)

1)不要在index.php周围使用double quotes使用single quotes。 只需运行更新查询

    $sql = "SELECT * FROM page_tracking where name ="index.php"";
    $result =  mysqli_query ($conn, $sql);
    $num_rows = mysqli_num_rows($result);
    if ($num_rows) {
        $sql= "UPDATE page_tracking SET count=count+1 where name= 'index.php'";

    }else{
    $sql = "INSERT INTO page_tracking (name, count) VALUES ('index.php', '1')"; 
}

if (mysqli_query($conn, $sql)) {
    echo "Thanks for visiting! Your visit has been recorded";
} else {
    echo "Unfortunately we were unable to record your visit: " . $sql . "<br>" . mysqli_error($conn);
}

答案 2 :(得分:0)

获取结果并检查其是否有记录。

  // Check to see if record exists
    $sql = "SELECT * FROM page_tracking where name ="index.php"";
    $query = mysqli_query ($conn, $sql);

    $result=mysqli_fetch_all($query,MYSQLI_ASSOC);
    if (count($result) > 0) {
        $sql= "UPDATE page_tracking SET count=count+1 where name="index.php")";
    }

    else {
    //Insert Query
    $sql = "INSERT INTO page_tracking (name, count)
    VALUES ('index.php', '1')"; 
    }

答案 3 :(得分:0)

请试试这个。使用单引号而不是双引号。

$link = mysql_connect("localhost", $mysql_user, $mysql_password);
mysql_select_db($database, $link);

$result = mysql_query("SELECT * FROM page_tracking where name ='index.php'", $link);
$num_rows = mysql_num_rows($result);

if($num_rows==1){
  //Update Query
}else{
  //Insert Query
}