2014-03-29 61 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 = ...'行後。 –