php - 使用 mySQL 和 php 处理 JSON 数据

标签 php mysql json

在过去的两天里,我一直在互联网上寻找如何处理以 json 形式存储在 mySQL 数据库中的数据。我发现的只是这里的一篇文章,但我没有成功。所以这是我的问题

这是我的表,称为附加表,仅包含 2 列...作业和成本。 jobid 是一个长度为 5 的 int,显然是主键,cost 简单地存储为文本。我将所有成本合并在一列下的原因是因为我的应用程序中的用户可以将他/她想要的任何内容放在那里,所以对我来说成本是未知的。例如,一个条目可能是

24321 , {"电话": "$20"} 或者 24322 , {"电话": "$20", "酒店": "$400"}

诸如此类,但我希望你明白这一点。

现在给出这个例子,我需要知道如何使用 php 处理以 json 形式存储的数据库中的数据输入和输出。因此,插入、选择和更新,但我认为通过一个给定的示例,如果有人可以帮助我了解如何处理数据库中的 json 数据进出,我可以完成其余的工作。

哦,还有最后一件事。我不仅需要知道如何获取数据,我还需要能够将其分离,例如:

$cost1 = {"telephone" : "$20"};
$cost2 = {"hotel" : "$400"};

我真的希望有人可以帮助解决这个问题,因为就像我上面所说的,我花了两天时间试图解决这个问题,但要么没有关于此事的文章(除了这个网站上的文章),要么与我的示例完全无关

最佳答案

您将其标记为 PHP,以便可以使用 PHP 函数:json_encode 和 json_decode。

例如,当您读取(SELECT)并在与主键 24322 相对应的字符串中获取此成本值时:

//after you query db and got the cost in string...
$sql = "SELECT * FROM additional"; 
$result = mysqli_query($conn,$sql); $row = mysqli_fetch_array($result);
//from your comment below.... just changed to $cost so I don't have to change everything here...
$cost = $row['costs'];
//$cost = '{"telephone" : "$20", "hotel" : "$400"}'
//you just have to:
$cost = json_decode($cost); 
// result in an object which you can manipulate such as:
print_r($cost->telephone);
// $20 or:
print_r($cost->hotel);
//$400;
//or if you want to go through all of the costs... you change that to array:
$cost = (array)$cost; //or on your json_decode you add a TRUE param... ie(json_decode($cost, TRUE))...
print_r($cost);
//will produce an associative array: ['telephone'=>'$20', 'hotel'=>'$400']
//for which you can do a foreach if you want to go through each value...

另一方面,当您使用对象保存到数据库时:

$cost = (object)['hotel'=>'$300', 'taxi'=>'$14'];
//you json_encode this so you can write to db:
$cost = json_encode($cost);
//a string... you can then use $cost to write to db with (insert, update, etc)

注意:json_decode 需要输入字符串为 UTF-8 编码。所以你可能需要强制你的 mysql 服务器提供 UTF-8。一些阅读:https://www.toptal.com/php/a-utf-8-primer-for-php-and-mysql

希望这有帮助...

关于php - 使用 mySQL 和 php 处理 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40360090/

相关文章:

javascript - 我们如何禁用输入类型 ="date"中的 dd-mm-yyyy 字段,以便仅接受选定的日期

MySQL 通过创建更多列而不是行来连接表

MYSQL根据年龄选择生日

MySQL 连接与通配符(任何)用户和主机发生冲突

ios - RestKit:发送特定的 JSON,请帮忙,我已经尝试了我能想到的一切

php - 如何使用 jwt-auth 对 Facebook 用户进行身份验证?

php - 如何有效地使用多个 OR 语句

java - 如何从java中的列表中获取Jsonobject?

json - 是否可以在浏览器的url地址栏中传递json格式? (获取方法)

php - 获取文件上传后在服务器上的客户端路径