how can I make loop within a loop in codeigniter? - php

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.

Related

select from 2 table and make ordering them

first, sorry for my English ...
what i want is to select from two SQL tables and then make them in a specific order , like in forums ...
i have two table, topic and users, i want to select from both of them a putt author info next to his topic
here is the SQL of Topic and users
CREATE TABLE IF NOT EXISTS `topics` (
`id` int(11) NOT NULL,
`id2` int(11) NOT NULL,
`title` varchar(256) NOT NULL,
`message` longtext NOT NULL,
`author_id` int(11) NOT NULL,
`timestamp` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `users` (
`id` bigint(20) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`avatar` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
and the php code might look like this
<?php
$sql = mysql_query(' MySQL query ... ');
while($row = mysql_fetch_array($sql)) {
echo '<p>'.$row['username']'<br>';
echo $row['message'].'<br></p>';
}
?>
is there any way to do it ??
As I understood, what you are looking for is the correct SQL statement to execute. The following simple solution will.
<?php
$sql = mysql_query('SELECT users.username, topics.message FROM `users` INNER JOIN topics ON topics.author_id = users.id');
while($row = mysql_fetch_array($sql)) {
echo '<p>'.$row['username']'<br>';
echo $row['message'].'<br></p>';
}
?>
SELECT * FROM `users` INNER JOIN topics ON topics.author_id = users.id'

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.

Get a record with maxid and condition in mysql in yii, but sometime it get second record?

my table:
CREATE TABLE IF NOT EXISTS `the_kho_chi_tiet_with_id` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`ngay_thang` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`ma_phieu` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
`id_san_pham` int(11) NOT NULL,
`id_kho` int(11) NOT NULL,
`khoi_luong_nhap` double NOT NULL,
`so_luong_nhap` int(11) NOT NULL,
`khoi_luong_xuat` double NOT NULL,
`so_luong_xuat` int(11) NOT NULL,
`khoi_luong_ton` double NOT NULL,
`so_luong_ton` int(11) NOT NULL,
`kho_du_tru` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
)
PHP code:
$sql = "SELECT so_luong_ton, khoi_luong_ton, kho_du_tru FROM the_kho_chi_tiet_with_id WHERE id_kho = $id_kho and id_san_pham = $id_san_pham ORDER by id DESC LIMIT 1";
$command=$connection->createCommand($sql);
$dataReader=$command->queryAll();
if($dataReader!=null)
{
foreach($dataReader as $row)
{
.................
}
}
**Get a record with maxid and condition in mysql in yii, *but sometime it get second record* !?**
Please check with the below, hope it works!..if not please tell...
$id_kho=373;//sample value declaration
$id_san_pham=1;//sample value declaration
$select="select max(id) as id,so_luong_ton, khoi_luong_ton, kho_du_tru from
the_kho_chi_tiet_with_id where users_ref_id=".$id_kho." and
status=".$id_san_pham;
$command = Yii::app()->db->createCommand($select)->queryRow();
$Maxid=$command['id'];
$so_luong_ton=$command['so_luong_ton'];
$khoi_luong_ton=$command['khoi_luong_ton'];
$kho_du_tru=$command['kho_du_tru'];
I think, the problem is conflict. It mean that when I get record have max_id, and then before i insert new record, having another process insert new record was inserted.
if such cases happen, so how to handle to fix above problem?
My solution:
$lock = $connection->createCommand('LOCK TABLES `the_kho_chi_tiet_with_id` READ');
$lock->execute();
$sql = "SELECT so_luong_ton, khoi_luong_ton, kho_du_tru FROM the_kho_chi_tiet_with_id WHERE id_kho = $id_kho and id_san_pham = $id_san_pham ORDER by id DESC LIMIT 1";
$command=$connection->createCommand($sql);
$dataReader=$command->queryAll();
if($dataReader!=null)
{
foreach($dataReader as $row)
{
.................
}
}
//Insert new record here
TheKhoChiTietWithId::model()->InsertNewRecord(1,300,1,333,1);
$unlock = $connection->createCommand('UNLOCK TABLES');
$unlock->execute();
I lock table to keep no other session work to this table.

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

Nested loops always confuse me

So I have a loop to be nested inside another loop based on two queries. I have the first loop working fine-
$sql_categories = mysql_query("SELECT * FROM $categories_table");
$results = mysql_query("SELECT * FROM $events_table");
while ($num_rows = mysql_fetch_assoc($sql_categories)) {
extract($num_rows);
echo "<h2>$category_name</h2>";
// Begin second loop to output events
while/for(not sure) {
}
}
I want to output into the second loop all the $vars for the corresponding $category_id. In the second query, the matching value is $event_category_id.
I don't know if that makes sense, but what I'm trying to get is basically--
<h2>Category One</h2>
Event Name
Event Name
Event Name
<h2>Category Two</h2>
Event Name
Event Name
Event Name
etc. where the "Event Name" corresponds to the "Category Name"
The two tables I'm working with look like this-
CREATE TABLE `wp_wild_dbem_categories` (
`category_id` int(11) NOT NULL auto_increment,
`category_name` tinytext NOT NULL,
PRIMARY KEY (`category_id`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1
CREATE TABLE `wp_wild_dbem_events` (
`event_id` mediumint(9) NOT NULL auto_increment,
`event_author` mediumint(9) default NULL,
`event_name` tinytext NOT NULL,
`event_start_time` time NOT NULL default '00:00:00',
`event_end_time` time NOT NULL default '00:00:00',
`event_start_date` date NOT NULL default '0000-00-00',
`event_end_date` date default NULL,
`event_notes` text,
`event_rsvp` tinyint(1) NOT NULL default '0',
`event_seats` tinyint(4) default NULL,
`event_contactperson_id` mediumint(9) default NULL,
`location_id` mediumint(9) NOT NULL default '0',
`recurrence_id` mediumint(9) default NULL,
`event_category_id` int(11) default NULL,
UNIQUE KEY `event_id` (`event_id`)
) ENGINE=MyISAM AUTO_INCREMENT=26 DEFAULT CHARSET=latin1
Thanks for your help!
You need to do the second query inside the while loop for it to have any meaningful effect:
$sql_categories = mysql_query("SELECT * FROM $categories_table");
while($category = mysql_fetch_assoc($sql_categories)) {
extract($category);
$events = mysql_query("SELECT * FROM $events_table WHERE event_category_id = '".mysql_real_escape_string($category_id)."'");
echo "<h2>$category_name</h2>";
while($event = mysql_fetch_assoc($events) {
extract($category);
echo "<p>$event_name</p>";
}
}
This should get you where you want, but note that this is not the optimal way to do things. You should first get all of the events, build an array of them indexed by event_category_id and loop that array inside your while loop. This is because now you are doing one extra query per each category whereas only two queries in total should suffice.
But perhaps this would get you started on that then.

Categories