displaying different content on each row of query result - arrays

My model code
function wife($a){
$sql="select person.person_id,person.new_surname,person.fname,person.father_name,person.village,marriage.wife_id from person left join marriage on person.person_id=marriage.wife_id where marriage.husband_id='$a'";
$query=$this->db->query($sql);
return $query->result();
}
My view code
<?php
foreach($result as $row){
echo "first".$row->fname;
echo $row->father_name
echo $row->new_surname;
echo $row->village;
?>
for first row i want to display above and for second row i want to display following
<?php
foreach($result as $row){
echo "Second".$row->fname;
echo $row->father_name
echo $row->new_surname;
echo $row->village;
?>

<?php
$i = 0;
foreach($result as $row){
if ($i == 0) {
echo "first" . $row->fname;
} else if ($i == 1) {
echo "Second" . $row->fname;
} else {
// Do this for third etc. rows
}
echo $row->father_name
echo $row->new_surname;
echo $row->village;
$i++;
}
?>

You can take Variable i and convert number to string using any function which can be used without hard coded strings and will work for n numbers

Related

How is it possible to echo a multidimension array value witout loop in php

I have a multidimension array, in fact a 2 dimension array, I like to echo all the value of the second index... something like that : $cars[0][0]
$cars = array
(
array("Volvo",100,96),
array("BMW",60,59),
array("Toyota",110,100)
);
$cars[0][0] will get me : Volvo. what i need is : Volvo 100 96. Is there is a way to echo this ?.. not print_r or var_dump. does a php function exist to do that ?
let's say now the RESULT array is $cars... 3 sub array value... i what them out. based on answer i try that :
foreach ($cars as $singleArray => $key) {
$result = "";
$result = implode(' ', $singleArray[$key]);
echo '# '. $key .' '. $result .'<br/>';
}
there is an ERROR : Warning: implode() [function.implode]: Invalid arguments passed in /home/studiot/public_html/previsite.com/data/array2.php on line 46
Array
i have done it like this :
foreach ($cars as $singleArray) {
$keyValue ++;
$result = "";
$result .= implode(' ', $singleArray);
echo '(# '. $keyValue .') -> '. $result .'<br/>';
}
You can simply implode the array you want to output with spaces:
echo implode(' ', $cars[0]);
// Volvo 100 96
Docs: http://nz1.php.net/function.implode
EDIT
I see you've tried to use a foreach loop, your syntax is wrong for it. foreach parameters are input array as array key => array value. So you'll implode the value (which is another array. Like this:
foreach ($cars as $key => $value) {
$result = implode(' ', $value);
echo '# '. $key .' '. $result .'<br/>';
}

Is it possible to write the result of a $WPDB query in file

I like to be able to write the query result to a file... now this code write ARRAY... useless !
global $wpdb;
$wpdb->show_errors();
//insert in DB
$randomString = '"'.substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand()).'"';
$randnum = rand(1,999);
$wpdb->query("INSERT INTO test (id,tx) VALUES($randnum,$randomString)");
//read DB
$queryResult = $wpdb->get_results("SELECT * FROM test ");
$i=1;
echo "<table>";
foreach($queryResult as $subQuery){
echo "<tr>";
echo "<td>".'['.$i.'] '.$subQuery->id.' '.$subQuery->tx."</td>";
echo "</tr>";
$i++;
}
echo "</table>";
//write file
$filename = 'aaaa.txt';
$handle = fopen($filename, 'a');
$filewrite = fwrite($handle,$queryResult);
echo $filewrite;
After changing fwrite to file_put_contents that fix the problem.... so here is the solution
global $wpdb;
$wpdb->show_errors();
//$wpdb->print_error();
//insert in DB
$randomString = '"'.substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, rand()).'"';
$randnum = rand(1,999);
$wpdb->query("INSERT INTO test (id,tx) VALUES($randnum,$randomString)");
//read DB
$queryResult = $wpdb->get_results("SELECT * FROM test ");
$i=1;
echo "<table>";
foreach($queryResult as $subQuery){
echo "<tr>";
echo "<td>".'['.$i.'] '.$subQuery->id.' '.$subQuery->tx."</td>";
echo "</tr>";
$i++;
}
echo "</table>";
//write file
$filename = 'aaaa.txt';
//$handle = fopen($filename, 'w');
$json = json_encode($queryResult);
//$filewrite = fwrite($handle,$queryResult);
//fclose($handle);
file_put_contents ($filename,$json);
//read it back :
$myarray = json_decode(file_get_contents($filename));
If its just for caching then you can opt for W3 total cache plugin, which provides database caching too, in addition to all other types of caching.
Before:
ob_start()
After "/table"
$data = ob_get_contents();
//...
fwrite($handle, $data);
Is that you want?

how to print out all certian json data in database?

What I'm trying is I have a page which you can input 3 angel integers and submit.
After you submit the data will be saved in database using json encode
{"angle1":"60","angle2":"60","angle3":"90","submit":"Submit"}
The above is what's saved into a row
I used
<?php
$sql = "SELECT * FROM wp_options WHERE option_name LIKE 'angle%' ORDER BY option_name";
$options = $wpdb->get_results($sql);
foreach ( $options as $option )
{
echo '<p><b>'.$option->option_name.'</b> = '
.esc_attr($option->option_value).'</p>'.PHP_EOL;
$line = json_decode($option->option_value, true);
}
echo '<span style="color:#f00;">'.'Angel 1 : '.$line['angle1'].'</span><br>';
echo '<span style="color:#0f0;">'.'Angel 2 : '.$line['angle2'].'</span><br>';
echo '<span style="color:#00f;">'.'Angel 3 : '.$line['angle3'].'</span><br>';
This prints out angel 1 : ## where ## is the angle entered and so on.
I also made a simple 2d piechart which shows the angles.
the problem I'm having is if I submit another 3 angles then my result only shows the MOST RECENT angles entered even if there are two or more in the database.
For example in my database I can see
{"angle1":"60","angle2":"60","angle3":"90","submit":"Submit"}
{"angle1":"60","angle2":"60","angle3":"180","submit":"Submit"}
{"angle1":"30","angle2":"60","angle3":"180","submit":"Submit"}
but the result only prints 30 60 and 180 instead of printing all three.
Anyone mind giving me a hand on how I can print all three data out or at least all three sets of the angles. I believe once I figured that out I can then print out all the piecharts with all the angles instead right now only the most recent angle and the piechart are printed.
Thanks a lot people~
P.S.
I'm so so so stupid I didn't put those echo into the foreach loop but my other question is I believe I need to input my codes below into the foreach loop but there are so many tags is there a way to input all those into the foreach loop instead of doing something like echo canvas id="piechart1" blah blah blah and do it bit by bit?
<canvas id="piechart1" width="100" height="100"></canvas>
<script src="<?php echo get_stylesheet_directory_uri().'/piechart.js'; ?>"></script>
<script>
var chartId = "piechart1";
var colours = ["#f00", "#0f0", "#00f"];
var angles = [<?php echo $line['comp2052_angle1'].','.
$line['comp2052_angle2'].','.
$line['comp2052_angle3'];
?>];
piechart(chartId, colours, angles);
</script>
It not print 3 results, because you put them out of for scope. It only print the last $line because $line will replace every for loops.
To fixed it.
<?php
$sql = "SELECT * FROM wp_options WHERE option_name LIKE 'angle%' ORDER BY option_name";
$options = $wpdb->get_results($sql);
foreach ( $options as $option )
{
echo '<p><b>'.$option->option_name.'</b> = '
.esc_attr($option->option_value).'</p>'.PHP_EOL;
$line = json_decode($option->option_value, true);
// put the echo in for scope
echo '<span style="color:#f00;">'.'Angel 1 : '.$line['angle1'].'</span><br>';
echo '<span style="color:#0f0;">'.'Angel 2 : '.$line['angle2'].'</span><br>';
echo '<span style="color:#00f;">'.'Angel 3 : '.$line['angle3'].'</span><br>';
echo '<hr/>'; // to separate each data
}
You can stored line into array then print their when you want it. for example.
<?php
$sql = "SELECT * FROM wp_options WHERE option_name LIKE 'angle%' ORDER BY option_name";
$options = $wpdb->get_results($sql);
// added to stored line
$line = array();
foreach ( $options as $option )
{
echo '<p><b>'.$option->option_name.'</b> = '
.esc_attr($option->option_value).'</p>'.PHP_EOL;
$line[] = json_decode($option->option_value, true);
}
Then. You can mixed html and php in the pretty ways like code below.
<?php foreach($line as $i => $l): ?>
<canvas id="piechart<?php echo $i?>" width="100" height="100"></canvas>
<script>
var chartId = "piechart<?php echo $i?>";
var colours = ["#f00", "#0f0", "#00f"];
var angles = [<?php echo $l['angle1'].','.
$l['angle2'].','.
$l['angle3'];
?>];
piechart(chartId, colours, angles);
</script>
<?php endforeach; ?>
Put this anywhere in html before the code above
<script src="<?php echo get_stylesheet_directory_uri().'/piechart.js'; ?>"></script>

Display database array lines whilst autoincrementing id per line

I wish to display the results of a database query in my view whilst giving each row a unique ID.
My model is:
function get_load_lines($ordernumber)
{
$this->db->select('product,pricepercube,qty,linecost,linediscount,cubicvolume,bundles,treated,autospread');
$this->db->from('Customer_Order_Lines');
$this->db->where('CustomerOrderID',$ordernumber);
$q = $this->db->get();
if($q->num_rows() > 0)
{
return $q->row_array();
}
}
My controller is:
function edit_order_lines()
{
$data = array(
'ordernumber' =>$this->input->post('ordernumber'),
'customer' =>$this->input->post('customer'),
'loadlines' => $this->sales_model->get_load_lines($this->input->post('ordernumber'))
);
$this->load->view('sales/edit_order_lines',$data);
}
As mentioned I want to display each of these rows in my view.
So I use this code in my view:
<table>
<?php
$i=1;
foreach ($loadlines as $row)
{
echo "<tr>";
echo "<td>".$i."</td>";
echo "<td>".$row['product']."</td>";
echo "<td>".$row['pricepercube']."</td>";
echo "<td>".$row['qty']."</td>";
echo "</tr>";
$i++;
}
?>
</table>
This does not have the intended result. $i increments for each array entry, not each array line.
Any advice on the best way to display this data?
So if 3 rows the below is required:
In your model, try returning a result_array, rather than a row_array:
return $q->result_array();
If more than one result exists, result array will return all of the results, whereas row array will only return one. CodeIgniter's user guide explains the differences.
You could also make your for loop at little bit tidier, by incrementing $i like this:
$i=1;
foreach ($loadlines as $row)
{
echo "<tr>";
echo "<td>".$i++."</td>";
echo "<td>".$row['product']."</td>";
echo "<td>".$row['pricepercube']."</td>";
echo "<td>".$row['qty']."</td>";
echo "</tr>";
}
I'm not sure I understand you question clearly, but in order to edit Customer Order Line (order details) you should also pull the ID of each Customer_Order_Lines when you query the database. (assuming your table Customer_Order_Lines has primary key filed called ID).
$this->db->select('id,product,pricepercube,q...');
Then when you loop through the results, do:
foreach ($loadlines as $row)
{
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['product']."</td>";
echo "<td>".$row['pricepercube']."</td>";
echo "<td>".$row['qty']."</td>";
echo "</tr>";
$i++;
}
This will give you the specific unique ID's (primary keys) of each Order Line. Then, you can updated each Order Line by referring to this ID.
Let me know if I misunderstood your question.

CakePHP echo first and last record of array output foreach() iteration

I am able to access and output a full array list of Zip items like so (this is working as expected):
... (this is a foreach within a foreach)
foreach ($plan_edit['Zip'] as $zip) :
echo $zip['title'] . "<br />";
endforeach; ...
Returns:
Array
(
[0] => Array
(
[id] => 110
[state_id] => 1
[title] => 97701
[PlansZip] => Array
(
[id] => 83698
[plan_id] => 443
[zip_id] => 110
)
)
[1]
I am trying to ONLY get the first and last value (of ['title']) of each array set for each main record.
I've been messing around with phps array current() and end() functions, but I can only get "Array
" to print out with those.
I know I am doing something wrong, but kind of lost direction at this point.
Any constructive criticism of my work/methods is welcome.
This is where I am at currently:
<?php
foreach ($plan_edit['Zip'] as $zip) :
echo current($zip['title']) . "<br />";
endforeach;
foreach ($plan_edit['Zip'] as $zip) :
echo end($zip['title']) . "<br />";
endforeach;
?>
$first = reset($plan_edit['Zip']);
$last = end($plan_edit['Zip']);
echo $first['title'];
echo $last['title'];
If the array is numerically indexed, you can also just do:
echo $plan_edit['Zip'][0]['title'];
echo $plan_edit['Zip'][count($plan_edit['Zip']) - 1]['title'];

Resources