Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用PHP读取JSON数组_Php_Mysql_Json - Fatal编程技术网

用PHP读取JSON数组

用PHP读取JSON数组,php,mysql,json,Php,Mysql,Json,我编写了一个简单的php脚本,它将接收一个JSON数组(我认为是这样),并将接收到的数组添加到MySQL数据库中。但是,当我调用脚本时,它只将数组中的最后一项添加到数据库中。这里有没有我遗漏的简单的东西 此外,我的TRUNCATE表无法从表中删除任何内容 <?php $handle = mysql_connect('localhost','root',''); if($handle==false) { die('No database connection'); } $res

我编写了一个简单的php脚本,它将接收一个JSON数组(我认为是这样),并将接收到的数组添加到MySQL数据库中。但是,当我调用脚本时,它只将数组中的最后一项添加到数据库中。这里有没有我遗漏的简单的东西

此外,我的TRUNCATE表无法从表中删除任何内容

<?php 
$handle = mysql_connect('localhost','root',''); 
if($handle==false) 
{ 
die('No database connection'); 
} 

$result = mysql_query("TRUNCATE TABLE 'available_ingredients'");


$db=mysql_select_db('r2bar2'); 
$query='INSERT INTO available_ingredients (drink_name) VALUES ("'.$_POST["drink_name"].'")'; 
$result=mysql_query($query); 
?>

编辑: 下面是生成JSON数组的代码

ArrayList<NameValuePair> j2 = new ArrayList<NameValuePair>();
j2.add("drink_name", "rootbeer")
j2.add("drink_name", "pepsi")

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(my url);
httppost.setEntity(new UrlEncodedFormEntity(j2));
HttpResponse response = httpclient.execute(httppost);
responseText = EntityUtils.toString(response.getEntity())
ArrayList j2=新的ArrayList();
j2.添加(“饮料名称”、“根啤酒”)
j2.添加(“饮料名称”、“百事可乐”)
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(我的url);
setEntity(新的UrlEncodedFormEntity(j2));
HttpResponse response=httpclient.execute(httppost);
responseText=EntityUtils.toString(response.getEntity())
  • TRUNCATE TABLE
    不需要或不希望在表名周围加单引号
  • 您没有向我们显示
    $\u POST
    确切包含的内容,因此我们无法确切说明发生了什么
  • 代码将用户提供的数据嵌入到SQL中而不进行清理,因此容易受到SQL注入的攻击

您应该养成检查调用函数的所有返回值是否有错误的习惯(就像您已经在使用
mysql\u connect
时所做的那样);这将导致您发现截断表立即失败的原因。

使用json_decode查看PHP如何接收json对象。在Android端,您可能只需要创建一个变量来发送json数据

i、 e.data=“…此处是json字符串…”(伪代码,因为我不确定您在android中是如何操作的。其想法是您将向PHP发送1个键/值,其中键为数据,值为json字符串中的所有值。)

然后在PHP中,如果您通过POST发送,则可以得到如下结果:

注意,删除truncate表查询,正如其他人提到的,它正在擦除整个表

这段代码应该回答您的主要问题

<?php
// decode json string
$data = json_decode($_POST['data']);

// sanitize your input to avoid sql injection like others have mentioned
$safe_drink_name = mysql_real_escape_string($data->drink_name);

.... // your mysql connect code

$query='INSERT INTO available_ingredients (drink_name) VALUES ("'.$safe_drink_name.'")'; 
?>


非常容易受到SQL注入攻击。您的TRUNCATE查询不正确。使用`(backtick)而不是“(单引号)引用您的MySQL表和列名。您从何处获取JSON?它是使用httppost从Android应用程序发送的。您试图保存的JSON是否存储在
$\u POST[“drink\u name”]
中?