繁体   English   中英

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

[英]How do i decode and get string values from 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"
}]

保存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);
?>

这是回答问题的完全不同的野兽。 比我最初计划的要多的工作(大约5个小时)。 imo,它仍然做得很好。

我已经将其转换为PDO。 甚至“ mysqli”也比我想要的要多。

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

它需要版本5.3'cos,我在其中使用了'closure'。 可以根据需要更改功能。 请让我知道。

已测试:PHP 5.3.18,MySQL 5.5 Windows XP(Oi,Stop 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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM