如何在表中插入IP地址?

时间:2019-05-20 19:49:42

标签: php sql

我是php的初学者,这是我在学校学习Web开发的第一门课程。 我也是这个网站的新手,但我会尽力以“正确的方式”提出问题。对于我在学校的项目,我已经创建了一个网站,并且我还需要一个管理页面,用于跟踪用户/访问者。到目前为止,我有一些代码,但是我还需要将用户/访问者的IP地址也添加到表中。这是我的代码,除ip地址外,所有内容都添加到数据库表中。该表是users4project,列是IP地址,带有int(10)UNSIGNED NOT NULL我在phpmyadmin中创建了该表。

<?php
function visitor($record) {
    // my database info
    $db_host = "";
    $db_username = ""; 
    $db_password = "";
    $db_name = "";
    $db_table = "ipusers4project";
    $counter_page = "access_page";
    $counter_field = "access_counter";

    $db = mysqli_connect ($db_host, $db_username, $db_password, $db_name) 
        or die("Host or database not accessible");

    $sql_call = "INSERT INTO ".$db_table." (".$counter_page.", 
        ".$counter_field.") VALUES ('".$record."', 1) ON DUPLICATE KEY UPDATE ".$counter_field." = ".$counter_field." + 1";
    mysqli_query($db, $sql_call) or die("Error while entering");

    $sql_call = "SELECT ".$counter_field. " FROM ".$db_table." WHERE ".$counter_page. " = '".$record. "'";
    $sql_result = mysqli_query($db, $sql_call) or die("SQL request failed ");
    $row = mysqli_fetch_assoc($sql_result);
    $x = $row[$counter_field];

    mysqli_close($db);
    return $x;
}
?>
<?php
$ipadress = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO
    ipusers4project
    ( ipadress )
    VALUES
    ( '$ipadress')";
?>

编辑:在index.php上,我有以下代码:

<?php
$page_name = "index.php";
?>
<title><?php echo $page_name; ?></title>
<?php
include "webcounter.php";
$access_number = visitor($page_name);

?>

1 个答案:

答案 0 :(得分:1)

只需将其添加为visitor()要添加的行中的另一列。

<?php
function visitor($record) {
    // my database info
    $db_host = "";
    $db_username = ""; 
    $db_password = "";
    $db_name = "";
    $db_table = "ipusers4project";
    $counter_page = "access_page";
    $counter_field = "access_counter";
    $ipadress = $_SERVER['REMOTE_ADDR'];

    $db = mysqli_connect ($db_host, $db_username, $db_password, $db_name) 
        or die("Host or database not accessible");

    $sql_call = "INSERT INTO ".$db_table." (".$counter_page.", 
        ".$counter_field.", ipadress) VALUES ('".$record."', 1, '$ipadress') ON DUPLICATE KEY UPDATE ".$counter_field." = ".$counter_field." + 1, ipadress = VALUES(ipadress)";
    mysqli_query($db, $sql_call) or die("Error while entering");

    $sql_call = "SELECT ".$counter_field. " FROM ".$db_table." WHERE ".$counter_page. " = '".$record. "'";
    $sql_result = mysqli_query($db, $sql_call) or die("SQL request failed ");
    $row = mysqli_fetch_assoc($sql_result);
    $x = $row[$counter_field];

    mysqli_close($db);
    return $x;
}
?>