我如何从json解码并获取字符串值

时间:2014-03-29 14:08:28

标签: php html 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": "dgdgd@gg.c",
    "ChildPhoto": "Requirement.PNG",
    "TemporaryAddress": "bfdbd",
    "PermanentAddress": "bdbdbf",
    "Mentor": "fbbfd",
    "DateOfJoin": "2014-03-06",
    "JoinGrade": "J",
    "ReferredBy": "bdbf",
    "ContactNumber": "0",
    "EmergencyContactNumber": "0"
}]

2 个答案:

答案 0 :(得分: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);
?>

答案 1 :(得分:0)

这是一个完全不同的野兽来回答完整的问题。比我最初的计划(大约5个小时)更多的工作。仍然可以很好地完成工作,imo。

我已将其转换为PDO。甚至&#39; mysqli&#39;是我想要的更多限制。

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

它需要版本5.3&#39;我使用&#39;关闭&#39;在里面。如果需要,可以为函数更改。请告诉我。

经过测试:PHP 5.3.18,mysql 5.5 windows xp(oi,stop laffin&#39;)

<?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>