Here this line $find_cond = str_replace('|',' ',$rem_exp); returns 225 and 245 number.
I want to get the records based on these two id number. But this below code returns the output repeatedly.
How do I properly put the while loop code inside a foreach?
foreach($arr_val as $key => $val)
{
$c_subsubtopic = str_replace('-','_',$subsubtopic);
$rem_exp = $val[$c_subsubtopic];
$find_cond = str_replace('|',' ',$rem_exp);
$sql = "SELECT a.item_id, a.item_name, a.item_url, b.value_url, b.value_name, b.value_id FROM ".TBL_CARSPEC_ITEMS." a, ".TBL_CARSPEC_VALUES." b WHERE a.item_id = b.item_id AND a.item_url = '".$subsubtopic."' AND value_id = '".$find_cond."' AND a.status = '1'";
while($r = mysql_fetch_array(mysql_query($sql)))
{
echo $r['value_name'];
}
}
The problem is that you are redoing the sql query at every iteration of the loop, thus resetting the results internal pointer, so you keep fetching the same array.
$res = mysql_query($sql)
should be on it's own line before the while loop, and then
while($r = msql_fetch_array($res))
This will properly increment through the $res list.
Try this and you are done
As you were getting may get multiple id in the string after replacing it so its better to use IN the where clause
foreach($arr_val as $key => $val)
{
$c_subsubtopic = str_replace('-','_',$subsubtopic);
$rem_exp = $val[$c_subsubtopic];
$find_cond = str_replace('|',',',$rem_exp);
$sql = "SELECT a.item_id, a.item_name, a.item_url, b.value_url, b.value_name, b.value_id FROM ".TBL_CARSPEC_ITEMS." a, ".TBL_CARSPEC_VALUES." b WHERE a.item_id = b.item_id AND a.item_url = '".$subsubtopic."' AND value_id IN('".$find_cond."') AND a.status = '1'";
while($r = mysql_fetch_array(mysql_query($sql)))
{
echo $r['value_name'];
}
}
Related
I have Three queries execute at the same time and its declared one object $sql.
In result "Product" Array Actually Four Record display only one Record,Three Record is not Display. In "total" Array Percentage Value Display null.
I have need this Result
{"success":1,"product":[{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-06 00:00:00.000000","timezone_type":3,"timezone":"UTC"},"subject":"MATHS","ExamName":"WT","Marks":"30.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-07 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"15.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-10-08 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"25.00","TotalMarks":"30.00","PassingMarks":"10"},{"std_Name":"VIVEK SANAPARA","Standard":"12-SCI-CE","Division":"A","ExamDate":{"date":"2016-11-22 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Kolkata"},"subject":"PHYSICS","ExamName":"WT","Marks":"25.00","TotalMarks":"30.00","PassingMarks":"10"},],"total":[{"Marks":"30.00","TotalMarks":"30.00","Percentage":"79.166600"}],"exam":[{"ExamName":"WT"}]}
I have show Error Image below the Code. In image only one record display but in above resulr Four Record and Percentage Value Display null in image.
Marks.php
if(isset($_REQUEST["insert"]))
{
$reg = $_GET['reg'];
$sql = "select b.std_Name,d.Standard,e.Division,a.ExamDate,f.subject,a.ExamName,a.Marks,a.TotalMarks,a.PassingMarks
from Marks_mas a inner join std_reg b on a.regno=b.regno
INNER JOIN Subject_mas as f ON a.Subject_ID = f.Subject_ID
inner join StandardMaster d on a.standard = d.STDID
inner join DivisionMaster e on a.Division = e.DivisionID
where a.RegNo= '$reg' order by a.ExamDate; select sum(a.Marks) as Marks,sum(a.TotalMarks) as TotalMarks, sum(a.Marks)/sum(a.TotalMarks) * 100 as Percentage
from Marks_mas a
where a.RegNo= '$reg'; select distinct ExamName From Marks_mas;";
$stmt = sqlsrv_query($conn, $sql);
$result = array();
if (!empty($stmt)) {
// check for empty result
if (sqlsrv_has_rows($stmt) > 0) {
$stmt = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC);
$product = array();
$product["std_Name"] = $stmt["std_Name"];
$product["Standard"] = $stmt["Standard"];
$product["Division"] = $stmt["Division"];
$product["ExamDate"] = $stmt["ExamDate"];
$product["subject"] = $stmt["subject"];
$product["ExamName"] = $stmt["ExamName"];
$product["Marks"] = $stmt["Marks"];
$product["TotalMarks"] = $stmt["TotalMarks"];
$product["PassingMarks"] = $stmt["PassingMarks"];
$total = array();
$total["Marks"] = $stmt["Marks"];
$total["TotalMarks"] = $stmt["TotalMarks"];
$total["Percentage"] = $stmt["Percentage"];
$exam = array();
$exam["ExamName"] = $stmt["ExamName"];
// success
$result["success"] = 1;
// user node
$result["product"] = array();
$result["total"] = array();
$result["exam"] = array();
array_push($result["product"],$product);
array_push($result["total"],$total);
array_push($result["exam"],$exam);
// echoing JSON response
echo json_encode($result);
} else {
// no product found
$result["success"] = 0;
$result["message"] = "No product found";
// echo no users JSON
echo json_encode($result);
}
//sqlsrv_free_stmt($stmt);
sqlsrv_close($conn); //Close the connnection first
}
}
This is Error:
enter image description here
just put below percentage calculation section in brackets and try
(sum(a.Marks)/sum(a.TotalMarks) * 100) as Percentage
In your sql query there is no field with name "Percentage" so that is why you are getting this error
$sql = "select b.std_Name,d.Standard,e.Division,a.ExamDate,f.subject,a.ExamName,a.Marks,a.TotalMarks,a.PassingMarks, Percentage missing "
I'm trying to fetch a list of values from MySQL table using query1 and then use them in query2 to fetch values. Query1 gives 4 values however Query2 gives output matching the last value of Query1.
Following is my controller code
public function example_ctl(){
$data['result'] = $this->some_model->example();
}
Following is my model code
public function example() {
$query = "select m.queue_id from agent_queue_mapping_table as m, user_table as u where u.id=m.user_id and m.company_id = ".$this->session->userdata('user_comp_id')." and u.id = ".$this->session->userdata('user_id');
$res = $this->db->query($query);
foreach ($res->result_array() as $value) {
$queue_ids = implode(',', $value);
}
$query_ticket = "select * from tickets_table where company_id = ".$this->session->userdata('user_comp_id')." and ticket_status = 'New' and queue_id IN (".$queue_ids.") ORDER BY id DESC LIMIT 3";
$res_ticket = $this->db->query($query_ticket);
return $res_ticket->result_array();
}
I'm not able to understand where I'm going wrong. Please help.
try changing your code into this
<?php
$queue_id = array();
foreach ($res->result_array() as $value) {
$queue_id[] = $value;
}
$queue_id = implode(",",$value);
?>
$queue_id is overridden inside the loop each time loop executes that is why you get last value
This is how I fixed this issue.
$query = "select m.queue_id from agent_queue_mapping_table as m, user_table as u where u.id=m.user_id and m.company_id = ".$this->session->userdata('user_comp_id')." and u.id = ".$this->session->userdata('user_id');
$res = $this->db->query($query);
foreach ($res->result_array() as $value) {
$queue_ids[] = $value['queue_id'];
}
$queue_id = implode(',', $queue_ids);
$query_ticket = "select * from tickets_table where company_id = ".$this->session->userdata('user_comp_id')." and ticket_status = 'New' and queue_id IN (".$queue_id.") ORDER BY id DESC LIMIT 3";
$res_ticket = $this->db->query($query_ticket);
return $res_ticket->result_array();
In the below code i want to join or implode all arrays of $trackersurl in a single line. i am getting the results in different lines, so i want to join in a single line.
Can anyone help me out?
I am searching results in stackoverflow, but could not follow.
My code is in below:
$sql = "SELECT * FROM announce WHERE torrent = $id ORDER BY seeders DESC";
$query = #mysql_query($sql);
while ($result = #mysql_fetch_array($query)) {
$trackersurl1 = $result['url'];
$trackersurl2 = "&tr=".$trackersurl1;
$trackersurl = array($trackersurl2);
}
Results of [var.trackersurl] in html page is below:
&tr=http:ajgdsjhg/ann
&tr=udp://iuysidfu/ann
&tr=udp:wutefghgw/ann
&tr=http://sdhgsjdhgj/ann
I want to join them in a single line below
&tr=http:ajgdsjhg/ann&tr=udp://iuysidfu/ann&tr=udp:wutefghgw/ann&tr=http://sdhgsjdhgj/ann
You should be careful of sql injection.
Are you looking to create an array['trackers'] with a string of all the trackers for a magnet link?
<?php
$sql = "SELECT * FROM announce WHERE torrent = ".mysql_real_escape_string($id)." ORDER BY seeders DESC";
$query = mysql_query($sql);
$tracker = null;
if(mysql_num_rows($query)>=1){
while ($result = mysql_fetch_array($query)) {
$tracker .= "&tr=".$result['url'];
}
}
$tracker = array('trackers'=>$tracker);
//$tracker['trackers'] = "&tr=a.com&tr=b.com&tr=c.com";
?>
Try this code
$newArray=array();
while ($result = #mysql_fetch_array($query)) {
$trackersurl1 = $result['title'];
$newArray[] = "&tr=".$trackersurl1;
}
$urlString=implode('',$newArray);
I'm trying to mesh the below mysql query results into a single json object, but not quite sure how to do it properly.
$id = $_POST['id'];
$sql = "SELECT contracts.po_number, contracts.start_date, contracts.end_date, contracts.description, contracts.taa_required, contracts.account_overdue, jobs.id AS jobs_id, jobs.job_number, companies.id AS companies_id, companies.name AS companies_name
FROM contracts
LEFT JOIN jobs ON contracts.job_id = jobs.id
LEFT JOIN companies ON contracts.company_id = companies.id
WHERE contracts.id = '$id'
ORDER BY contracts.end_date";
$sql2 = "SELECT types_id
FROM contracts_types
WHERE contracts_id = '$id'";
//return data
$sql_result = mysql_query($sql,$connection) or die ("Fail.");
$arr = array();
while($obj = mysql_fetch_object($sql_result)) { $arr[] = $obj; }
echo json_encode($arr); //return json
//plus the selected options
$sql_result2 = mysql_query($sql2,$connection) or die ("Fail.");
$arr2 = array();
while($obj2 = mysql_fetch_object($sql_result2)) { $arr2[] = $obj2; }
echo json_encode($arr2); //return json
Here's the current result:
[{"po_number":"test","start_date":"1261116000","end_date":"1262239200","description":"test","taa_required":"0","account_overdue":"1","jobs_id":null,"job_number":null,"companies_id":"4","companies_name":"Primacore Inc."}][{"types_id":"37"},{"types_id":"4"}]
Notice how the last section [{"types_id":"37"},{"types_id":"4"}] is placed into a separate chunk under root. I'm wanting it to be nested inside the first branch under a name like, "types".
I think my question has more to do with Php array manipulation, but I'm not the best with that.
Thank you for any guidance.
Combine the results into another structure before outputting as JSON. Use array_values to convert the type IDs into an array of type IDs. Also, fix that SQL injection vulnerability. Using PDO, and assuming the error mode is set to PDO::ERRMODE_EXCEPTION:
$id = $_POST['id'];
try {
$contractQuery = $db->prepare("SELECT contracts.po_number, contracts.start_date, contracts.end_date, contracts.description, contracts.taa_required, contracts.account_overdue, jobs.id AS jobs_id, jobs.job_number, companies.id AS companies_id, companies.name AS companies_name
FROM contracts
LEFT JOIN jobs ON contracts.job_id = jobs.id
LEFT JOIN companies ON contracts.company_id = companies.id
WHERE contracts.id = ?
ORDER BY contracts.end_date");
$typesQuery = $db->prepare("SELECT types_id
FROM contracts_types
WHERE contracts_id = ?");
$contractQuery->execute(array($id));
$typesQuery->execute(array($id));
$result = array();
$result['contracts'] = $contractQuery->fetchAll(PDO::FETCH_ASSOC);
$result['types'] = array_values($typesQuery->fetchAll(PDO::FETCH_NUM));
echo json_encode($result); //return json
} catch (PDOException $exc) {
...
}
If $contractQuery returns at most one row, change the fetch lines to:
$result = $contractQuery->fetch(PDO::FETCH_ASSOC);
$result['types'] = array_values($typesQuery->fetchAll(PDO::FETCH_NUM));
It would seem like you'd be better served by consolidating the two queries with a JOIN at the SQL level. However, assuming the two arrays have equal length:
for ($x = 0, $c = count($arr); $x < $c; $x++) {
if (isset($arr2[$x])) {
$arr[$x] += $arr2[$x];
}
}
echo json_encode($arr);
Edit: you would need to change from mysql_fetch_object to mysql_fetch_assoc for this to work properly.
Why are you using 2 distinct arrays ? I would simply add the rows of the 2nd query in $arr instead of $arr2. This way, you end up with a single array containing all rows from the 2 queries.
Suppose I have a while loop like:
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
}
then if first query return 5 results i.e 1-5 and second query returns 3 results than if i want to echo out second query it gives me like this..........
111112222233333
than how can i fix to 123 so that the second while loop should execute according to number of times allowed by me........!! how can i do that.........!!
I'm not sure I 100% understand your question - it's a little unclear.
It's possible you could solve this in the query with a GROUP BY clause
$sql_2 = mysql_query("SELECT id FROM secondtable WHERE id != $id GROUP BY id");
But that would only work if you need just secondtable.id and not any of the other columns.
When you say "number of time allowed by me" do you mean some sort of arbitrary value? If so, then you need to use a different loop mechanism, such as Greg B's solution.
Do you want to explicitly limit the number of iterations of the inner loop?
Have you considered using a for loop?
$sql = mysql_query("SELECT * FROM tablename");
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
for($i=0; $i<3; $i++){
$ro = mysql_fetch_array($sql_2);
$id2 = $ro["id2"];
echo $id2;
}
}
Your first while loop is iterating over all 5 results, one at a time.
Your second while loop is iterating over each of the 5 results, producing it's own set of results (i.e. 3 results for each of the 5 iterations, totaling 15 results).
I believe what you are trying to do is exclude all IDs found in your first loop from your second query. You could do that as follows:
$sql = mysql_query("SELECT * FROM tablename");
$exclude = array();
while($row = mysql_fetch_array($sql)) {
array_push($exclude, $row['id']);
}
// simplify query if no results found
$where = '';
if (!empty($exclude)) {
$where = sprintf(' WHERE id NOT IN (%s)', implode(',', $exclude));
}
$sql = sprintf('SELECT * FROM secondtable%s', $where);
while($row = mysql_fetch_array($sql_2)) {
$id2 = $row["id2"];
echo $id2;
}
$sql = mysql_query("SELECT * FROM tablename");
$tmp = array();
while($row = mysql_fetch_array($sql)){
$id = $row["id"];
if(!in_array($id, $tmp)) {
$sql_2 = mysql_query("SELECT * FROM secondtable WHERE id != $id ");
while($ro = mysql_fetch_array($sql_2)){
$id2 = $ro["id2"];
echo $id2;
}
$tmp[] = $id;
}
}
Saving all queried $id's in an array to check on the next iteration if it has already been queried. I also think that GROUPing the first query result would be a better way.
I agree with Leonardo Herrera that it's really not clear what you're trying to ask here. It would help if you could rewrite your question. It sounds a bit like you're trying to query one table and not include id's found in another table. You might try something like:
SELECT * FROM secondtable t2
WHERE NOT EXISTS (SELECT 1 FROM tablename t1 WHERE t1.id = t2.id);