I have an array being collect via a form like below:
<select multiple="multiple" name="contractors[]" >
Input code to save the array in the DB.
$options = $_POST['contractors'];
$serializedoptions = serialize($options);
It saves the array in the DB in the format below, but I cannot display it properly. When I pull the entire It shows:
a:4:{i:0;s:28:Contractor1";i:1;s:15:"Contractor2";i:2;s:10:"Contractor3";}
How can I get it to display in a more readable format?
$result = mysql_query("SELECT * FROM form_2 GROUP BY jobname");
echo "<table border='1'>
<tr>
<th><font size='1'>Job Name</th>
<th><font size='1'>Contractors</th>
<th><font size='1'>Notes</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td><font size='1'>" . $row['jobname'] . "</font></td>";
echo "<td><font size='1'>" . $row['contractors'] . "</font></td>";
echo "<td><font size='1'>" . $row['notes'] . "</font></td>";
echo "</tr>";
}
echo "</table>";
That which is serialized must be unserialized. Just use the unserialize function on the data before working with it. In your case, an array will be returned.
http://php.net/manual/en/function.unserialize.php
$options = unserialize($serializedoptions);
Other languages can unserialize PHP serialize() as well if you find supporting code for it. For example, here is one for JavaScript: http://phpjs.org/functions/unserialize/
EDIT:
Updating the code you added, you can display it like any other PHP variable once you unserialize the value.
<?php
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td><font size='1'>" . $row['jobname'] . "</font></td>";
echo "<td><font size='1'>";
$contractors = unserialize($row['contractors']);
foreach ($contractors as $contractor)
echo htmlspecialchars($contractor).'<br/>';
echo "</font></td>";
echo "<td><font size='1'>" . $row['notes'] . "</font></td>";
echo "</tr>";
}
?>
Use print_r on the unserialized array:
print_r(unserialize($serializedArray));
You can use the unserialize command. You can then echo it using var_dump() or print_r().
In the HTML Table above, you would have to further break down the result for $row['contractors'].
So first, you would unserialize that value, so lets say
$contractors = unserialize($row['contractors']);
Then you can iterate through the new array of $contractors, and echoing a after each one, all inside the same TD.
I can't actually unserialize the above serialized data, so I can't write the loop for you.
Use unserialize($serializedoptions) to convert it back into an array. If you want to view it, use var_dump($unserialized)
Related
This question already has answers here:
How to extract and access data from JSON with PHP?
(1 answer)
Read JSON Data Using PHP [duplicate]
(5 answers)
Closed 4 years ago.
I have a JSON file in this format I want to data display in the table using for loops and for each loop what can I do?
[{"fertilizer":
{"pg1":"-21.259515860749435","pg2":"24.741169305724725","lastyearlastmonth":"764.119","currentmonth":"601.671","currentyearytd":"5735.1","lastyearytd":"4597.6","pname":"Urea","mmonth":"11","period":"11","myear":"2017"}},{"fertilizer":{"pg1":"-20.53085432388131","pg2":"9.258986807905458","lastyearlastmonth":"631.435","currentmonth":"501.796","currentyearytd":"2227.9","lastyearytd":"2039.1","pname":"DAP","mmonth":"11","period":"11","myear":"2017"}},{"fertilizer":{"pg1":"67.37546062508531","pg2":"51.07126222636238","lastyearlastmonth":"36.635","currentmonth":"61.318","currentyearytd":"648.7","lastyearytd":"429.4","pname":"CAN","mmonth":"11","period":"11","myear":"2017"}}]
i want to display in table through loop but i have problem how can i display all data thrugh using loops
foreach ($data as $nt)
{
echo "<tr class='{$dispval} {$boldrow}' >";
echo "<td>{$nt[pname]}</td>";
echo "<td class='txtright'>" . number_format($nt[lastyearlastmonth],1) . " </td>";
echo "<td class='txtright'>" . number_format($nt[currentmonth],1) . " </td>";
echo "<td class='txtright'>" . number_format($nt[pg1],1) . " </td>";
echo "<td class='txtright'>" . number_format($nt[lastyearytd],1) . " </td>";
echo "<td class='txtright' >" . number_format($nt[currentyearytd],1) . " </td>";
echo "<td class='txtright'>" . number_format($nt[pg2],1) . " </td>";
echo "</tr>";
}
You are on the right way!
First of all, json is a plain string in PHP. You need to decode it first using: json_decode();
For example:
$items = json_decode('your json string here');
foreach($items as $item) {
echo "<tr>";
echo "<td>".$item->fertilizer->pg1."</td>";
echo "<td>".$item->fertilizer->pg2."</td>";
// etc
echo "</tr>";
}
I have been working on this for awhile and I am maybe making this more difficult than it is. Any shared knowledge would be very much appreciated.
My code calls data using an API, I was able to display it as a ordered list but I wanted to make it more presentable using a table format.
Ideally I the results to be displayed grouped by day.
Below is what I have created so far, but it is not outputting anything currently:
echo "<table>";
echo "<tr>";
echo "<th>Date</th>";
echo "<th>Number of Asteroids</th>";
echo "</tr>";
echo "<tr>";
foreach ($near_earth_object->close_approach_data as $close_approach) {
echo "<td>" . $close_approach->close_approach_date . "</td>";
foreach ($data->near_earth_objects as $date => $count) {
echo"<td>" . sizeof($count) . "</td></tr>";
}
}
echo "<tr>";
echo "<th>Asteroid Name</th>";
echo "<th>Asteroid Size</th>";
echo "<th>Velocity</th>";
echo "<th>Passing Earth By</th>";
echo "</tr>";
echo "<tr>";
foreach ($data->near_earth_objects->$date as $near_earth_object) {
echo "<td>" . $near_earth_object->name . " <a href='" . $near_earth_object->nasa_jpl_url . "'>" . $near_earth_object->nasa_jpl_url . "</td>";
echo "<td>" . $near_earth_object->estimated_diameter->meters->estimated_diameter_min . " metres</td>";
}
foreach ($near_earth_object->close_approach_data as $close_approach) {
echo "<td>" . $close_approach->relative_velocity->kilometers_per_hour . " km/h " . "</td><td>". $close_approach->miss_distance->kilometers . " km</td></tr> ";
}
echo"</table>";
You should avoid echoing HTML code whenever possible. You can use PHP Short tags <?= and ?> to inject PHP into your HTML code. This line
echo "<td>" . $close_approach->close_approach_date . "</td>";
can then be changed to
<td><?=$close_approach->close_approach_date?></td>
Furthermore I don't see any PHP opening and closing tags (<?php and ?>) to start and end your PHP code (although this may just be lacking in your example)
You're only looping through your table data <td> tags not your table row <tr> tags. You have to include these in your loop to keep creating a new table rows for every item in your loop:
foreach ($near_earth_object->close_approach_data as $close_approach) {
echo "<tr>";
Finally, PHP offers an alternative syntax for control structures. Check out the PHP documentation
PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively.
You can use this to improve your existing code:
foreach ($data->near_earth_objects->$date as $near_earth_object) {
echo "<td>" . $near_earth_object->name . " <a href='" . $near_earth_object->nasa_jpl_url . "'>" . $near_earth_object->nasa_jpl_url . "</td>";
echo "<td>" . $near_earth_object->estimated_diameter->meters->estimated_diameter_min . " metres</td>";
}
And turn it into something like this
foreach ($data->near_earth_objects->$date as $near_earth_object): ?>
<td><?=$near_earth_object->name?> <a href='<?=$near_earth_object->nasa_jpl_url?>'><?=$near_earth_object->nasa_jpl_url?></td>
<td><?=$near_earth_object->estimated_diameter->meters->estimated_diameter_min?> metres</td>
<? endforeach; ?>
I recommend creating the table as you'd like to see it just with HTML and then using PHP to dynamically populate it. What may help is, rather than having PHP echo all of the HTML, just use PHP to populate the data (i.e., separate data from display). Just as an example taken from here:
<?php foreach ($things as $thing): ?>
<li><?php echo $thing; ?></li>
<?php endforeach; ?>
To begin with I know very little PHP and no java/javascript or jquery. I have created an html table populated from mysql database. It is for a call log. I am wanting to click on either a <td> or <tr> to open the corresponding record in a new page to be viewed in more detail. I have thought about putting the call_id value in a hidden column to be used in a variable somehow, but don't know where to go from there or if that is anywhere near the correct way to accomplish this.
Assuming that you're creating the table doing something like this,
$results = some_mysql_query;
foreach ($results as $index => $array) {
echo "<tr>";
echo "<td>";
echo $array['RecordNumber'];
echo "</td>";
echo "<td>";
echo $array['CallerName'];
echo "</td>";
echo "<td>";
echo $array['Time'];
echo "</td>";
echo "<td>";
echo $array['Duration'];
echo "</td>";
echo "</tr>";
}
Then you can add in a link by doing something like this:
$results = some_mysql_query;
foreach ($results as $index => $array) {
echo "<tr>";
echo "<td>";
echo "<a href='recordInfo.php?record='" . $array['RecordNumber'] . "'>" . $array['RecordNumber'] . "</a>";
echo "</td>";
echo "<td>";
echo "$array['CallerName'];
echo "</td>";
echo "<td>";
echo $array['Time'];
echo "</td>";
echo "<td>";
echo $array['Duration'];
echo "</td>";
echo "</tr>";
}
NOTE the use of single-quotes, ', inside the double-quotes - and the '" / "' surrounding the variable.
Alternatively, your echo with the link could look like this:
echo "<a href='recordInfo.php?record='{$array['RecordNumber']}'>{$array['RecordNumber']}</a>";
These accomplish the same thing.
This principle is the same, BTW, if your code looks like this:
$results = some_mysql_query;
while ($row = mysql_fetch_array($result)) {
...
echo $row['RecordNumber'];
Also, in case you're not already aware of how this will work, your recordInfo.php will receive its information in the $_GET array; specifically, it will refer to the RecordNumber as $_GET['RecordNumber'].
This question already has answers here:
How do you parse and process HTML/XML in PHP?
(31 answers)
Closed 7 years ago.
I have a String and it gives a XML output , now I want to capture that value. But the problem is there are same variables and that needs to run in a loop.
It's a Shipping method activity tracking, means shiftment step by step process and outputing that
Here is the XML I am getting:
<ArrayOfConsignmentTrack xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<ConsignmentTrack>
<ERROR/>
<DOCKNO>AB000000002</DOCKNO>
<TRANSIT_LOCATION>ANDHERI BRANCH OFFICE, MUMBAI</TRANSIT_LOCATION>
<ACTIVITY>In Transit to</ACTIVITY>
<EVENTDATE>13 Apr 2015</EVENTDATE>
<EVENTTIME>18:27:40</EVENTTIME>
<NEXT_LOCATION>ANDHERI BRANCH OFFICE</NEXT_LOCATION>
<TRACKING_CODE>T</TRACKING_CODE>
</ConsignmentTrack>
<ConsignmentTrack>
<ERROR/>
<DOCKNO>AB000000002</DOCKNO>
<TRANSIT_LOCATION>OKHLA BRANCH, OKHLA</TRANSIT_LOCATION>
<ACTIVITY>Picked up and Booking processed</ACTIVITY>
<EVENTDATE>13 Apr 2015</EVENTDATE>
<EVENTTIME>17:27:53</EVENTTIME>
<NEXT_LOCATION/>
<TRACKING_CODE>T</TRACKING_CODE>
</ConsignmentTrack>
</ArrayOfConsignmentTrack>
Now I want a output like this:
I am using this code to get the value
$myXMLData = file_get_contents($URL);
$xml = (array)simplexml_load_string($myXMLData);
if($xml) {
$dataArray = (array)$xml['ConsignmentTrack'];
echo $DOCKNO = $dataArray['DOCKNO'];
echo $TRANSIT_LOCATION = $dataArray['TRANSIT_LOCATION'];
echo $ACTIVITY = $dataArray['ACTIVITY'];
echo $EVENTDATE = $dataArray['EVENTDATE'];
echo $EVENTTIME = $dataArray['EVENTTIME'];
echo $NEXT_LOCATION = $dataArray['NEXT_LOCATION'];
} else{
echo " - Invalid Docket No.";
}
But it's giving only one value. What loop structure do I have to use?
This should work for you:
Just load your string with simplexml_load_string(), then you can do: echo $xml->asXML(); to see the structure of the xml, to then see where you have to loop through.
<?php
$xml = simplexml_load_string($myXMLData);
echo "<table border='1'>";
echo "<tr>";
echo "<td>Transit Location</td>";
echo "<td>Activity</td>";
echo "<td>Event Date</td>";
echo "<td>Event Time</td>";
echo "<td>next Location</td>";
echo "</tr>";
foreach($xml->ConsignmentTrack as $v) {
echo "<tr>";
echo "<td>" . $v->TRANSIT_LOCATION . "</td>";
echo "<td>" . $v->ACTIVITY . "</td>";
echo "<td>" . $v->EVENTDATE . "</td>";
echo "<td>" . $v->EVENTTIME . "</td>";
echo "<td>" . $v->NEXT_LOCATION . "</td>";
echo "</tr>";
}
echo "</table>";
?>
This is assignment so not looking for anything perfectly safe and secure, just working.I have table in SQL database, I'm printing down all records, all records have unique reference number, for each row of the database I printed down I gave checkbox with value of the row's ref. number, when I submit them by "POST" everything is working and printing out:
if (!$_POST['checkbox']) {
echo "Your basket is empty.";
} else {
echo "<table border='0' id='games_table' cellspacing='1'>";
echo "<tr id='basket_table_row'>";
echo "<td colspan='3'>" . "Logged: " . $_SESSION['user'] . "</td>";
echo "<td colspan ='2'>" . "OS used on this machine: " . "<script type='text/javascript'>document.write(yourOS())</script><noscript>Computers</noscript>" . "</td>";
echo "</tr>";
echo "<tr id='basket_table_row'>";
echo "<td colspan='5'>" . "You put into the basket these games: " . "</td>";
echo "</tr>";
foreach ($_POST['checkbox'] as $value) {
$_SESSION['basket']=array($value);
$res=pg_query($conn,"select * from CSGames where refnumber='$value'");
while ($a = pg_fetch_array ($res)) {
echo "<tr id='games_table_row'>";
echo "<td>" . $a["refnumber"] . "</td>";
echo "<td>" . $a["title"] . "</td>";
echo "<td>" . $a["platform"] . "</td>";
echo "<td>" . $a["description"] . "</td>";
echo "<td>" . $a["price"] . "</td>";
echo "</tr>";
}
}
echo "</table>\n";
}
but only think which stays recorded in $_SESSION['basket'] is value of the last checkbox but I need all of them (60 or 70).
what Am I doing wrong?
You are overwriting te value of $_SESSION['basket'] at each iteration of the loop.
The last value is the only one stored.
Currently, you are only storing the last value, if you wish to store every value, you should add it like this:
$_SESSION['basket'][] = $value;
foreach($_POST['checkbox'] as $value){
$_SESSION['basket']=array($value);
}
every iteration of your loop is overwriting the value in $_SESSION['basket'], hence you only seeing the last checkbox value.
In every step of foreach, you create a new array in $_SESSION['basket'] with only one item, the current value of $value. It is corrected like this:
// ...
$_SESSION['basket'] = array();
foreach ($_POST['checkbox'] as $value) {
$_SESSION['basket'][] = $value;
// ...
}
// ...
You can directly do it like this
$_SESSION['basket'] = $_POST['checkbox'];
because the data of $_POST['checkbox'] is an array anyway.
What you are doing is looping the $_POST['checkbox'] and saving each data as array to a session.
this $_SESSION['basket'] = $_POST['checkbox'];
and
foreach ($_POST['checkbox'] as $value) {
$_SESSION['basket'][]=$value;
}
will have the same value.
What you have right only saves the last value of $_POST['checkbox']