Php: Group and add missed field - php

I have in a array a table like this:
cid plugin lang_id name father
1 Newspage 1 Actualidad 1
1 Newspage 2 News 1
2 Newspage 1 Tecnologia 1
2 Newspage 2 Tech 1
3 Newspage 1 Deportes 1
3 Newspage 2 Sports 1
4 Newspage 1 Ocio 1
In this example there are two languages (1:Spanish and 2:English) but admin can add more languages
I want do a "modify category" section and group it by CID with input boxes for each language if language its missed i want display a empty input for add the missed language.
Something like this:
http://i.imgur.com/fGCUgKc.png
My actual bad code its this:
$content = "<div class='catlist'>";
$content .= "<p>{$LANGDATA['L_NEWS_MODIFIED_CATS']}</p>";
$query = $db->select_all("categories", array ("plugin" => "Newspage", "lang_id" => 1));
while ($cat_grouped = $db->fetch($query)) {
$content .= "<form id='cat_mod' method='post' action=''>";
$content .= "<div>";
foreach ($langs as $lang) {
if ($lang['lang_id'] == $cat_grouped['lang_id']) {
$content .= "<label>{$lang['lang_name']}</label> <input type='text' name='{$lang['lang_id']}' value='{$cat_grouped['name']}' />";
} else {
$query2 = $db->select_all("categories", array ("plugin" => "Newspage", "cid" => "{$cat_grouped['cid']}", "lang_id" => "{$lang['lang_id']}"));
if($db->num_rows($query2) <= 0) {
$content .= "<label>{$lang['lang_name']}</label> <input type='text' name='{$lang['lang_id']}' value='' />";
} else {
$other_lang_cat = $db->fetch($query2);
$content .= "<label>{$lang['lang_name']}</label> <input type='text' name='{$lang['lang_id']}' value='{$other_lang_cat['name']}' />";
}
}
}
$content .= "<input type='hidden' name='cid' value='{$cat_grouped['cid']}' />";
$content .= "<input type='submit' name='ModCatSubmit' value='{$LANGDATA['L_NEWS_MODIFY']}' />";
$content .= "</div></form>";
}
$content .= "</div>";
This:
$db->select_all(...);
mean
$db->select_all("table", $WHERE, ...)
I want to retrieve all content in one query and do the work in php
My actual code its clearly very bad and assumed lang_id=1 exists for each entry and do few query's huh!
My old code use "GROUP BY cid" for the first query and not need to use "lang_id=1" but after a system upgrade that line give the error:
reported: Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column
and not want to use again that.
any idea the best way for do that?

I don't know what your database library is, so I'm writing a pseudo like code.
First, I would use a pagination to limit the database queries, for example 10/20 phrases for each page. So the query would be:
SELECT * FROM language_phrases WHERE cid IN (
SELECT DISTINCT cid FROM language_phrases WHERE plugin = 'Newspage'
LIMIT 0,10
)
then I would use the data from database first to get the cid values:
$cid = array();
$strings = array();
while($row = $db->fetch($result))
{
if(!in_array($cid,$row["cid"]))
{
$cid[] = $row["cid"];
}
$strings[]= array(
"cid" => $row["cid"],
"lang_id" => $row["lang_id"],
"name" => $row["name"],
"father" => $row["father"]
);
}
Then I would have the table and the distinct cid's in this page in my buffer. Then PHP will do the rest:
foreach($cid as $idx=>$key)
{
$values = array_filter($strings,function($d) use ($key) {
return $d["cid"] == $key;
});
// build the form with the $values array.
}

This problem give a headache but i made another version that work and only one query.
I will check later the Taha Paksu version/way (thanks!)
$content = "<div class='catlist'>";
$content .= "<p>{$LANGDATA['L_NEWS_MODIFIED_CATS']}</p>";
$query = $db->select_all("categories", array ("plugin" => "Newspage"), "ORDER BY cid");
$cats = [];
$catsids = [];
while ($cats_row = $db->fetch($query)) {
$cats[] = $cats_row;
$catsids[] = $cats_row['cid'];
}
$catsids = array_unique($catsids);
$foundit = 0;
foreach ($catsids as $catid) {
$content .= "<form id='cat_mod' method='post' action=''>";
$content .= "<div>";
foreach ($langs as $lang) {
foreach ($cats as $cat) {
if (($catid == $cat['cid']) && ($cat['lang_id'] == $lang['lang_id'])) {
$content .= "<label>{$lang['lang_name']}</label> <input type='text' name='{$lang['lang_id']}' value='{$cat['name']}' />";
$foundit = 1;
}
}
if ($foundit == 0) {
$content .= "<label>{$lang['lang_name']}</label> <input type='text' name='{$lang['lang_id']}' value='' />";
}
$foundit = 0;
}
$content .= "<input type='hidden' name='cid' value='$catid' />";
$content .= "<input type='submit' name='ModCatSubmit' value='{$LANGDATA['L_NEWS_MODIFY']}' />";
$content .= "</div></form>";
}

Related

Updating multiple rows with select option

Database:
+------+------+
| id |status|
+------+------+
| 50 | 2 |
+------+------+
| 51 | 0 |
+------+------+
| 52 | 1 |
+------+------+
As you can see there is a column named id and another column named status which indicates the current status of sth (2=done, 1=in work, 0 = open)
So I have done a little GUI where you can choose the current status through an select option input field, it also preselects the current record for status.
function generateSelect($name = '', $options = array(), $default = '') {
$html = '<select name="'.$name.'">';
foreach ($options as $option => $value) {
if ($value == $default) {
$html .= '<option value='.$value.' selected="selected">'.$option.'</option>';
} else {
$html .= '<option value='.$value.'>'.$option.'</option>';
}
}
$html .= '</select>';
return $html;
}
As I have mentioned each number in the database stands for a text with its status
$statusArray=array("Done" => "2", "In Work" => "1","Open" => "0");
This is what the generation of all the select option fields for every id looks like:
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$strStatus = generateSelect("stat", $statusArray, $row['status']);
echo '<tr><td>' . $row['id']. '</td><td>'.$strStatus.'</td></tr>';
What I am trying to do right now is that when the submit button is pressed it updates all status records.
What I have tried:
1.getting the selected one
function getSelected(){
$value="";
if($_POST['status']=="0")
$value="0";
else if($_POST['status']=="1")
$value="1";
else if($_POST['status']=="2")
$value="2";
else if($_POST['status']=="3")
$value="3";
return $value;
}
2. SQL statement where probably the problem is
$tmp = getSelected();
$sql = "UPDATE form SET status='$tmp' WHERE *";
Another option would be just saving the one edited, maybe with the onchange method from the select field?
Really appreciate every help I can get :) ty in advance for taking time to look throught the code.
UPDATE
ty for the quick answer and Extra Update #MarioZ
However it still doesnt seem rly to work. :/ maybe you can help me out there ^^
first worked fine with just $row['id'] because I want to be able to update more fields i have added ."['status']"
$strStatus = generateSelect($row['id']."['status']", $statusArray, $row['status']);
and also tried this for person, with no success then.
$personArray=array("Zivildiener" => "4", "Schmikl" => "3", "Poier" => "2","Dirnböck" => "1","Tom" => "0");
$strPerson = generateSelect($row['id']."['person']", $personArray, $row['person']);
and I have also added this which also worked fine, however only for status :/
foreach($_POST as $key => $value) {
$sql = "UPDATE form SET status='$value' WHERE id = $key";
$result = $conn->query($sql); }
Idk I honestly didnt really understand the foreach loop, but it worked somehow, you maybe need to know that there are more columns in the database which I didnt listen, but despite all this the first answer you gave worked perfectly, no clue how though :x so I would really appreciate your help again if you have some time :)
You need to pass the id of each row as the name of each select:
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$strStatus = generateSelect($row['id'], $statusArray, $row['status']);
echo '<tr><td>' . $row['id']. '</td><td>'.$strStatus.'</td></tr>';
So, when you retrieve the $_POST data you have the id as key and the value of the option as value:
foreach($_POST as $key => $value) {
$sql = "UPDATE form SET status='$value' WHERE id = $key";
}
You can adapt your function getSelected() in that loop to ge sure no other value is injected in the query.
FINAL UPDATE:
This is a way to do what you want to do, I've wrote to be easy to understand and apply to your code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form name="tasks" action="<?php $_SERVER['PHP_SELF']; ?>" method="post">
<?php
// Names of fields
$status_list[] = "open";
$status_list[] = "in work";
$status_list[] = "done";
$person_list[] = "John";
$person_list[] = "Bran";
$person_list[] = "Edd";
$task_list[50] = "Kill enemies";
$task_list[51] = "Avenge father";
$task_list[52] = "Sleep";
// Database conection
$db = new mysqli("localhost", "root", "", "test");
// Update database only if post
if(!empty($_POST)) {
foreach($_POST as $key => $value){
if($db->query("UPDATE change_status SET status = {$value['status']}, person = {$value['person']} WHERE id = $key ")) {
echo "<span>".$key." - UPDATED!</span>";
} else {
echo "<span>".$key." - FAILED!</span>";
}
}
}
// Get database
$query = $db->query("SELECT * FROM change_status");
// Draw the HTML content
$form = "";
while($result = $query->fetch_array()) {
$form .= '<div>';
$form .= '<span>'.$task_list[$result['id']].'</span>';
$form .= ' - ';
$form .= '<select name="'.$result['id'].'[status]">';
foreach($status_list as $key => $value) {
$form .= '<option value="'.$key.'"';
$form .= $result['status'] == $key? " selected" : "";
$form .= '>'.$value.'</option>';
}
$form .= '</select>';
$form .= '<select name="'.$result['id'].'[person]">';
foreach($person_list as $key => $value) {
$form .= '<option value="'.$key.'"';
$form .= $result['person'] == $key? " selected" : "";
$form .= '>'.$value.'</option>';
}
$form .= '</select></div>';
}
echo $form; // display html content
?>
<input type="submit">
</form>
</body>
</html>

Getting all array values in loop

So here's my code in getting an input from a user on how many questions (multiple choice) he/she would like to make:
Multiple choice: <input type = "text" name="MC"><br>
<input type = "submit" name = "confirm" value = "Confirm">
After that, this is the code of how many questions the system will generate:
<?php
if(isset($_POST['confirm'])){
$MC = $_POST['MC'];
echo "<form method = 'POST' name = 'items' action ='createquestions.php'>";
$items = 1;
for ($x = 1; $x <= $MC; $x++) {
echo "Question Number $items:"; echo "<input type = 'text' name = 'questions[]' style='width: 500px'><br><br>";
echo "A. "; echo "<input type = 'text' name = 'ans1[]'>";
echo "B. "; echo "<input type = 'text' name = 'ans2[]'><br>";
echo "C. "; echo "<input type = 'text' name = 'ans3[]'>";
echo "D. "; echo "<input type = 'text' name = 'ans4[]'><br>";
echo "Correct Answer: "; echo "<input type = 'text' name ='cans[]'><br><br>";
$items++;
}
echo "<input type ='submit' name = 'save' value = 'Save'>";
echo "</form>";
}
?>
<?php
The problem is that it will only save the last input of the user.
For example, I have inputted 2 in the Multiple choice: --textbox here--
This code will generate 2 questions, 8 choices, 2 cans = correct answer but it will only save the 2nd question, answers, and the correct answer. the system won't get the record of the 1st question, answer, and the correct answer.
Here is the code where I would insert it on the database:
<?php
if(isset($_POST['save'])){
$user_id = $_SESSION['id'];
$questions = $_POST['questions'];
$ans1 = $_POST['ans1'];
$ans2 = $_POST['ans2'];
$ans3 = $_POST['ans3'];
$ans4 = $_POST['ans4'];
$cans = $_POST['cans'];
foreach($questions as $q){
echo "<input type = 'hidden' value = '$q'>";
}
require_once('xcon.php');
$query = "INSERT INTO mcq (mc_id, user_id, questions, ans1, ans2, ans3, ans4, cans)
VALUES ('NULL','$user_id','$q','$ans1','$ans2','$ans3','$ans4','$cans')";
$result = mysql_query($query);
if($result){
echo 'Insert Success!';
}
else{
echo 'Error';
}
}
?>
When you save you should be running through a loop again. Try this maybe?
<?php
if(isset($_POST['save'])){
$user_id = $_SESSION['id'];
require_once('xcon.php');
foreach ($_POST['questions'] as $key => $question){
$ans1 = $_POST['ans1'][$key];
$ans2 = $_POST['ans2'][$key];
$ans3 = $_POST['ans3'][$key];
$ans4 = $_POST['ans4'][$key];
$cans = $_POST['cans'][$key];
echo "<input type = 'hidden' value = '$question'>";
$query = "INSERT INTO mcq (mc_id, user_id, questions, ans1, ans2, ans3, ans4, cans)
VALUES ('NULL','$user_id','$question','$ans1','$ans2','$ans3','$ans4','$cans')";
$result = mysql_query($query);
if($result){
echo 'Insert Success!<br>';
}else{
echo 'Error<br>';
}
}
}
?>
According to this post you should use:
echo "Question Number $items:"; echo "<input type = 'text' name = 'questions' style='width: 500px'><br><br>";
echo "A. "; echo "<input type = 'text' name = 'ans[]'>";
echo "B. "; echo "<input type = 'text' name = 'ans[]'><br>";
echo "C. "; echo "<input type = 'text' name = 'ans[]'>";
echo "D. "; echo "<input type = 'text' name = 'ans[]'><br>";
echo "Correct Answer: "; echo "<input type = 'text' name ='cans'><br><br>";
And this:
$ans1 = $_POST['ans'][0];
$ans2 = $_POST['ans'][1];
$ans3 = $_POST['ans'][2];
$ans4 = $_POST['ans'][3];
Explanation
You only need to post ans[] repeatedly , and not
ans1[], ans2[], ans3[]... in order to get an array like
$_POST['ans'][0], $_POST['ans'][1]...
or you can use
ans1, ans2, ans3
(without brackets []) to read as
$_POST['ans1'], $_POST['ans2'], $_POST['ans3']...
You are using element naming in a strange way, you are using array, but still use numbers. Try generating like this:
for ($x = 0; $x <= $MC; $x++) {
echo "<input type = 'text' name = 'questions[$i]'>";
echo "A. <input type = 'text' name = 'ans[$i][A]'>";
echo "B. <input type = 'text' name = 'ans[$i][B]'><br>";
echo "C. <input type = 'text' name = 'ans[$i][C]'>";
echo "D. <input type = 'text' name = 'ans[$i][D]'><br>";
echo "Correct Answer: <input type = 'text' name ='cans[$i]'><br><br>";
}
Then you'll get the following results in your $_POST:
[
"questions" => [
0 => "question1",
...
]
"ans" => [
0 => [
"A" => "answer A",
"B" => "answer B",
"C" => "answer C",
"D" => "answer D",
]
...
]
"cans" => [
0 => "A",
....
]
]
Which is easily processed with a foreach:
foreach ($_POST['questions'] as $key => $question) {
// $question == 'question1';
$answers = $_POST['ans'][$key]; // array of answers
$solution = $_POST['cans'][$key];
}

How to pass values to $_GET from a drop-down list from a table

the situation I am facing is like that:
I read data from a database and dump them into a table in a webpage. And then, according to a column's value, show a drop-down list or not. And write the value from the drop-down list back into the database.
I use ...Submit, but the $_GET has no values about the drop-down list.
I list the whole code set here.
Any help is highly appreciated!
$GCdataSQL = "select * from table_name";
$GCdata = new Query($GCdataSQL);
$table = "<form method='GET'><table class='datatable table table-condensed ' id='query-data'><thead><tr>";
$ColName = array('col1','col2','col3','col4', 'col5', 'col6', 'col7', 'col8');
foreach ($ColName as $Name){
$table .= "<th>$Name</th>";
}
$table .= "</tr></thead><tbody>";
while ($GCdataRow = $GCdata->fetchRow()){
$emplid = $GCdataRow['emplid'];
$term = $GCdataRow['term'];
$handled = $GCdataRow['handled'];
if ($GCdataRow['code'] == 'UNKNOW' || $GCdataRow['code'] == 'Not Repeated'){$GCdataRow['code']= '';}
if ($GCdataRow['local_action'] !== $GCdataRow['new_action']){
$table .= "<tr bgcolor= 'LightPink'>";
}
else {
$table .= "<tr>";
}
foreach($GCdataRow as $key=>$value){
if ($key == 'emplid'){
$table .="<td><a href='link' target = '_blank'>$value</a></td>";
}
else if ($key == 'new_action'){
$table .="<td><a href='link' target = '_blank'>$value</a></td>";
}
else if ($key == 'handled' && $handled == 'Not Reviewed'){
$table .="<td><select name = 'handlecode'><option value = 'Not Reviewed'>Not Reviewed</option><option value = 'Handled by Script'>Handled by Script</option><option value = 'Handled Manually'>Handled Manually</option><option value = 'Leave It'>Leave It</option></select></td>";
}
else {
$table .= "<td>".htmlentities($value)."</td>";
}
}
$table .= "</tr>";
$loopcount++;
}
if(isset($table)) {$table .= "</tbody></table>";}
echo $table;
echo "<button type='submit' class = 'btn btn-primary' style = 'position: absolute; left:50%;' >Submit</button></form>";
finally I changed the form method to POST, and everything is fine! Now the values are in $_POST, and I could use them to insert into the database!
Thank you!

Jquery post method - Auto populate two dropdown fields onchange

I have a dropdown select called 'Select Company' on change of which i would auto-populate the 'Locations' dropdown by fetching the company id from the table. Below is my PHP code that returns the results after querying for both the fields that need to be auto-populated :
$output = array();
if(!empty($data))
{
$out = "<select name='location' id='location'>";
$out .="<option value=''>Select a location</option>";
for($i=0;$i<count($data);$i++)
{
$out .="<option value='".$data[$i]['id']."'>".$data[$i]['location']."</option>";
}
$out .= "</select>";
}
else{
$out = "<select name='location' id='location'>";
$out .="<option value=''>No locations added</option>";
$out .="</select>";
}
$sql2 = "select id,username from client24_bcpfm.users where cid = '$cid'";
$data2 = return_results($sql2);
if(!empty($data2))
{
$out2 = "<select name='username' id='username'>";
$out2 .="<option value=''>Select a User</option>";
for($i=0;$i<count($data2);$i++)
{
$out2 .="<option value='".$data2[$i]['id']."'>".$data2[$i]['username']."</option>";
}
$out2 .= "</select>";
}
else{
$out2 = "<select name='username' id='username'>";
$out2 .="<option value=''>No Users</option>";
$out2 .="</select>";
}
$output['0'] = $out;
$output['1'] = $out2;
print_r(json_encode($output));
Part where i am stuck , using the jquery to iterate the two different arrays for two different fields :
$.post('locations2.php',{cid:cid},
function(data)
{
data = $.parseJSON(data);
$("#location").html(data);
return;
});
Please let me know how to return the php values for 2 dropdowns and also iterate through them in the front end jquery .
If you want to return an array, you can also do it like this:
echo json_encode(array(
"out1" => $out,
"out2" => $out2));
and get the values in jquery like this:
$.post('locations2.php',{cid:cid},
function(data)
{
data = $.parseJSON(data);
//first array
$("#location").html(data.out1);
//second array
$("#location").html(data.out2);
return;
});

PHP JQuery Checkbox Array - Selecting only 1 value

Following is an ajax post page which renders the checkboxes on run-time. I am facing issue while writting the script for select all button, when I click on the button only 1 value is getting selected not the entire array:
<?php
session_start();
error_reporting(E_ALL);
ini_set("display_errors", 1);
include("../includes/functions.php");
if(isset($_REQUEST['t']))
{
$td = $_REQUEST['t'];
$t = split(",",$td);
$all = "";
$box_in_row = 0 ;
$this_box="<table border=0><tr>";
foreach($t as $table)
{
$this_box = "<td><h3>$table</h3>";
$result = mysql_query("SHOW FULL COLUMNS FROM $table FROM prfxcom1_prfx");
$options = "";
while($r = mysql_fetch_object($result))
{
if(!empty($r->Comment))
{
$options .= "<br><input type=checkbox name=\"".$table."[]\" value='$r->Field' id=\"$table\">" . $r->Field;
}
}
if($table == "transfer_req")
{
$options .= "<br><input type=checkbox name=\"".$table."[]\" value='Net Profit' id=\"$table\">NetProfit";
}
$this_box .= $options;
// Button
$click = "$('#$table').attr('checked', 'checked')";
$button = "<br /><input style='margin-top:10px;' type='button' name='$table_button' id='$table_button' value=' Select All ' onclick=\"$click\"/>";
$all .= "<div class='tblBox'>".$this_box.$button."</div></td>";
}
//$all = "<table class=\"listing form\" cellpadding=\"0\" cellspacing=\"0\">".$all."</table>";
echo $all;
}
?>
Issue is faced in the line:
$click = "$('#$table').attr('checked', 'checked')";
Please suggest, I am stuck on this.
Thanks,
Hardik
WHAT???
$click = "$('#$table').attr('checked', 'checked')";
How can you write Javascript in the middle of a PHP file? It needs to be in script tags but even then PHP runs at the server and will not render your Javascript for you.
Add script tags, change your ID's to separate ones and give them the same class like tableClassName, and then write the following.
$(function(){
$('.tableClassName').attr('checked', 'checked')";
});
Ignoring the many issues with the code and simply answering the question:
You need to refer to the checkboxes using a class name not a ID (you have given them all the same ID)
For these lines: $options .= "<br><input type=checkbox name=\"".$table."[]\" value='$r->Field' id=\"$table\">" . $r->Field;
Change to: $options .= "<br><input type=checkbox name='" . $table . "[]' value='" . $r->Field ."' class='" . $table . "'>" . $r->Field;
For this line: $click = "$('#$table').attr('checked', 'checked')"; use single quotes or escape the $
Change to: $click = '$("."'.$table.'").attr("checked", "checked")';

Categories