簡體   English   中英

PHP Prepared-Statement:綁定變量參數

[英]PHP Prepared-Statement: binding variable parameters

我的數據庫中的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"的String綁定參數,為什么數據庫中的所有varchars都具有值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         

我希望你能理解我的問題,可以幫助我:)

您的綁定被反轉。

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

$nickname$difficulty是整數。 您的數據庫的nicknamevarchar

它應該是:

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

你可以在這里看到它。

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

問題出在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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM