douluo6626 2010-05-26 21:30
浏览 139
已采纳

PHP / mysqli:使用mysqli_stmt_bind_param()插入IP地址

I have a database table which contains an unsigned integer field to store the visitor's IP address:

`user_ip` INT(10) UNSIGNED DEFAULT NULL,

Here's the snippet of PHP code which tries to store the IP address:

$ipaddr = $_SERVER['REMOTE_ADDR'];
if ($stmt = mysqli_prepare($dbconn, 'INSERT INTO visitors(user_email, user_ip) VALUES (?,?)'))
{
    $remote_ip = "INET_ATON('$ipaddr')";
    mysqli_stmt_bind_param($stmt, 'ss', $email, $remote_ip);
    if (mysqli_stmt_execute($stmt) === FALSE) return FALSE;
    $rows_affected = mysqli_stmt_affected_rows($stmt);
    mysqli_stmt_close($stmt);
}

The INSERT operation succeeds, however the user_ip field contains a null value. I have also tried changing the parameter type in mysqli_stmt_bind_param() (which was set to string in the above example) to integer, i.e. mysqli_bind_param(... 'si',...) - but to no avail.

I've also tried using the following bit of code instead of mysql's INET_ATON() SQL function:

function IP_ATON($ipaddr)
{
    $trio = intval(substr($ipaddr,0,3));
    return ($trio>127) ? ((ip2long($ipaddr) & 0x7FFFFFFF) + 0x80000000) : ip2long($ipaddr);
}

It still doesn't work - the 'user_ip' field is still set to null. I've tried passing the $ip_addr variable as both integer & string in mysqli_bind_param() - to no avail.

It seems the problem lies with the parameterized insert.

The following "old-style" code works without any problem:

mysqli_query(..., "INSERT INTO visitors(user_email, user_ip) VALUES ('$email',INET_ATON('$ipaddr'))");

What am I doing wrong here?

Thanks in advance!

  • 写回答

2条回答 默认 最新

  • douduandiao1368 2010-05-26 21:33
    关注

    I think it should look like this:

    $ipaddr = $_SERVER['REMOTE_ADDR'];
    if ($stmt = mysqli_prepare($dbconn, 'INSERT INTO visitors(user_email, user_ip) VALUES (?, INET_ATON(?))'))
    {
        mysqli_stmt_bind_param($stmt, 'ss', $email, $ipaddr);
        if (mysqli_stmt_execute($stmt) === FALSE) return FALSE;
        $rows_affected = mysqli_stmt_affected_rows($stmt);
        mysqli_stmt_close($stmt);
    }
    

    Note the change by the second ? and what parameters are sent into mysqli_stmt_bind_param.

    Since the parameters you pass into mysqli_stmt_bind_param should be the actual values to be inserted, and not any functions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置
  • ¥15 Matlab怎么求解含参的二重积分?
  • ¥15 苹果手机突然连不上wifi了?