How do i get the string output? There is one error which occurred when i tried to decode. And I want to insert the output value in textbox.
我如何获得字符串输出?我尝试解码时发生了一个错误。我想在文本框中插入输出值。
How can it be done ?
怎么做到呢 ?
$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
My 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);
?>
My JSON Output
我的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 个解决方案
#1
0
Save the json encoded array then restore it later.
保存json编码的数组,然后再恢复。
untested code
<?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);
?>
#2
0
This is a completely different beast to answer the full question asked. Rather more work than i initially planned (about 5 hours). Still it does the job rather nicely, imo.
这是一个完全不同的野兽来回答所提出的完整问题。相比我最初计划的工作(大约5个小时)。仍然它很好地完成了工作,imo。
I have converted it to PDO. Even 'mysqli' was rather more limiting that i wanted.
我已将其转换为PDO。甚至'mysqli'也是我想要的限制。
Purpose: select child details from the db. Shows a form with all the details. Validates the input - well, checks for missing input. Displays individual error messages. Have a play with it.
目的:从数据库中选择子详细信息。显示包含所有详细信息的表单。验证输入 - 好吧,检查缺少的输入。显示各个错误消息。玩一玩吧。
It needs version 5.3 'cos i use a 'closure' in it. That can be changed for a function if required. Just let me know.
它需要版本5.3'我在其中使用'闭包'。如果需要,可以为函数更改。请告诉我。
Tested: PHP 5.3.18, mysql 5.5 windows xp (oi, stop laffin')
经测试: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), ' :' ?></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>
#1
0
Save the json encoded array then restore it later.
保存json编码的数组,然后再恢复。
untested code
<?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);
?>
#2
0
This is a completely different beast to answer the full question asked. Rather more work than i initially planned (about 5 hours). Still it does the job rather nicely, imo.
这是一个完全不同的野兽来回答所提出的完整问题。相比我最初计划的工作(大约5个小时)。仍然它很好地完成了工作,imo。
I have converted it to PDO. Even 'mysqli' was rather more limiting that i wanted.
我已将其转换为PDO。甚至'mysqli'也是我想要的限制。
Purpose: select child details from the db. Shows a form with all the details. Validates the input - well, checks for missing input. Displays individual error messages. Have a play with it.
目的:从数据库中选择子详细信息。显示包含所有详细信息的表单。验证输入 - 好吧,检查缺少的输入。显示各个错误消息。玩一玩吧。
It needs version 5.3 'cos i use a 'closure' in it. That can be changed for a function if required. Just let me know.
它需要版本5.3'我在其中使用'闭包'。如果需要,可以为函数更改。请告诉我。
Tested: PHP 5.3.18, mysql 5.5 windows xp (oi, stop laffin')
经测试: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), ' :' ?></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>