looping through json decoded array - php

This is my code to get product details from database..
$i=0;
foreach($res->result() as $row ){
$products=json_decode($row->product_name,1);
//var_dump($products);
/*$sess_products[$i]['product_id'] = $row->product_id;
$sess_products[$i]['product_name'] = $row->product_name;
$sess_products[$i]['quantity'] = $row->quantity;
$sess_products[$i]['unit'] = $row->unit;
$sess_products[$i]['unit_rate'] = $row->unit_rate;
$this->session->set_userdata('sess_products',$sess_products);*/
//$post_array['cart']=$this->session->userdata('sess_products');
echo "<tr>";
echo "<td><input type='hidden' style='width:80%;' value='".$products[$i]['product_id']."' name='product_id[]'/></td>";
echo "<td><input type='hidden' style='width:80%;' value='".$products[$i]['product_name']."' name='product_name[]'/></td>";
echo "</tr>";
echo "<tr>";
echo "<td style='width:40%;'>".$products[$i]['product_name']."</td>";
echo "<td><input type='text' class='quantity' style='width:100%;' value='".$products[$i]['quantity']."' name='quantity[]'/></td>";
echo "<td><input type='text' class='quantity' style='width:100%;' value='".$products[$i]['unit']."' name='unit[]'/></td>";
echo "<td><input type='text' class='quantity' style='width:100%;' value='".$products[$i]['unit_rate']."' name='unit_rate[]'/></td>";
echo "<td><a href='javascript:void(0)' rownum='".$i."' class='remove_from_update_cart'><img src='images/close.png'/></a></td>";
echo "</tr>";
$i++;
}
Now I am able to display first item in json string by decoding it. but I want to display whole records in foreach loop.? So what will be the error??
Above code display only first record from that array.

I guess this is working,
<?php
$product = '[{"product_id":"1","product_name":"Apple iMac","quantity":"32","unit":"23","unit_rate":"32"},{"product_id":"5","product_name":"Nokia E5","quantity":"543","unit":"543","unit_rate":"543"},{"product_id":"8","product_name":"Zinc Sulphate 500 ml","quantity":"5443","unit":"434","unit_rate":"5333"}]';
$products = json_decode($product, true);
print_r($products);
Output:
Array
(
[0] => Array
(
[product_id] => 1
[product_name] => Apple iMac
[quantity] => 32
[unit] => 23
[unit_rate] => 32
)
[1] => Array
(
[product_id] => 5
[product_name] => Nokia E5
[quantity] => 543
[unit] => 543
[unit_rate] => 543
)
[2] => Array
(
[product_id] => 8
[product_name] => Zinc Sulphate 500 ml
[quantity] => 5443
[unit] => 434
[unit_rate] => 5333
)
)
Demo:
http://3v4l.org/5D3qe
EDIT:
foreach($res->result() as $row)
{
$products = json_decode($row->product_name, true);
foreach($products as $prod)
{
echo "<tr>";
echo "<td><input type='hidden' style='width:80%;' value='".$prod['product_id']."' name='product_id[]'/></td>";
echo "<td><input type='hidden' style='width:80%;' value='".$prod['product_name']."' name='product_name[]'/></td>";
echo "</tr>";
echo "<tr>";
echo "<td style='width:40%;'>".$prod['product_name']."</td>";
echo "<td><input type='text' class='quantity' style='width:100%;' value='".$prod['quantity']."' name='quantity[]'/></td>";
echo "<td><input type='text' class='quantity' style='width:100%;' value='".$prod['unit']."' name='unit[]'/></td>";
echo "<td><input type='text' class='quantity' style='width:100%;' value='".$prod['unit_rate']."' name='unit_rate[]'/></td>";
echo "<td><a href='javascript:void(0)' rownum='".$i."' class='remove_from_update_cart'><img src='images/close.png'/></a></td>";
echo "</tr>";
}
}

Use
json_decode($product, true);
To get as an array

Try trimming:
foreach($res->result() as $row ){
$product=$row->product_name;
$products=json_decode(trim($product), 1);
print_r($products);
}
Tried:
var_dump(json_decode('[{"product_id":"1","product_name":"Apple iMac","quantity":"32","unit":"23","unit_rate":"32"},{"product_id":"5","product_name":"Nokia E5","quantity":"543","unit":"543","unit_rate":"543"},{"product_id":"8","product_name":"Zinc Sulphate 500 ml","quantity":"5443","unit":"434","unit_rate":"5333"}]'));
UPDATE:
Not sure but, it can be this bug. I can see the white space between Apple iMac. One option left is to try updating PHP, this might be too much.
Try test cases from the bug link:
Test script:
<?
function json_cmp($x, $y)
{
print var_dump(json_decode($x) === $y);
}
// works
json_cmp("true", true);
// fails - is actually true
json_cmp("tRue", NULL);
// fails - is actually NULL
json_cmp("true ", true);
// works
json_cmp("[true ] ", array(true));
// works, even though the non-array version fails
json_cmp("[tRue]", NULL);
?>
Expected result:
true * 5
Actual result:
bool(true)
bool(false)
bool(false)
bool(true)
bool(true)

This is my working code..
$i=0;
foreach($res->result() as $row ){
$j=0;
$products=json_decode($row->product_name,1);
foreach($products as $row2){
$sess_products[$j]['product_id'] = $row2['product_id'];
$sess_products[$j]['product_name'] = $row2['product_name'];
$sess_products[$j]['quantity'] = $row2['quantity'];
$sess_products[$j]['unit'] = $row2['unit'];
$sess_products[$j]['unit_rate'] = $row2['unit_rate'];
$this->session->set_userdata('sess_products',$sess_products);
//print_r($sess_products);
//$post_array['cart']=$this->session->userdata('sess_products');
echo "<tr>";
echo "<td><input type='hidden' style='width:80%;' value='".$row2['product_id']."' name='product_id[]'/></td>";
echo "<td><input type='hidden' style='width:80%;' value='".$row2['product_name']."' name='product_name[]'/></td>";
echo "</tr>";
echo "<tr>";
echo "<td style='width:40%;'>".$row2['product_name']."</td>";
echo "<td><input type='text' class='quantity' style='width:100%;' value='".$row2['quantity']."' name='quantity[]'/></td>";
echo "<td><input type='text' class='quantity' style='width:100%;' value='".$row2['unit']."' name='unit[]'/></td>";
echo "<td><input type='text' class='quantity' style='width:100%;' value='".$row2['unit_rate']."' name='unit_rate[]'/></td>";
echo "<td><a href='javascript:void(0)' rownum='".$j."' class='remove_from_update_cart'><img src='images/close.png'/></a></td>";
echo "</tr>";
$j++;
}
}

Related

Stop button to repet in loop

Is there any way to stop a button from submit button to stop looping in while loop?
it just looks terrible to have like 15 submit buttons insted of 1. whitout moving it from the from
$sql = "SELECT * FROM `bestalning` WHERE lev=0
ORDER BY tid";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
echo "<div class='continer bg-vit table-rsponsive-sm '>";
echo "<table class='table'>";
echo "<thead class='thead-dark'>";
echo "<tr><th>Lev</th>";
echo "<th> </th>";
echo "<th>Artikelnr</th>";
echo "<th>Antal</th>";
echo "<th>Singnatur</th>";
echo "<th>Önskad ankomst</th>";
echo "<th>Skickad</th>";
echo "</tr></thead><tbody>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<form method='POST' action='ID_change.php'>";
echo "<td><input style='margin-right:5px;' name='levJA' type='checkbox' value='1'></td>";
echo "<td><input style='margin-right:5px;' name='RowID' type='hidden' value='".$row['ID']."'></td>";
echo "<td>".$row['artikelnr']."</td>";
echo "<td>".$row['antal']."</td>";
echo "<td>".$row['ovrigt']."</td>";
echo "<td>".$row['Tid']."</td>";
echo "<td>".$row['date']."</td>";
echo "<input class='btn btn-dark m-1' type='submit' value='submit'>;
echo "</form>";
echo "</tr>";
}
echo "</tbody></table>";
echo "</div>";
mysqli_close($conn);

PDO MySQL update statement does not effect

I use two PHP files, one a_ndryshoje_produktin.php for posting data to be updated and one another produkti_ndryshuar.php that executes the posted data for update.
The problem for my question is that the file produkti_ndryshuar.php does execute without errors but there isn't any update of only the produkti_id with the produkti_i_ri_id on MySQL produktet table.
Below is my code for both files.
Thank you
echo "<form action='produkti_ndryshuar.php' method='post'>";
echo "<table class='tbl_manevro'>";
echo "<tr><td class='titujt'>";
echo "ID";
echo "</td></tr>";
echo "<tr><td>";
echo "<input type='text' name='produkti_i_ri_id' maxlength='60' value='".$row['produkti_id']."' />";
echo "</td></tr>";
echo "<tr><td class='titujt'>";
echo "Kategoria";
echo "</td></tr>";
echo "<tr><td>";
echo "<input type='text' name='kategori_id' maxlength='60' value='".$row['kategori_id']."' />";
echo "</td></tr>";
echo "<tr><td class='titujt'>";
echo "Emri";
echo "</td></tr>";
echo "<tr><td>";
echo "<input type='text' name='produkti_emri' maxlength='60' value='".$row['produkti_emri']."' />";
echo "</td></tr>";
echo "<tr><td class='titujt'>";
echo "Çmimi";
echo "</td></tr>";
echo "<tr><td>";
echo "<input type='text' name='produkti_cmimi' maxlength='60' value='".$row['produkti_cmimi']."' />";
echo "</td></tr>";
echo "<tr><td class='titujt'>";
echo "Fotografia";
echo "</td></tr>";
echo "<tr><td>";
echo "<input type='text' name='produkti_fotografia' maxlength='60' value='".$row['produkti_fotografia']."' />";
echo "</td></tr>";
echo "<input type='hidden' name='produkti_id' value=".$row['produkti_id']." />";
echo "<tr><td>";
echo "<input class='shtoje_btn' type='submit' value='Ndryshoje produktin' />";
echo "</td></tr>";
echo "</table>";
echo "</form>";
and the other file produkti_ndryshuar.php :
$produkti_i_ri_id=strip_tags($_POST['produkti_i_ri_id']);
$kategori_id=strip_tags($_POST['kategori_id']);
$produkti_emri=strip_tags($_POST['produkti_emri']);
$produkti_cmimi=strip_tags($_POST['produkti_cmimi']);
$produkti_fotografia=strip_tags($_POST['produkti_fotografia']);
$produkti_id=strip_tags($_POST['produkti_id']);
if($produkti_i_ri_id && $kategori_id && $produkti_emri && $produkti_cmimi && $produkti_fotografia ){
$db=include('dbconnect.php');
$query_2=$db->prepare("update produktet set
produkti_id=:produkti_i_ri_id,
kategori_id=:kategori_id,
produkti_emri=:produkti_emri,
produkti_cmimi=:produkti_cmimi,
produkti_fotografia=:produkti_fotografia
where produkti_id=:produkti_id");
$query_2->execute(array(':produkti_i_ri_id'=>$produkti_i_ri_id,
':kategori_id'=>$kategori_id,
':produkti_emri'=>$produkti_emri,
':produkti_cmimi'=>$produkti_cmimi,
':produkti_fotografia'=>$produkti_fotografia,
':produkti_id'=>$produkti_id));
echo "<span class='lajmi_sakte'>Produkti i caktuar u ndryshua me sukses.</span>";
}
You are giving values to your if statement, not booleans.
Try isset() :
$produkti_i_ri_id=strip_tags($_POST['produkti_i_ri_id']);
$kategori_id=strip_tags($_POST['kategori_id']);
$produkti_emri=strip_tags($_POST['produkti_emri']);
$produkti_cmimi=strip_tags($_POST['produkti_cmimi']);
$produkti_fotografia=strip_tags($_POST['produkti_fotografia']);
$produkti_id=strip_tags($_POST['produkti_id']);
if(isset($produkti_i_ri_id) && isset($kategori_id) && isset($produkti_emri) && isset($produkti_cmimi) && isset($produkti_fotografia) ){
$db=include('dbconnect.php');
$query_2=$db->prepare("update produktet set
produkti_id=:produkti_i_ri_id,
kategori_id=:kategori_id,
produkti_emri=:produkti_emri,
produkti_cmimi=:produkti_cmimi,
produkti_fotografia=:produkti_fotografia
where produkti_id=:produkti_id");
$query_2->execute(array(':produkti_i_ri_id'=>$produkti_i_ri_id,
':kategori_id'=>$kategori_id,
':produkti_emri'=>$produkti_emri,
':produkti_cmimi'=>$produkti_cmimi,
':produkti_fotografia'=>$produkti_fotografia,
':produkti_id'=>$produkti_id));
echo "<span class='lajmi_sakte'>Produkti i caktuar u ndryshua me sukses.</span>";
}
else{
echo "<span class='lajmi_mink'>Ju lutemi plotësoni të gjitha fushat!!!</span>";
}
And why are you using strip_tags() function?

How to random the choices in php

I am creating a random generated quiz with 10 questions. In generating the random question is fine, but I want to display also the choices in random, same with the questions.
This is my code that I am currently working with:
<?php
generate();
function generate(){
include('connection.php');
mysql_select_db('exam');
$result=mysql_query("SELECT * FROM questionaires
INNER JOIN choices ON questionaires.q_id=choices.q_id
WHERE RAND()<(SELECT ((10/COUNT(*))*10) FROM questionaires)
ORDER BY RAND() LIMIT 10");
$c=0;
echo "<table border='3' align='center' bordercolor='#CCCCCC'>
<tr>
<th>Number:</th>
<th>Question</th>
</tr>
";
while($row = mysql_fetch_array($result)){
$c++;
echo "<tr>";
echo "<td>" . $c . "</td>";
echo "<td>";
echo $row['question'] . "<br>";
echo "<input type='radio' name='ans'>".$row['choice_a']."</input><br>";
echo "<input type='radio' name='ans'>".$row['choice_b']."</input><br>";
echo "<input type='radio' name='ans'>".$row['choice_c']."</input><br>";
echo "<input type='radio' name='ans'>".$row['choice_d']."</input><br>";
echo "</td>";
echo "</tr>";
//}
//}
}
echo "</table>";
}
?>
Little help will highly appreciated.
You could change script to this:
echo "<td>";
echo $row['question'] . "<br>";
$ans=array($row['choice_a'],$row['choice_b'],$row['choice_c'],$row['choice_d']);
shuffle($ans);
foreach ($ans as $choice) {
echo "<input type='radio' name='ans'>".$choice."</input><br>";
} unset($choice);
echo "</td>";

form input value before Submit the Form

I am writing an attendance system, where the name of the person working in a department will be shown and user will select respective attendance through radio buttons. I want to write the attendance record in a mysql data base.
For this i tried to prepare an array where i am unable to pass the value of selected radio button. Please help.
The sample code is as under:
<?php
$qry1="select * from master where office='ECZO_IT' order by cadre desc,srno";
$result1=mysql_query($qry1,$con);
$sl=1;
echo "<form method='post' action=''>";
echo "<table align='center' border='1' cellpadding='0' cellspacing='0' style='border- collapse: collapse' bordercolor='#111111' width='800' id='AutoNumber1' height='219'>";
echo "<tr><th colspan='14' bgcolor='#C0C0C0' align='center'>Attendance Report</th></tr>";
echo "<tr bgcolor='#C0C0C0' align='center'><th>Sl.</th>";
echo "<th >SR No.</th>";
echo "<th>Name</th>";
echo "<th>Designation</th>";
echo "<th colspan='10' align='center'>Attendance</th></tr>";
while ($data=mysql_fetch_row($result1))
{
echo "<tr><td align='center'>$sl</td>";
echo "<td align='center'>$data[0]</td>";
echo "<td>$data[1]</td>";
echo "<td align='center'>$data[4]</td>";
echo "<td bgcolor='#C0C0C0' align='center'>Present</td>";
echo "<td><input type='radio' name='r1[$sl]' value='PRESENT' id='at' checked></td>";
echo "<td bgcolor='#C0C0C0' align='center'>Training</td>";
echo "<td><input type='radio' name='r1[$sl]' value='TRAINING' id='at'></td>";
echo "<td bgcolor='#C0C0C0' align='center'>Tour</td>";
echo "<td><input type='radio' name='r1[$sl]' value='TOUR' id='at'></td>";
echo "<td bgcolor='#C0C0C0' align='center'>Leave</td>";
echo "<td><input type='radio' name='r1[$sl]' value='LEAVE' id='at'></td>";
echo "<td bgcolor='#C0C0C0' align='center'>Absent</td>";
echo "<td><input type='radio' name='r1[$sl]' value='ABSENT' id='at'></td></tr>";
$out[]= array ('srno' => $data['0'], 'ename' => $data[1], 'att' => $_POST['r1']);
$sl=$sl+1;
}
echo "</table>";
echo "<p align='center'><input type='submit' name ='s1' value='Submit'></p>";
echo "</form>";
foreach($out as $row)
{
echo $row['srno'].'----'.$row['ename'].'----'.$row['att']."<br/>";
}
?>
Please suggest if there is any other way out
Notes:
I tried to change the array as under
$out = array ('srno' => $data['0'], 'ename' => $data[1], 'att' => $_POST['r1']);
before modification the result was like this:
343587----SUNIL PRASAD OJHA----Array
343607----MUKESH KUMAR JHA----Array
343701----PRABHAT RANJAN----Array
After modification the result was as under:
3----3----3
P----P----P
I also tried to check output through the following code in foreach loop:
echo var_dump($out['att']);
but the result shows NULL only
Please help
I can access your radio button's value through:
var_dump($out[0]['att']);
Correct your array this way:
$out = array ('srno' => $data['0'], 'ename' => $data[1], 'att' => $_POST['r1']); //removed [] from $out
to accces it as:
echo $out['att'][1];
The 1 is because your radio buttons are an input array and your $sl value is 1
I have no idea why you need the foreach loop but you can also use it this way:
$data[1]='test';
$data2[1]='test2';
$out= array ('srno' => $data, 'ename' => $data2, 'att' => $_POST['r1']);
$i=1;
foreach($out as $key=>$val)
{
echo $key.'='.$val[$i]."<br/>";
}
//Prints: srno=test
// ename=test2
// att=TRAINING

Php empty array checking

I've a following html table which name contain array. How can i check this array if it's value is empty ?
echo "<input type='radio' name='ch[$roll][$sname][$class]' value='1' /> ";
echo "<input type='radio' name='ch[$id][$sname][$class]' value='0' />";
Currently i'm checking it with following code, it's not working but i know the name is array and it's must be compare with any array function. Can you guys give me a idea ?
if(isset($_POST['ch']))
{
$ch = $_POST['ch'];
if(empty($ch))
echo "<div class='error>Select attendence field. </div>";
}
Regards.
Update: (Full Code)
$action = htmlspecialchars($_SERVER['PHP_SELF'])."?class=$class_from";
echo "<form method='post' action='$action' name='attendence'/>";
echo "<table width='100%' cellpadding='0' cellspacing='0' border='0'>";
echo "<tr>";
echo "<td class='tdhead' valign='top' width='200'><b>Student Name</b></td>";
echo "<td class='tdhead' valign='top' width='250'><b>Roll No</b>
</td>";
echo "<td class='tdhead' valign='top' width='250'><b>Class Name</b>
</td>";
echo "<td class='tdhead' valign='top' width='200'><b>Present / Not present</b>
</td>";
echo "<td class='tdhead' valign='top' width='200'>
Present All <input type= 'checkbox'
onclick='checkAll(this)'</td>";
echo "</tr>";
//start the counter variable
$counter = 1;
while($res2 = mysql_fetch_array($sql2))
{
$id = (int) $res2['id'];
$sname = inputvalid($res2['sname']);
$roll = inputvalid($res2['roll']);
$class = inputvalid($res2['class']);
echo "<tr>";
echo "<td class='tdhead2' valign='top'>$sname</td>";
echo "<td class='tdhead2' valign='top'>$roll</td>";
echo "<td class='tdhead2' valign='top'>$class</td>";
echo "<td class='tdhead2' valign='top'>";
//echo each radio with the counter for this row
echo "<input type='radio' name='ch[$roll][$sname][$class]' value='1' /> ";
echo "<input type='radio' name='ch[$id][$sname][$class]' value='0' />";
echo "</td>";
echo "<td class='tdhead2' valign='top'> </td>";
echo "</tr>";
//add one to the counter
$counter++;
}
echo "<tr>";
echo "<td class='tdhead2'> </td>";
echo "<td class='tdhead2'> </td>";
echo "<td class='tdhead2'> </td>";
echo "<td class='tdhead2'> </td>";
echo "<td class='tdhead2'><input type='submit' value='Record' name='Submit'
class='submit' /></td>";
echo "</tr>";
echo "</table>";
echo "</form>";
if(isset($_POST['Submit']) && $_POST['Submit'] == "Record")
{
if(isset($_POST['ch']))
{
$ch = array_filter($_POST['ch']);
if (empty($ch))
{
echo "<div class='error>Select attendence field. </div>";
}
}
if(count($ch) == 0)
{
echo "<div class='error>Select attendence field. </div>";
}
else
{
foreach ($_POST['ch'] as $roll => $arr1)
{
$roll;
foreach ($arr1 as $name => $arr2)
{
$name;
foreach ($arr2 as $class => $value)
{
$class;
$value;
$sql = mysql_query("INSERT INTO e_attendence VALUES('', '$name', '$roll', '$class',
'$value', '$current_date')");
}
}
}
}
if($sql)
echo "<div class='success'>Succesfully recorded.
</div>";
}
empty() method work for finding whether the array is empty or not.
But for Your solution use below:-
if(isset($_POST['ch']) && $_POST['ch']=='1')
{
$ch = $_POST['ch'];
if(empty($ch))
echo "<div class='error>Select attendence field. </div>";
}
if You want to show a error message when no radio is selected then use below code:-
if(!isset($_POST['ch']) && $_POST['ch']=='')
{
echo "You have not selected any radio button";
}
use empty() instead of isset()
check the comparison table available at the below link
http://php.net/manual/en/types.comparisons.php
try this
print_r($_POST['ch']);
Try this
if(isset($_POST['ch'])){
$ch = array_filter($_POST['ch']);
if (empty($ch)) {
echo "<div class='error>Select attendence field. </div>";
}
}

Categories