Populating Multiple Combo Boxes with PHP from MySQL database - php

I have a maximum of 100 selections (now 79) for the combo box, and have 79 of them. Each one stands for a question and is recorded to "questions" table in MySQL. The options are recorded in a table called "question_codes" and they stand for the field names associated with some questions. I tried 2 for loops within each other but I think that will overload the server because of 79*79 iterations. I also have a text field depending upon the selection with ajax, working properly. Number 0 field in the table "question_codes" is id and I don't use that. Here is my code.
$code_query="SELECT * FROM questions WHERE id='1'";
$question_query="SELECT * FROM questions WHERE id='2'";
$result_question_query=mysql_query($question_query,$conn);
$result_code_query=mysql_query($code_query,$conn);
$selected_query=mysql_query("SELECT * FROM question_codes");
while($row_selected=mysql_fetch_row($selected_query))
{
$column_count=count($row_selected);
}
while($row=mysql_fetch_array($result_question_query) && $row2=mysql_fetch_array($result_code_query))
for($i=1;$i<$column_count;$i++)
{
$db_q="q$i";
$fill=$row[$db_q];
$fill_code=$row2[$db_q];
print('<tr style="background:navy;color:white"><td width="60px">Question '.$i.'</td>
<td>
<select name="'.$db_q.'_code" id="'.$db_q.'_code" onchange="showQuestion(this)">
<option value="">Select a question</option>
for ($j=1;$j<$column_count;$j++)
{
$name=mysql_field_name($selected_query,$j);
if ($fill_code==$name)
{
$selected="selected";
}
else
{
$selected="";
}
print('<option value="'.$name.'" '.$selected.'>'.$name.'</option>');
}
print('</select>
</td>
<td><input type="text" value="'.$fill.'" name="'.$db_q.'" id="'.$db_q.'"></td></tr>');

There's probably a more elegant way to structure the database and PHP.
Perhaps something like this for SQL:
CREATE TABLE `questions` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`question` varchar(255) NOT NULL,
`answer` int(11) unsigned NOT NULL DEFAULT '0'
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
CREATE TABLE `question_options` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`question_id` int(11) unsigned NOT NULL DEFAULT '0',
`option` varchar(64) NOT NULL
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
... and this for the PHP ...
$q_sql = mysql_query("SELECT * FROM `questions`");
while ($q = mysql_fetch_row($q_sql)) {
echo '
<tr><td>Question '. $q['id'] .'</td>
<td><select name="q'. $q['id'] .'">';
$qo_sql = mysql_query("SELECT * FROM `question_options` WHERE `question_id` = '". $q['id'] ."'");
while ($qo = mysql_fetch_row($qo_sql)) {
$selected = ($q['answer'] == $qo['id']) ? ' selected' : '';
echo '
<option value="'. $qo['id'] .'"'. $selected .'>'. $qo['option'] .'</option>';
}
echo '
</select>
</td></tr>';
}
To tighten this further (this method can generate too many queries) ... make a single query instead, something like:
SELECT q.`question`, qo.*
FROM `question_options` as `qo`
LEFT JOIN `questions` as q
ON (q.`id` = qo.`question_id`)
ORDER BY qo.`question_id`
... then with a single while loop, check for a change in the question.

Related

get checked checkboxes from database

I am looknig to seek a way to get the tick boxes checked if they are assigned to the category in the database.
<?php
try{
// Selecting entire row from cat_list table
$results = $dbh->query("SELECT cat_id, cat_title FROM cat_list");
}catch(Exception $e) {
echo $e->getMessage();
die();
}
$category = $results->fetchAll(PDO::FETCH_ASSOC);
?>
<br>
<label><input type="checkbox" name="" class="selectall"/> Select all</label>
<div id="checkboxlist" >
<?php
foreach($category as $cat){
?>
<input type="checkbox" value="<?php echo $cat["cat_id"]; ?>" <?php echo ($cat['cat_id'] == 1) ? 'checked="checked"' : ''; ?> name="cat_no[]" id="box1"> <?php echo $cat["cat_title"]; ?></a><br>
<?php
}
So when I create the post I select from the available categories which are displayed as an array, the code above is taken from my edit post form so I want it retrieve the categories I assigned to it and tick the boxes.
I have 3 tables:
doc_list (Stores documents)
cat_list (Stores Categories)
cat_doc_link_table (stores the doc_id & cat_id from the previous two tables)
Here are how they are formed:
CREATE TABLE `cat_doc_link_table` (
`id` int(11) NOT NULL,
`link_cat_id` int(11) NOT NULL,
`link_doc_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE `cat_list` (
`cat_id` int(11) NOT NULL,
`cat_title` varchar(32) NOT NULL,
`cat_color` varchar(20) NOT NULL,
`cat_icon` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf16 AUTO_INCREMENT=66 ;
CREATE TABLE `doc_list` (
`doc_id` int(11) NOT NULL,
`doc_title` varchar(50) NOT NULL,
`doc_content` text NOT NULL,
`doc_created` datetime NOT NULL,
`user_id` int(11) NOT NULL,
`doc_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf16 AUTO_INCREMENT=295 ;
put the selected cat_id's in an array(). then use in_array() to check.
// query your db to return an array of cat_id's for the specified post.
$cats_array = array('123', '124', '156');
foreach($category as $cat){
// compare
if(in_array($cat['cat_id'], $cats_array)) {
// cat checked
}else{
// not checked
}
}

PHP something wrong with while loop

Okay so now its display results like 3 times in a row
$user_apps = mysql_query("SELECT a.name,a.download_url FROM user_apps as ua LEFT JOIN
apps as a ON (ua.app_id=a.app_id)
WHERE ua.user_id='$user_id'") or die(mysql_error());
while($raw = mysql_fetch_array($user_apps)){
$name = $raw['name'];
$url = $raw['download_url'];
echo $name;
echo "<br />";
echo $url;
}
Database Table Structure(since I am new to the site and did not know how to display the table structure I just exported the sql)
CREATE TABLE IF NOT EXISTS `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
CREATE TABLE IF NOT EXISTS `user_apps` (
`user_id` int(11) NOT NULL,
`app_id` int(11) NOT NULL,
KEY `user_id` (`user_id`,`app_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `apps` (
`app_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`description` text NOT NULL,
`icon` varchar(255) NOT NULL,
`download_url` varchar(255) NOT NULL,
`default` int(20) NOT NULL DEFAULT '0',
PRIMARY KEY (`app_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
I'v tried different Join types but that does not seem to work.
Used the join query for get the result check bellow example query
$user_apps = mysql_query("SELECT DISTINCT a.name,a.download_url FROM user_apps as ua LEFT JOIN apps as a ON (ua.app_id=a.app_id) WHERE ua.user_id='$user_id'") or die(mysql_error());
while($raw = mysql_fetch_array($user_apps)){
$name = $raw['name'];
$url = $raw['download_url'];
echo $name;
echo $url;
}
change the join type as per your requirement. the above query for only example
INNER JOIN: Returns all rows when there is at least one match in BOTH
tables
LEFT JOIN: Return all rows from the left table, and the matched rows
from the right table
RIGHT JOIN: Return all rows from the right table, and the matched
rows from the left table
FULL JOIN: Return all rows when there is a match in ONE of the tables
more about join click here
AND also check this http://blog.codinghorror.com/a-visual-explanation-of-sql-joins/
You have used single quotes in query at user_id='$user_id' .
Are you sure your user_id is char, varchar or text? Just print_r($user_apps) and check it has any records or not? If user_id is int,tinyin than remove single quote.

Create a new page on submit from database

I've created a chained menu using php and a database, following this tutorial.
The first table content a list of categories like :
CREATE TABLE IF NOT EXISTS `chainmenu_categories` (
`id_cat` int(4) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(40) NOT NULL,
PRIMARY KEY (`id_cat`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=12 ;
My second table, the type, like :
CREATE TABLE IF NOT EXISTS `type` (
`id_type` int(4) unsigned NOT NULL AUTO_INCREMENT,
`id_cat` int(4) unsigned NOT NULL,
`name` varchar(40) NOT NULL,
`destination` varchar(40) NOT NULL,
PRIMARY KEY (`id_type`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ;
I managed, once clicking on submit, to redirect to another page by that in my select.php:
var result = $("select#type option:selected").html();
$("#select_form").submit(function( event ) {
var the_url = $("#type").val();
window.location = the_url;
event.preventDefault();
});
and adding this on my select.class.php
public function ShowCategory()
{
$sql = "SELECT * FROM chainmenu_categories";
$res = mysql_query($sql,$this->conn);
$category = '<option value="0">choose...</option>';
while($row = mysql_fetch_array($res))
{
$category .= '<option value="' . $row['id_cat'] . $row['destination']. '">' . $row['name'] . '</option>';
}
return $category;
}
So now it redirects each time to a different page depending of the option choose from the menu, like http://mydomain.com//3 then 4, 5, 6, etc.
But as the page doesn't exist, it redirects to a dead link.
Can someone give me help to create these pages from the chained menu (or have some highlight)? and if possible, some pointer to create the admin interface to allow an admin to add the pages and categories to the chained menu?
I've been trying to start with something which look like:
PHP Code:
<?php require('db_config.php');
$stmt = $db->prepare('SELECT id_type, name FROM type WHERE id_cat=$_POST[id]');
$stmt->execute(array(':id_cat' => $_GET['name']));
$row = $stmt->fetch();
However, I don't know if this is good at all.
if(file_exists($filename.'.php'))
echo "file : " . $filename.'.php' . " is exist";
else
{
$file = fopen($filename.'.php',"w");
$code="here what U want to write inside the new page.php";
fwrite($file,$code);
fclose($file);
}

how can I make loop within a loop in codeigniter?

I have table faq_categories with following fields
CREATE TABLE IF NOT EXISTS `faq_categories` (
`catid` int(11) NOT NULL AUTO_INCREMENT,
`categoryname` varchar(37) NOT NULL,
`parentid` int(11) DEFAULT NULL,
`description` text NOT NULL,
`metatags` text NOT NULL,
`sorder` int(11) NOT NULL,
`visible` tinyint(4) NOT NULL,
`categoryphoto` varchar(255) NOT NULL,
PRIMARY KEY (`catid`),
KEY `parentid_fk` (`parentid`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=52 ;
In my php code I have the following code :
$query="SELECT * FROM categories";
$result=mysql_query($query);
$num=mysql_num_rows($result);
$i=0;
while ($i < $num) {
$id=mysql_result($result,$i,"id");
$name=mysql_result($result,$i,"name");
$parentid=mysql_result($result,$i,"parentid");
$categoryphoto=mysql_result($result,$i,"categoryphoto");
$sorder=mysql_result($result,$i,"sorder");
$visible=mysql_result($result,$i,"visible");
echo $id;
echo $name;
// THIS IS WHAT I DON'T KNOW HOW TO DO IN CODEIGNITER
// HOW TO GET THE CATEGORYNAME ON BASE ON PARENTID
if ($parentid) {
//echo $parentid;
$query1="SELECT name as parentname FROM categories WHERE id = ".$parentid;
echo mysql_result(mysql_query($query1),0,"parentname");
} else {
echo "Root Category";
}
How can I do this in codeigniter? If possible, I would like to avoid joins.
First: I think you can check Database class
Second: why don't you want use joins? If you hate it maybe you can use FROM table1,table2 :) IMHO lesser queries is better :)
EDIT
Install an sql-gui (e.g. phpMyAdmin, adminer...) and try some query! An example similar what you need:
SELECT *, catjoin.categoryname AS parentname
FROM categories
JOIN categories AS catjoin ON (catjoin.catid=categories.parentid)
You can extend catjoin.categoryname with IFNULL to returns ROOT category.

update with combo box

I have job insert page which is working fine.
I just build an update page in admin panel.
I'm not able to show screen short :(
I need to show the category as selected which is already in the job table.
let me show you the table details.This is the job table
CREATE TABLE IF NOT EXISTS `jobs` (
`job_id` int(11) NOT NULL AUTO_INCREMENT,
`job_title` varchar(99) NOT NULL,
`job_category` int(3) NOT NULL,
`job_location` varchar(33) NOT NULL,
`job_country` varchar(33) NOT NULL,
`job_salary` int(12) NOT NULL,
`job_reference` varchar(9) NOT NULL,
`job_contact_name` varchar(9) NOT NULL,
`job_description` text NOT NULL,
`job_requirments` text NOT NULL,
`job_companydetails` text NOT NULL,
`status` int(2) NOT NULL,
`date` date NOT NULL,
`featured` int(1) NOT NULL,
PRIMARY KEY (`job_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1091 ;
and this is the category table
CREATE TABLE IF NOT EXISTS `job_category` (
`category_id` int(11) NOT NULL AUTO_INCREMENT,
`category_name` varchar(25) NOT NULL,
PRIMARY KEY (`category_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=16 ;
I'm just showing data from job table for update.
but the thing is that I need to show JOB CATEGORY in the Combobox.
I think it is easy through like this
<select name="job_category">
<?php
$result = mysql_query("SELECT * FROM $category_tbl");
while($row = mysql_fetch_array($result))
{
echo "<option value=$row[category_id]> $row[category_name] </option>";
}
?>
</select>
but the thing is that I need to show selected category name which is in the job table
In the while loop you can have something like:
while($row = mysql_fetch_array($result)) {
echo "<option value='$row[category_id]'";
if($row['category_id'] === $rows['job_category']){
echo "selected='selected'";
}
echo "> $row[category_name] </option>";
}
job['job_category'] would contain the category id of the job you are currently displaying.
Hope this helps.
It is has some bug
I just fixed it
look the changes
$result = mysql_query("SELECT * FROM $category_tbl");
while($row = mysql_fetch_array($result))
{
echo "<option value='$row[category_id]'";
if($row['category_id'] === $rows['job_category'])
{
echo "selected='selected'";
}
echo "> $row[category_name] </option>";
}
thanks for your clue

Categories