I have a form with 4 checkboxes; debut, batted, no and bowled. When adding, if one is checked, it will add in the data with this code (in this instance, debut):
if(!empty($_POST["debut"])) {
try
{
$sql = 'INSERT INTO performance SET
matchid = :matchid,
playerid = :playerid,
team = :team,
debut = 1,
batted = 0,
batpos = :batpos,
runs = :runs,
ballsfaced = :ballsfaced,
fours = :fours,
sixes = :sixes,
no = 0,
howout = :howout,
fielder = :fielder,
bowler = :bowler,
bowled = 0,
ballsbowled = :ballsbowled,
maidens = :maidens,
wickets = :wickets,
runsconceded = :runsconceded,
catches = :catches,
stumpings = :stumpings,
runouts = :runouts';
$s = $pdo->prepare($sql);
$s->bindValue(':matchid', $_POST['matchid']);
$s->bindValue(':playerid', $_POST['playerid']);
$s->bindValue(':team', $_POST['team']);
$s->bindValue(':batpos', $_POST['batpos']);
$s->bindValue(':runs', $_POST['runs']);
$s->bindValue(':ballsfaced', $_POST['ballsfaced']);
$s->bindValue(':fours', $_POST['fours']);
$s->bindValue(':sixes', $_POST['sixes']);
$s->bindValue(':howout', $_POST['howout']);
$s->bindValue(':fielder', $_POST['fielder']);
$s->bindValue(':bowler', $_POST['bowler']);
$s->bindValue(':ballsbowled', $_POST['ballsbowled']);
$s->bindValue(':maidens', $_POST['maidens']);
$s->bindValue(':wickets', $_POST['wickets']);
$s->bindValue(':runsconceded', $_POST['runsconceded']);
$s->bindValue(':catches', $_POST['catches']);
$s->bindValue(':stumpings', $_POST['stumpings']);
$s->bindValue(':runouts', $_POST['runouts']);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error adding submitted performance.';
include 'error.html.php';
exit();
}
}
And it works perfectly fine. But if I try a combination (eg debut and batted) it doesnt work by using this code:
else if(!empty($_POST["debut"]) && (!empty($_POST["batted"]))) {
try
{
$sql = 'INSERT INTO performance SET
matchid = :matchid,
playerid = :playerid,
team = :team,
debut = 1,
batted = 1,
batpos = :batpos,
runs = :runs,
ballsfaced = :ballsfaced,
fours = :fours,
sixes = :sixes,
no = 0,
howout = :howout,
fielder = :fielder,
bowler = :bowler,
bowled = 0,
ballsbowled = :ballsbowled,
maidens = :maidens,
wickets = :wickets,
runsconceded = :runsconceded,
catches = :catches,
stumpings = :stumpings,
runouts = :runouts';
$s = $pdo->prepare($sql);
$s->bindValue(':matchid', $_POST['matchid']);
$s->bindValue(':playerid', $_POST['playerid']);
$s->bindValue(':team', $_POST['team']);
$s->bindValue(':batpos', $_POST['batpos']);
$s->bindValue(':runs', $_POST['runs']);
$s->bindValue(':ballsfaced', $_POST['ballsfaced']);
$s->bindValue(':fours', $_POST['fours']);
$s->bindValue(':sixes', $_POST['sixes']);
$s->bindValue(':howout', $_POST['howout']);
$s->bindValue(':fielder', $_POST['fielder']);
$s->bindValue(':bowler', $_POST['bowler']);
$s->bindValue(':ballsbowled', $_POST['ballsbowled']);
$s->bindValue(':maidens', $_POST['maidens']);
$s->bindValue(':wickets', $_POST['wickets']);
$s->bindValue(':runsconceded', $_POST['runsconceded']);
$s->bindValue(':catches', $_POST['catches']);
$s->bindValue(':stumpings', $_POST['stumpings']);
$s->bindValue(':runouts', $_POST['runouts']);
$s->execute();
}
catch (PDOException $e)
{
$error = 'Error adding submitted performance.';
include 'error.html.php';
exit();
}
}
And in this instance only debut will be inserted as 1. What am I doing wrong?
I notice this is inside an elseif statement... maybe the first condition is met and this part of the code is never executed?
If this code follows the above if statement, that would definitely be the case.
[edit]
You should check for code duplication as well, if the only difference is setting 'batted' and 'debut' to 0 or 1, there is a much shorter way of doing it without the 'if' statement.
$debut = (isset($_POST['debut']) ? 1 : 0);
$batted = (isset($_POST['batted']) ? 1 : 0);
Then just bind the values as you did with the others. see http://davidwalsh.name/php-ternary-examples for examples of ternary statements
Related
I am inserting a serial number in a table that is increment by one always but when multiple request is coming in same time it is inserting same serial number for different requests.I am using mysql database.
I know i am fetching the max serial number too early in the code and if request is come in same time so it will fetching same serial number for both. is it good idea to update serial number after all work done. what if inserting a record for new request and updating the serial number for previous one is in same time.
public function add(){
$session = $this->request->session();
$company_id = $session->read('Admin.company_id');
$emp_id = $session->read('Admin.emp_id');
$user_email_id = $session->read('Admin.email_id');
$employee_name = $session->read('Admin.employee_name');
$conn = ConnectionManager::get('default');
if ($this->request->is('post')) {
try{
$conn->begin();
$department = $this->request->data['department'];
$data = $this->request->data;
if(!array_key_exists('is_requisition_for_contractor', $data)){
$is_requisition_for_contractor = 0;
} else {
$is_requisition_for_contractor = $data['is_requisition_for_contractor'];
}
if(!array_key_exists('is_requisition_for_employee', $data)){
$is_requisition_for_employee = 0;
} else {
$is_requisition_for_employee = $data['is_requisition_for_employee'];
}
if(!array_key_exists('is_boulder_requisition', $data)){
$is_requisition_for_boulder = 0;
} else {
if($data['is_boulder_requisition'] == ''){
$is_requisition_for_boulder = 0;
} else {
$is_requisition_for_boulder = $data['is_boulder_requisition'];
}
}
$is_requisition_for_plant = 0;
if(!array_key_exists('is_plant_requisition', $data)){
$is_requisition_for_plant = 0;
} else {
if($data['is_plant_requisition'] == ''){
$is_requisition_for_plant = 0;
} else {
$is_requisition_for_plant = $data['is_plant_requisition'];
}
}
if(array_key_exists("files",$this->request->data)) {
$files = $this->request->data['files'];
if (count($files)) {
$files_uploading_response = $this->uploadMultipleFiles($files, 'files/requisitions/');
}
}
$last_material_insert_id = '';
if($this->request->data('material_id')[0] == ''){
if($this->request->data('department') == 1){
$type = 1;
} elseif($this->request->data('department') == 3){
$type = 3;
} elseif($this->request->data('department') == 2){
$type = 2;
}
if($this->request->data('department') == 1 || $this->request->data('department') == 3){
$conn->execute("INSERT INTO material (material_name, material_type_id, company_id, status, is_approved_by_admin) VALUES (?,?,?,?,?)",[$this->request->data('material_name'), $type, $company_id, 1,0]);
$last_material_insert_id = $conn->execute("SELECT LAST_INSERT_ID() AS last_id")->fetchAll('assoc');
} elseif($this->request->data('department') == 2) {
//todo for unapproved material
$conn->execute("INSERT INTO material (part_no, material_type_id, company_id, status, is_approved_by_admin,unique_category_id) VALUES (?,?,?,?,?,?)",[$this->request->data('part_no')[0], $type, $company_id, 1,0,$this->request->data('unique_category_id')[0]]);
$last_material_insert_id = $conn->execute("SELECT LAST_INSERT_ID() AS last_id")->fetchAll('assoc');
}
}
// here i am fatching max serial number from table
$requistion_number = $conn->execute("SELECT IF(MAX(requisition_no) IS NULL, 0,MAX(requisition_no)) AS requisition_no FROM requisition WHERE site_id = ?",[$this->request->data('site_id')])->fetchAll('assoc');
$Requisition = TableRegistry::get('requisition');
$requisition = $Requisition->newEntity();
$requisition->registered_on = $this->request->data['date'];
$requisition->department_id = $this->request->data('department');
$requisition->site_id = $this->request->data('site_id');
$requisition->issues_to_id = $this->request->data['prepared_by_id'];
$requisition->prepared_by_id = $this->request->data['prepared_by_id'];
$requisition->approved_by_id = $this->request->data['hod_id'];
$requisition->hod_id = $this->request->data['hod_id'];
$requisition->is_diesel_requisition_for_employee = $is_requisition_for_employee;
$requisition->is_diesel_requisition_for_contractor = $is_requisition_for_contractor;
$requisition->is_requisition_for_boulder = $is_requisition_for_boulder;
$requisition->is_requisition_for_plant = $is_requisition_for_plant;
if(array_key_exists('for_tanker_stock', $this->request->data)) {
$requisition->for_tanker_stock = 1;
}
if($last_material_insert_id != ''){
$requisition->is_material_approved_by_admin = 0;
}
$requisition->status = 1;
$site_id = $this->request->data['site_id'];
$requisition->requisition_no = $requistion_number[0]['requisition_no'] + 1;
$requistionnumber = $requistion_number[0]['requisition_no'] + 1;
$saveRequsition = $Requisition->save($requisition);
$conn->commit();
}
I am expecting the output different serial number for each request.any optimise way to do this. thanks in advance.
Ok, how about the same strategy, setting the $requisition_number after the row has been inserted (see my other answer), but using a single query with the same method you use to determine the new requisition id:
$conn->execute("UPDATE requisition
SET requisition_no = (SELECT IF(MAX(requisition_no) IS NULL, 0,MAX(requisition_no)) AS requisition_no FROM requisition WHERE site_id = ?) + 1",
[$this->request->data('site_id')]);
The idea here is that a single query will be executed in one step, without another, similar query, being able to interfere.
What you currently do is to first get the old requistion number like this:
$requistion_number = $conn->execute("SELECT IF(MAX(requisition_no) IS NULL, 0,MAX(requisition_no)) AS requisition_no
FROM requisition WHERE site_id = ?",[$this->request->data('site_id')])->fetchAll('assoc');
and then increase it before you save and commit.
My suggestion is to not set the $requistion_number at all before you save and commit the requisition row, but to determine the $requistion_number afterwards.
You now wonder how?
Well, you need to count the total number of requisition rows in the table for the site the requisition is for, and add one, like this:
$last_requisition_id = $conn->execute("SELECT LAST_INSERT_ID() AS last_id")->fetchAll('assoc');
$site_id = $this->request->data('site_id');
$requisition_number = $conn->execute("SELECT COUNT(*) AS requisitionsCount
FROM requisition
WHERE <primary_key> <= ? AND
site_id = ?",
[$last_requisition_id, $site_id]) + 1;
$conn->execute("UPDATE requisition
SET requisition_no = ?
WHERE <primary_key> <= ?",
[$requisition_number, $last_requisition_id]);
I know this code is not working. The $requisition_number will probably contain an array with the requisitionsCount as a value, but you can correct that.
Because you're using data that is already present in the database table you don't run the risk that two rows will get the same $requisition_number. The assumption here is that requisitions are never deleted.
I have this code, in which i have a if statement inside while loop, the problem is that i can't make it work because it always returns the same comment ID after the if statement is accomplished. I couldn´t found a solution. I'd appreciate any help. Thank you.
while($fila = mysql_fetch_assoc($resultado)) {
$archivos = $fila['archivos'];
$fecha = $fila['fecha'];
$comentarioID = $fila['id'];
$comentario = $fila['comentario'];
if(strlen($comentario) > 100){
$comentario = substr($comentario, 0, 100);
$vermas = '...Ver mas';
}
echo $comentario.$vermas;
}
First off MySQL is deprecated. Use MySQLi. You should also define $vermas outside of the if() statement, because if the strlen is less than or equal to 100 characters, then $vermas will be left undefined.
Try this...
while($fila = mysqli_fetch_array($resultado)) {
$archivos = $fila['archivos'];
$fecha = $fila['fecha'];
$comentarioID = $fila['id'];
$comentario = $fila['comentario'];
if(strlen($comentario) > 100){
$comentario = substr($comentario, 0, 100);
}
$vermas = "...<a href='' class='vermas' id='vermas_".$comentarioID."'>Ver mas</a>";
echo $comentario.$vermas;
}
I have some problem with getting results from VFP database results... The time which is taking by my php script is veeeery long - about 30 minutes, but it should be much shorter...
So there is the code which is responsible for taking database results:
$connect = odbc_connect("RIS", "", "", SQL_CUR_USE_DRIVER) or die("Error in connection ". odbc_errormsg($connect));
$array = array();
$info = array();
$from = $_GET['from'];
$to = $_GET['to'];
$rez_nap = odbc_exec($connect, "
select
pacientid as pac_pk,
datanapr,
ocered,
rtgapparat,
doctor as doc_naprav,
pk_na,
data_opis,
arst_opis as id_arst_opis
from
napravlenie
where
not arst_opis == '0000' and
not arst_opis == '' and
datanapr between {^".$from."} and {^".$to."}
") or die(odbc_errormsg());
while($row_nap = odbc_fetch_array($rez_nap))
{
echo "<pre>";
var_dump($row_nap);
$rez_opis = odbc_exec($connect, "
select
opis as opisanie,
doctor as doc_opis
from
opisanie_rtg
where
pacientid = '".$row_nap["pac_pk"]."' and
data = '".$row_nap["data_opis"]."' and
ocered = '".$row_nap["ocered"]."'
") or die(odbc_errormsg());
while($row_desc = odbc_fetch_array($rez_opis))
{
$op = explode('##$', $row_desc['opis']);
$opisanie = iconv( "cp1257", "utf-8", trim( addslashes($op[1]) ) );
$t_nr_i = substr($op[0], 12);
$ttt = explode("[", $t_nr_i);
if ( strlen($ttt[0]) > 12 )
{
$tt_nr_is = explode("-", $ttt[0]);
$t_nr_is_t = substr($tt_nr_is[0], 0, 8);
$t_nr_is_t_2 = substr($tt_nr_is[0], 8, 5);
$row_desc["nr_is"] = $t_nr_is_t."-".$t_nr_is_t_2;
}
else
{
$t_nr_is_t = substr($ttt[0], 0, 8);
$t_nr_is_t_2 = substr($ttt[0], 8, 5);
$row_desc["nr_is"] = $t_nr_is_t."-".$t_nr_is_t_2;
}
$row_desc['opis'] = $opisanie;
/////////////////////////////////////////////////////////////////////////////////////////////////////
$rez_apparat = odbc_exec($connect, "
select
kod,
gruppa,
imy,
prefiks
from
apparatura
where
kod = '".$row_nap["rtgapparat"]."'
") or die("Error in apparatura.dbf - ". odbc_errormsg($connect));
while($row_apparat = odbc_fetch_array($rez_apparat))
{
$rez_app_gruppa = odbc_exec($connect, "
select
gruppa,
prefiks,
apparati
from
apparat_gruppa
where
gruppa = '".$row_apparat["gruppa"]."'
") or die(error_logs("Error in apparat_gruppa.dbf - ".odbc_errormsg($connect)));
while($row_app_gruppa = odbc_fetch_array($rez_app_gruppa))
{
$rez_personal = odbc_exec($connect, "
select
s_name as doc_opis_name,
f_name as doc_opis_surname
from
personal
where
number = '".$row_nap["id_doc_opis"]."'
") or die(error_logs("Error in personal.dbf - ".odbc_errormsg($connect)));
while($row_personal = odbc_fetch_array($rez_personal))
{
$row_personal["doc_opis_name"] = iconv("cp1257", "utf-8", trim($row_personal["doc_opis_name"]));
$row_personal["doc_opis_surname"] = iconv("cp1257", "utf-8", trim($row_personal["doc_opis_surname"]));
$row_personal["filial"] = "r15";
$info[] = array_merge($row_nap, $row_desc, $row_apparat, $row_app_gruppa, $row_personal);
}
}
}
}
}
echo json_encode($info);
odbc_close($connect);
the database has about ~80-90k rows with data, and I'm using odbc driver to connect to VFP database, also the database is on the remote server... Any advices what I'm doing wrong? Because I can't figure what I'm doing wrong... Thanks for any advice and help!
P.S Also I need to convert that response into JSON and then save it to MySQL database...
EDIT 1
I have the second indexes:
pacientid, data_opis, ocered into the pacient table, opisanie and napravlenie
I'm trying to work out how to move the $sql_pay_det query outside of the $sql_pay loop (so in effect query on $rs_pay_det rather than creating a new $rs_pay_det for each iteration of the loop)
At the moment my code looks like:
//Get payroll transactions
$sql_pay = 'SELECT Field1, DescriptionandURLlink, Field5, Amount, Field4, PeriodName FROM tblgltransactionspayroll WHERE CostCentreCode = "'.$cc.'" AND SubjectiveCode = "'.$subj.'" AND PeriodNo = "'.$month.'"';
$rs_pay = mysql_query($sql_pay);
$row_pay = mysql_fetch_assoc($rs_pay);
while($row_pay = mysql_fetch_array($rs_pay))
{
$employee_name = $row_pay['Field1'];
$assign_no = $row_pay['DescriptionandURLlink'];
$pay_period = $row_pay['Field5'];
$mth_name = $row_pay['PeriodName'];
$amount = $row_pay['Amount'];
$total_amount = $total_amount + $amount;
$amount = my_number_format($amount, 2, ".", ",");
$sql_pay_det = 'SELECT ElementDesc, Amount, WTEWorked, WTEPaid, WTEContract, Payscale FROM tblpayrolldetail WHERE CostCentreCode = "'.$cc.'" AND SubjectiveCode = "'.$subj.'" AND AccountingPeriod = "'.$mth_name.'" AND EmployeeRef = "'.$assign_no.'"';
$rs_pay_det = mysql_query($sql_pay_det);
$row_pay_det = mysql_fetch_assoc($rs_pay_det);
while($row_pay_det = mysql_fetch_array($rs_pay_det))
{
$element_det = $row_pay_det['ElementDesc'];
$amount_det = $row_pay_det['Amount'];
$wte_worked = $row_pay_det['WTEWorked'];
$wte_paid = $row_pay_det['WTEPaid'];
$wte_cont = $row_pay_det['WTEContract'];
$payscale = $row_pay_det['Payscale'];
//Get band/point and annual salary where element is basic pay
if ($element_det =="3959#Basic Pay"){
$sql_payscale = 'SELECT txtPayscaleName, Salary FROM tblpayscalemapping WHERE txtPayscale = "'.$payscale.'"';
$rs_payscale = mysql_query($sql_payscale);
$row_payscale = mysql_fetch_assoc($rs_payscale);
$grade = $row_payscale['txtPayscaleName'];
$salary = "£" . my_number_format($row_payscale['Salary'], 0, ".", ",");
}
}
}
I've tried doing this:
//Get payroll transactions
$sql_pay = 'SELECT Field1, DescriptionandURLlink, Field5, Amount, Field4, PeriodName FROM tblgltransactionspayroll WHERE CostCentreCode = "'.$cc.'" AND SubjectiveCode = "'.$subj.'" AND PeriodNo = "'.$month.'"';
$rs_pay = mysql_query($sql_pay);
$row_pay = mysql_fetch_assoc($rs_pay);
//Get payroll detail recordset
$sql_pay_det = 'SELECT ElementDesc, Amount, WTEWorked, WTEPaid, WTEContract, Payscale, EmployeeRef FROM tblpayrolldetail WHERE CostCentreCode = "'.$cc.'" AND SubjectiveCode = "'.$subj.'" AND AccountingPeriod = "'.$mth_name.'"';
$rs_pay_det = mysql_query($sql_pay_det);
while($row_pay = mysql_fetch_array($rs_pay))
{
$employee_name = $row_pay['Field1'];
$assign_no = $row_pay['DescriptionandURLlink'];
$pay_period = $row_pay['Field5'];
$mth_name = $row_pay['PeriodName'];
$amount = $row_pay['Amount'];
$total_amount = $total_amount + $amount;
$amount = my_number_format($amount, 2, ".", ",");
//Query $rs_pay_det
$sql_pay_det2 = 'SELECT ElementDesc, Amount, WTEWorked, WTEPaid, WTEContract, Payscale FROM ('.$sql_pay_det.') tpd WHERE EmployeeRef = "'.$assign_no.'"';
$rs_pay_det2 = mysql_query($sql_pay_det2);
$row_pay_det2 = mysql_fetch_assoc($rs_pay_det2);
while($row_pay_det2 = mysql_fetch_array($rs_pay_det2))
{
$element_det = $row_pay_det2['ElementDesc'];
$amount_det = $row_pay_det2['Amount'];
$wte_worked = $row_pay_det2['WTEWorked'];
$wte_paid = $row_pay_det2['WTEPaid'];
$wte_cont = $row_pay_det2['WTEContract'];
$payscale = $row_pay_det2['Payscale'];
//Get band/point and annual salary where element is basic pay
if ($element_det =="3959#Basic Pay"){
$sql_payscale = 'SELECT txtPayscaleName, Salary FROM tblpayscalemapping WHERE txtPayscale = "'.$payscale.'"';
$rs_payscale = mysql_query($sql_payscale);
$row_payscale = mysql_fetch_assoc($rs_payscale);
$grade = $row_payscale['txtPayscaleName'];
$salary = "£" . my_number_format($row_payscale['Salary'], 0, ".", ",");
}
}
}
But I get an error on $row_pay_det2 saying that "mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource"
Your subquery syntax (... FROM "'.$rs_pay_det.'" ...) is wrong.
According to the manual - dev.mysql.com/doc/refman/5.0/en/from-clause-subqueries.html
Subqueries are legal in a SELECT statement's FROM clause. The actual
syntax is:
SELECT ... FROM (subquery) [AS] name ...
Try changing to-
$sql_pay_det2 = 'SELECT ElementDesc, Amount, WTEWorked, WTEPaid, WTEContract, Payscale FROM ('.$sql_pay_det.') tpd WHERE EmployeeRef = "'.$assign_no.'"';
Edit - Issue #2
You are only getting the 2nd row in your data set as you have duplicate code (mysql_fetch_assoc() & mysql_fetch_array()) that moves the internal data pointer ahead after the using mysql_fetch_assoc(). So when you do mysql_fetch_array() you will get every row except the 1st row.
//Get payroll transactions
...
$row_pay = mysql_fetch_assoc($rs_pay);
//Get payroll detail recordset
...
while($row_pay = mysql_fetch_array($rs_pay))
{
...
$row_pay_det2 = mysql_fetch_assoc($rs_pay_det2);
while($row_pay_det2 = mysql_fetch_array($rs_pay_det2))
{
...
}
}
}
You need to remove - $row_pay = mysql_fetch_assoc($rs_pay); & $row_pay_det2 = mysql_fetch_assoc($rs_pay_det2);
I have a PHP MySQL fetch while loop as shown below in my script:
$result2211 = mysql_query("select * from products where is_config = 'yes' ");
while($row2211 = mysql_fetch_assoc($result2211))
{
$sn = $row2211['sn'];
$allparrentselectq = mysql_query("SELECT * FROM parrentpro where parrentsn = $sn");
while($allparrentselect = mysql_fetch_assoc($allparrentselectq))
{
$childarr = unserialize($allparrentselect['childsn']);
$subpro = '{"catname":"'.$allparrentselect['childname'].'",';
$i = 0;
foreach($childarr as $childarr):
$subpro .= '"Pro'.$i++.'":"'.$childarr.'",';
endforeach;
$subpro1[] = substr($subpro, 0, -1)."}";
$subproa = "[".implode(",",$subpro1)."]";
}
$prodObj2 = new ProductDetails();
$prodObj2->productname = $row2211['productname'];
$prodObj2->price = $row2211['productprice'];
$prodObj2->discount = $row2211['discount'];
$prodObj2->discountprice = $row2211['discountprice'];
$prodObj2->imageURL = $row2211['productimageurl'];
$prodObj2->category = $row2211['productcat'];
$prodObj2->configurablepone = $subproa;
$prodObj2->configurable = 'yes';
array_push($totArr, $prodObj2);
}
In that I have a problem. I get the result as like below (JSON):
[
{
"productname":"Veg.Pizaa",
"price":"350",
"discount":"",
"discountprice":"350",
"imageURL":"http:\/\/farm8.staticflickr.com\/7154\/6694188161_9ee692d854_s.jpg",
"category":"Pizaa",
"configurablepone":[{"catname":"Extra","Pro0":"Extra 25g Cheese","Pro1":"Extra 75g Cheese"},"catname":"Nuts","Pro0":"Almonds","Pro1":"Peanuts","Pro2":"Pistachios"}],
"configurable":"yes"
},
{
"productname":"Core i7 Pc",
"price":"48000",
"discount":"2",
"discountprice":"47040",
"imageURL":"http:\/\/www.4to40.com\/images\/science\/Basic_Computer_Parts\/Computer.jpg",
"category":"Pc",
"configurablepone":[{"catname":"Extra","Pro0":"Extra 25g Cheese","Pro1":"Extra 75g Cheese"},{"catname":"Nuts","Pro0":"Almonds","Pro1":"Peanuts","Pro2":"Pistachios"},{"catname":"Harddisk","Pro0":"Segate 500Gb","Pro1":"Samsung 250Gb"},{"catname":"Ram","Pro0":"8Gb Ram","Pro1":"4Gb Ram","Pro2":"2Gb Ram"}],
"configurable":"yes"
}
]
But I need the result as like below:
[
{
"productname":"Veg.Pizaa",
"price":"350",
"discount":"",
"discountprice":"350",
"imageURL":"http:\/\/farm8.staticflickr.com\/7154\/6694188161_9ee692d854_s.jpg",
"category":"Pizaa",
"configurablepone":[{"catname":"Extra","Pro0":"Extra 25g Cheese","Pro1":"Extra 75g Cheese"},"catname":"Nuts","Pro0":"Almonds","Pro1":"Peanuts","Pro2":"Pistachios"}],
"configurable":"yes"
},
{
"productname":"Core i7 Pc",
"price":"48000",
"discount":"2",
"discountprice":"47040",
"imageURL":"http:\/\/www.4to40.com\/images\/science\/Basic_Computer_Parts\/Computer.jpg",
"category":"Pc",
"configurablepone":[{"catname":"Harddisk","Pro0":"Segate 500Gb","Pro1":"Samsung 250Gb"},{"catname":"Ram","Pro0":"8Gb Ram","Pro1":"4Gb Ram","Pro2":"2Gb Ram"}],
"configurable":"yes"
}
]
As you can see configurablepone JSON is getting repeated for every loop so I am getting the value of the first product in second product also but I need to seperate like below:
First Product As Like Below
"configurablepone":[{"catname":"Extra","Pro0":"Extra 25g Cheese","Pro1":"Extra 75g Cheese"},{"catname":"Nuts","Pro0":"Almonds","Pro1":"Peanuts","Pro2":"Pistachios"}]
Second Product As Like Below
"configurablepone":[{"catname":"Harddisk","Pro0":"Segate 500Gb","Pro1":"Samsung 250Gb"},{"catname":"Ram","Pro0":"8Gb Ram","Pro1":"4Gb Ram","Pro2":"2Gb Ram"}]
I have tried changing the loop but I haven't found any solutions. Kindly help me to solve this.
I think, your problem in line $subpro1[] = substr($subpro, 0, -1)."}";.
So, first call of this line save data from "Veg.Pizaa" into $subpro1[0].
Second call of this line save data from "Core i7 Pc" into $subpro1[1].
Then, line $subproa = "[".implode(",",$subpro1)."]"; merged all array elements.
Just Use unset($subpro1); after the array_push($totArr, $prodObj2);.
Below Is An example Source
Try This One This May Work
$result2211 = mysql_query("select * from products where is_config = 'yes' ");
while($row2211 = mysql_fetch_assoc($result2211))
{
$sn = $row2211['sn'];
$allparrentselectq = mysql_query("SELECT * FROM parrentpro where parrentsn = $sn");
while($allparrentselect = mysql_fetch_assoc($allparrentselectq))
{
$childarr = unserialize($allparrentselect['childsn']);
$subpro = '{"catname":"'.$allparrentselect['childname'].'",';
$i = 0;
foreach($childarr as $childarr):
$subpro .= '"Pro'.$i++.'":"'.$childarr.'",';
endforeach;
$subpro1[] = substr($subpro, 0, -1)."}";
$subproa = "[".implode(",",$subpro1)."]";
}
$prodObj2 = new ProductDetails();
$prodObj2->productname = $row2211['productname'];
$prodObj2->price = $row2211['productprice'];
$prodObj2->discount = $row2211['discount'];
$prodObj2->discountprice = $row2211['discountprice'];
$prodObj2->imageURL = $row2211['productimageurl'];
$prodObj2->category = $row2211['productcat'];
$prodObj2->configurablepone = $subproa;
$prodObj2->configurable = 'yes';
array_push($totArr, $prodObj2);
unset($subpro1);
}
while($allparrentselect = mysql_fetch_assoc($allparrentselectq))
{
$childarr = unserialize($allparrentselect['childsn']);
$subpro = '{"catname":"'.$allparrentselect['childname'].'",';
$i = 0;
foreach($childarr as $childarr):
$subpro .= '"Pro'.$i++.'":"'.$childarr.'",';
endforeach;
$subpro1[] = substr($subpro, 0, -1)."}";
$subproa = "[".implode(",",$subpro1)."]";
$subpro1 = array();
}
try this in second while loop