我试图用PHP来查询我的数据库。我已经完成所有设置并且它会响应请求,问题是它只返回ID,而不是我要求的语句。 这是我得到的回应:
{"jagharaldrig":[{"id":"1","statement":null},{"id":"2","statement":null},{"id":"3","statement":null},{"id":"4","statement":null}]}
这是我用来查询我的数据库的PHP脚本:
<?php
/*
* Script to get jagharaldrig.
* @author Simon Cedergren
*/
#Connect to Database
$con = mysqli_connect("<host>", "<user>", "<password>", "<database>");
#Check connection
if (mysqli_connect_errno()) {
echo 'Database connection error: ' . mysqli_connect_error();
exit();
}
#Ensure that the client has provided a value for "type"
if (isset($_POST["type"])){
#Setup variables
$user_id = $_POST["user_id"];
$type = $_POST["type"];
$index = $_POST["index"];
$user_id = mysqli_real_escape_string($user_id);
$type = mysqli_real_escape_string($type);
$index = mysqli_real_escape_string($index);
$data = mysqli_query($con, "SELECT * FROM jagharaldrig") or die(mysql_error());
#If no data was returned, check for any SQL errors
if ($data) {
$result_data = array();
$i=0;
while($row = mysqli_fetch_array($data)){
$result_data[$i++] = array(
'id' => $row[0],
'statement' => $row[1]
);
}
}
#Output the JSON data
echo json_encode(array('jagharaldrig' => $result_data));
}else{
echo "Could not complete query. Missing parameter";
}
?>
这就是我的桌子的样子,以及它里面的内容。它只是初步设置的查询草案。这很基础。
MariaDB [onyktert]> SELECT * FROM jagharaldrig;
+----+-----------------------------------+
| id | statement |
+----+-----------------------------------+
| 1 | Jag har aldrig spelat schack! |
| 2 | Jag har aldrig ätit choklad! |
| 3 | Jag har aldrig varit kär! |
| 4 | Jag har aldrig åkt skridskor! |
+----+-----------------------------------+
4 rows in set (0.00 sec)
MariaDB [onyktert]> DESCRIBE jagharaldrig;
+-----------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| statement | varchar(500) | YES | | NULL | |
+-----------+--------------+------+-----+---------+----------------+
我在PHP脚本中遗漏了什么或是某种错误?我已尝试仅使用
查询语句SELECT statement FROM jagharaldrig;
然后返回&#34; null&#34;。
的4个条目答案 0 :(得分:1)
似乎你从数据库返回utf-8 characters
。
成功打开连接后,可以使用mysqli_set_charset将字符集设置为utf8。
mysqli_set_charset($con, "utf8");
此行中也有错误。
$data = mysqli_query($con, "SELECT * FROM jagharaldrig") or die(mysql_error());
将mysql_error
替换为mysqli_error($con)
,因为您使用的是mysqli_*
个功能。
$data = mysqli_query($con, "SELECT * FROM jagharaldrig") or die(mysqli_error($con));