2014-03-29 57 views
1

如何获取字符串输出?当我尝试解码时发生了一个错误。我想在文本框中插入输出值。如何解码并从json获取字符串值

怎么办?

$array=json_decode($json); 
echo $array; 

**Warning:** 
json_decode() expects parameter 1 to be string, array given in C:\xampp\htdocs\school\vijay\update.php on line 20 

我的PHP

<?php 
$json = array(); 
$con=mysql_connect("localhost","school","certify"); 

$db_select = mysql_select_db('School_Data', $con); 
$childid = $_GET['childid']; 
$result = mysql_query("SELECT * FROM childinfo where ChildID='$childid'",$con); 
while($r = mysql_fetch_assoc($result)) { 
    $json[] = $r; 
} 
if($result){ 
echo json_encode($json); 
} 
else 
    { 
     echo mysql_error(); 
    } 

//$obj = unserialize($json); 
$arrayOfEmails=json_decode($json); 
echo $arrayOfEmails; 

mysql_close($con); 
?> 

我的JSON输出

[{ 
    "ID": "1", 
    "ChildID": "1001", 
    "ParentID": "2002", 
    "SiblingsID": "hfh", 
    "TeacherID": "hfhf", 
    "ChildName": "fhfh", 
    "DOB": "2014-03-04", 
    "Age": "0", 
    "Gender": "male", 
    "Grade": "KG1", 
    "Section": "KG1", 
    "Stream": "NORMAL", 
    "BloodGroup": "O-", 
    "Nationality": "KG1", 
    "Country": "Lebanon", 
    "Religion": "KG1", 
    "MotherTongue": "KG1", 
    "FirstLanguage": "bfbf", 
    "SecondLanguage": "fbfbfb", 
    "PlaceOfBirth": "fhfh", 
    "LandlineNumber": "0", 
    "EmailID": "[email protected]", 
    "ChildPhoto": "Requirement.PNG", 
    "TemporaryAddress": "bfdbd", 
    "PermanentAddress": "bdbdbf", 
    "Mentor": "fbbfd", 
    "DateOfJoin": "2014-03-06", 
    "JoinGrade": "J", 
    "ReferredBy": "bdbf", 
    "ContactNumber": "0", 
    "EmergencyContactNumber": "0" 
}] 
+0

'$ arrayOfEmails'是一个对象,你不能直接'echo'出来。 –

+0

[**请不要在新代码中使用'mysql_ *'函数**](http://bit.ly/phpmsql)。他们不再被维护[并且被正式弃用](http://j.mp/XqV7Lp)。学习[*准备的语句*](http://j.mp/T9hLWi),并使用[PDO](http://php.net/pdo)或[MySQLi](http://php.net/ mysqli) - [这篇文章](http://j.mp/QEx8IB)将帮助你决定哪个。如果你选择PDO,[这里是一个很好的教程](http://j.mp/PoWehJ)。 –

+0

然后我怎样才能得到文本框中的各自输出 – user3317807

回答

0

保存JSON进行编码阵列后恢复。

未经测试的代码

<?php 
$json = array(); 
$con=mysql_connect("localhost","school","certify"); 

$db_select = mysql_select_db('School_Data', $con); 
$childid = $_GET['childid']; 
$result = mysql_query("SELECT * FROM childinfo where ChildID='$childid'",$con); 
while($r = mysql_fetch_assoc($result)) { 
    $json[] = $r; 
} 
if($result){ 
$encodedJson = json_encode($json); // save json string for later 
echo $encodedJson; 
} 
else 
    { 
     echo mysql_error(); 
    } 

//$obj = unserialize($json); 
$arrayOfEmails = json_decode($encodedJson); // convert back to an array 
var_dump($arrayOfEmails); 

mysql_close($con); 
?> 
+0

我可以从你的代码中获取json的值,在相应的html字段中显示这些值 – user3317807

+0

我可以得到values.but我需要以各自的html形式显示这些值 – user3317807

0

这是一个完全不同的野兽回答问题全问。而不是我最初计划的工作(大约5个小时)。它仍然很好地工作,即时通讯。

我已将其转换为PDO。即使是'mysqli'也是我想要的更多限制。

目的:从数据库中选择孩子的详细信息。显示包含所有细节的表单。验证输入 - 好,检查丢失的输入。显示单个错误消息。玩一玩吧。

它需要版本5.3'因为我使用'关闭'在它。如果需要,可以更改该功能。请让我知道。

测试:PHP 5.3.18中,MySQL 5.5的Windows XP(OI,停止laffin')

<?php // Q22732117 

/* 
* As i provide the database code you will have to change your current code to 
* either 'mysqli' or 'PDO'. 
* 
* 'cos the update statements are easier with PDO that is what i shall use!' 
* 
* needs PHP version 5.3 or greater 
* 
* contact me if you are on an earlier version 
*/ 

/* 
* database connection... 
*/ 
$myDatabaseName = 'School_Data'; 
$username = 'school'; 
$password = 'certify'; 

$dsn = "mysql:host=localhost;dbname={$myDatabaseName}"; 
$options = array( PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'); 
$theDB = new PDO($dsn, $username, $password, $options); 
$theDB->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

/* 
* get the child info into the 'currentChildInfo' array no need to use JSON... 
*/ 
$childid = !empty($_GET['childid']) ? $_GET['childid'] : ''; 

/* 
* get child details 
*/ 
$sql = "SELECT * FROM childinfo where ChildID = :childid"; 

$query = $theDB->prepare($sql); 

$query->execute(array(':childid' => $childid)); 

$resultSet = $query->fetchAll(PDO::FETCH_ASSOC); 
if (empty($resultSet)) { 
    die("One of our children ($childid) is missing!"); 
} 

/* 
* current child info for use throughout the script 
* 
* We need to keep a copy of this so we can check which fields are being updated. 
*/ 
$originalChildInfo = current($resultSet); 
$currentChildInfo = current($resultSet); 

/* 
* these data items will be hidden fields on the form 
*/ 
$hiddenFields = array(
    "ID", "ChildID", "ParentID", "SiblingsID", "TeacherID" 
    ); 


// ------------------------- 
$allInformationIsCorrect = true; // need this to halt script correctly 

if (!empty($_POST['goForIt'])) { // process the input... 

    $errorMsgs = array(); // hold individual error messages in here 
          // so you can display them in the HTML later! 

    /* 
    * transfer the $_POST data to the array... 
    */ 
    foreach($_POST['childInfo'] as $itemName => $itemValue) { 
     $currentChildInfo[$itemName] = $itemValue; 
    } 

    /* 
    * Validate all the input 
    */ 
    foreach($currentChildInfo as $itemName => $itemValue) { 

     // ignore hidden fields... 
     if (in_array($itemName, $hiddenFields)) { 
      continue; // ignore and do nest one 
     } 

     // check for missing data 
     if (empty($currentChildInfo[$itemName])) { 
      $errorMsgs[$itemName] = 'Oi! you missed some!!!'; 
      continue; 
     } 

     // extra validation here... 

    } 
    $allInformationIsCorrect = empty($errorMsgs); // any errors? 

    /* 
    * update the database? 
    */ 
    if ($allInformationIsCorrect) { // update the database 

     /* 
     * get list of columns to update 
     */ 
     $updateColumns = array_uintersect_assoc($currentChildInfo, 
               $originalChildInfo, 
               function ($value1, $value2) { 
                if ($value1 === $value2) { 
                 return 1; 
                } 
                else { 
                 return 0; 
                } 
               }); 

     $sqlColumns = ''; 
     $boundValues = array(); 

     foreach($updateColumns as $itemName => $itemValue) { 
      // ignore hidden fields... 
      if (in_array($itemName, $hiddenFields)) { 
       continue; // ignore and do next one 
      } 

      $_colName = '`'. $itemName .'`'; 
      $_bindName = ':'. $itemName .''; 

      $sqlColumns .= "$_colName = $_bindName,"; 

      $boundValues[$_bindName] = $itemValue; 
     } 
     $sqlColumns = rtrim($sqlColumns, ', '); // lose trailing comma 


     // generate the sql 'where' clause 
     $sqlWhere = " where `ChildID` = :ChildID"; 
     $boundValues[':ChildID'] = $currentChildInfo['ChildID']; 

     try { 
      if (!empty($sqlColumns)) { // skip if nothing changed 
       $sql = "update childinfo set " 
         . $sqlColumns 
         . $sqlWhere; 
       $query = $theDB->prepare($sql); 
       $allOk = $query->execute($boundValues); 
      } 
     } 
     catch (\Exception $e) { 
      echo 'drat! '. $e->getMessage(); 
      // throw $e; // re-raise the exception 
     } 
    } 
} 

// if all ok then leave else show the form for corrections 
if (!empty($_POST['goForIt']) && $allInformationIsCorrect) { 
    echo 'all done, we are going home! <br />'; 
    exit; 
} 

?> 
<!DOCTYPE html> 
<html> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
    <title>Amend Child Information.</title> 
    <style type="text/css"> 
     .item { 
      margin: 2px; 
      border: 1px wheat dotted; 
     } 
    .item-name { 
     display: inline-block; 
     width: 25%; 
     text-align: right; 
     margin: 2px; 
     padding-right: 3px; 
     border-top: 1px #adadad dotted; 
     background-color: wheat ; 
    } 
    .item-value { 
     display: inline-block; 
     width: 35%; 
     text-align: left; 
     background-color: wheat; 
    } 
    .item-error { 
     display: inline-block; 
     width: 38%; 
     text-align: left; 
     background-color: #eea236; 
    } 
    </style> 
</head> 

    <body> 
    <h2>Child data</h2> 

    <form action="" method="post"> 
     <fieldset > 
      <legend>Current Child Information</legend> 
     <?php foreach($currentChildInfo as $itemName => $itemValue): ?> 
      <?php $isHidden = false; // need this to sort out whether to print a closing 'div' '?> 
      <?php if (in_array($itemName, $hiddenFields)): // create a hidden field ?> 
       <input type="hidden" name="childInfo[<?= $itemName ?>]" value="<?= $itemValue ?>"> 
       <?php $isHidden = true; ?> 
      <?php else: ?> 
       <div class="item"> 
        <label for="<?= $itemName ?>" class="item-name" id="<?= $itemName ?>"><?= trim($itemName), '&nbsp:' ?></label> 
        <input type="text" name="childInfo[<?= $itemName ?>]" id="<?= $itemName ?>" 
          value="<?= $itemValue ?>" 
          class="item-value"> 
      <?php endif; ?> 

      <?php if (!empty($errorMsgs[$itemName]) && !$isHidden): // show the error message ?> 
       <div class="item-error"> 
        <?= $errorMsgs[$itemName] ?> 
       </div> 
       </div> <!-- close item div --> 

      <?php elseif (!$isHidden): ?> 
       </div> <!-- close item div --> 

      <?php endif; ?> 
     <?php endforeach; ?> 
    <input type="submit" name="goForIt" value="Go For It!"> 
    </form> 
    </body> 
</html> 
+0

我得到:我们的一个孩子()缺少!什么是显示它的公文 – user3317807

+0

看看错误信息来自哪里。没有从查询返回的行。或者您没有将小孩传递给脚本,或者未在数据库中找到childid。随意以任何您想要的方式编辑脚本。代码不是完整的。现在是**你的**代码。做你想做的事。更改所有的错误消息等我会帮你修复你发现的错误。它不按你想要的方式工作不是一个错误。 :-)我会尽力帮助你按照你想要的方式工作。 –

+0

这里是一个关于'mysqli'的教程,足以解释它。我用了'准备好的陈述'的东西。 ** ['MySQLi'初学者](http://codular.com/php-mysqli)**。如果您想查看update语句中生成的SQL,只需添加:var_dump($ sql); '$ allOk = ...'行后。 –