duanduo0520 2016-07-11 20:41
浏览 166
已采纳

PHP Prepared-Statement:绑定变量参数

I have a problem with a varchar in my database that only displays 0 instead of the in the past written text. I have a URL that contains some parameters like nickname, points or the difficulty of the game.

localhost/api.php?nickname=test&points=5&difficulty=3

These parameters gets an api (see the code below) and write them into the database.

<?php
$nickname = $_GET['nickname'];
$points = $_GET['points'];
$difficulty = $_GET['difficulty'];

$mysqli = new mysqli("localhost", "games", "123", "tictactoe");

if ($mysqli->connect_errno) {
    die("Error");
}

/* Prepared statement, stage 1: prepare */
$sql ="insert into highscores (nickname, points, difficulty) values (?, ?, ?)";
if (!($stmt = $mysqli->prepare($sql))) {
    die("Error");
}

/* Prepared statement, stage 2: bind and execute */
if (!$stmt->bind_param("isi", $nickname, $points, $difficulty)) {
    die("Error");
}

if (!$stmt->execute()) {
    die("Error");
}
mysqli_close($mysqli);
?>

But my problem is: Why does all varchars in the database have the value 0 if the api bind the parameters with a String that is like "test" ?

id  nickname  points  difficulty
1      0        5         3
2      0        5         3
3      0        5         3
4      0        5         3
5      0        5         3
6      0        5         3
7      0        5         3

The database structure:

Column       Type         Null     Standard   Comments
id          int(11)       No         
nickname    varchar(20)   No             
points      int(11)       No         
difficulty  tinyint(4)    No         

I hope you can understand my problem and can help me :)

  • 写回答

2条回答 默认 最新

  • dongxie3352 2016-07-11 20:44
    关注

    Your binding is inverted.

    $stmt->bind_param("isi", $nickname, $points, $difficulty)
    

    says that $nickname and $difficulty are integers. Your DB has nickname as varchar though.

    It should be:

    $stmt->bind_param("sii", $nickname, $points, $difficulty)
    

    You can see it documented here.

    Character   Description
    i           corresponding variable has type integer
    d           corresponding variable has type double
    s           corresponding variable has type string
    b           corresponding variable is a blob and will be sent in packets
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历