【问题标题】:PHP Prepared-Statement: binding variable parametersPHP Prepared-Statement:绑定变量参数
【发布时间】:2016-07-11 20:41:02
【问题描述】:

我的数据库中有一个 varchar 问题,它只显示 0 而不是过去的书面文本。我有一个包含昵称、分数或游戏难度等参数的 URL。

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

这些参数获取一个api(见下面的代码)并写入数据库。

<?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);
?>

但我的问题是:如果 api 将参数与类似 "test" 的字符串绑定,为什么数据库中的所有 varchar 都具有值 0

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

数据库结构:

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

希望你能理解我的问题并帮助我:)

【问题讨论】:

  • 你为什么在bind_param中使用isi?来自the manual“i 对应的变量具有整数类型”。你刚刚“告诉”mysqli 你想为nickname 发送一个整数...
  • 应该是sii,而不是isi。您指定的昵称是一个 int。

标签: php database api mysqli prepared-statement


【解决方案1】:

你的绑定被反转了。

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

$nickname$difficulty 是整数。不过,您的数据库有 nicknamevarchar

应该是:

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

你可以看到它记录在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

【讨论】:

  • 是的,或者不清楚它做了什么。希望写出来会有所帮助。
  • 感谢您的解决方案。这对我来说非常有效。
【解决方案2】:

问题出在 bind_parm 中。您正在使用“i”,它是整数。您必须使用“s”,这是您所需要的。

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 

【讨论】:

  • 感谢您提供的文档。这对我的其他用途很有帮助。
猜你喜欢
  • 2015-10-04
  • 1970-01-01
  • 1970-01-01
  • 2017-11-15
  • 1970-01-01
  • 2020-02-05
  • 2018-10-10
  • 1970-01-01
  • 2011-10-21
相关资源
最近更新 更多