Nested queries using wpdb - mysql

Im trying to display a few rows of data for each <h3><?php echo $name; ?></h3> item that appears in the loop.
With the current code it only shows one row for each item <h3><?php echo $name; ?></h3>
I have this in my functions.php file
$newdb = new wpdb('login', 'pass', 'db', 'host');
<?php $result=$newdb->get_results('select tbl1.name, tbl2.col1, tbl2.col2, tbl2.col3 from tbl1, tbl2 where tbl1.name=tbl2.tbl1_name');
$names=array();
foreach($result as $row): ?>
<?php $names[$row->name][]=$row;
endforeach; ?>
<?php foreach($names as $name=>$info): ?>
<h3><?php echo $name; ?></h3>
<table>
<tr><th>col1</th><th>col2</th><th>col3</th></tr>
<?php foreach($info as $n):?>
<tr>
<td><?php echo $n->col1; ?></td>
<td><?php echo $n->col2; ?></td>
<td><?php echo $n->col3; ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php endforeach; ?>
So the loop displays the heading followed by a few rows of records, not just one.
<h2>Name</h2>
<table>
<tr><th>col1</th><th>col2</th><th>col3</th></tr>
col1-value1 col2-value1 col3-value1
col1-value2 col1-value2 col1-value2
etc.
</table>
<h2>Name</h2>
<table>
<tr><th>col1</th><th>col2</th><th>col3</th></tr>
col1-value1 col2-value1 col3-value1
col1-value2 col1-value2 col1-value2
etc.
</table>
<h2>Name</h2>
<table>
<tr><th>col1</th><th>col2</th><th>col3</th></tr>
col1-value1 col2-value1 col3-value1
col1-value2 col2-value2 col3-value2
etc.
</table>
.....`

It's possible using your idea but you can do it using one query like
global $wpdb;
$result=$wpdb->get_results('select a.col, b.col1, b.col2, b.col3 from a,b where a.col=b.col5');
Assume that you have tbl1 table and it has a name field and tbl2 table and it has a field for example tbl1_name which has the name value of tbl1 name field and other fields, (with no duplicates) so you can join both tables like
$result=$wpdb->get_results('select tbl1.name, tbl2.col1, tbl2.col2, tbl2.col3 from tbl1, tbl2 where tbl1.name=tbl2.tbl1_name');
$names=array();
foreach($result as $row): ?>
$names[$row->name][]=$row;
<?php endforeach; ?>
foreach($names as $name=>$info):
echo $name;
?><table><?php
foreach($info as $n):
?>
<tr>
<td><?php echo $n->col1; ?></td>
<td><?php echo $n->col2; ?></td>
<td><?php echo $n->col3; ?></td>
</tr>
<?php
<?php endforeach; ?>
?></table><?php
<?php endforeach; ?>
Also remember $wpdb is a global object and available through the template files so you dont need to use new to make an instanse, just use global keyword as I wrote in my answer.
Class Reference/wpdb and sql join and this one.

Related

SQL NOT IN, != what to use?

I've an csv file with plant code like X001, X005, X019...
In mysql table plantcode=username.
I want to fetch all the plantcodes from my DB table where username are not present in my CSV file and deleted =0.
mycode
<?php
$file = fopen("aa.csv","r");
echo "<pre>";
//print_r(fgetcsv($file));
?>
<tr>
<td width="10%"><label>Username</label></td>
<td width="10%"><label>service center id</label></td>
<td width="10%"><label>service center name</label></td>
</tr>
<?php
$arr= fgetcsv($file);
foreach ($arr as $k => $v) {
$q= "SELECT * FROM `service_center` WHERE `deleted` = 0 AND username NOT LIKE '$v'";
$r = mysql_query($q);
$nr = mysql_num_rows($r);
if ($nr > 0) {
WHILE ($rows = mysql_fetch_array($r)) {
?>
<td><?php echo $rows['username'] ?></td>
<td><?php echo $rows['service_center_id'] ?></td>
<td><?php echo $rows['service_center_name'] ?></td>
<?php
}
}
else{
?>
<tr>
<td><?php echo $k;?></td>
<td><?php echo $v; ?></td>
<td><?php echo "No service center found";}?></td>
</tr>
<?php
}
fclose($file);
?>
I get output for each query like this
If username=X008 then from CSV i dont get X008 for one loop and in the next loop I get X008 and ,dont get present value plant code, But I want something like this
select * from service_center WHERE username != "X001, X007.." AND deleted = 0;
use NOT IN($name_array)
Pass username array in NOT IN
select * from service_center WHERE username NOT IN ("X001", "X007") AND deleted = 0;

Arrange data in tables?

I retrieve the data from the database and tried to implement them in the table, but now I don't know how to arrange them in the table. My view is:
<?php include('inc/header.php');?>
<div class="main">
<table>
<thead>
<tr>ID:</tr>
<th>Name:</th>
</thead>
<tbody>
<tr>
<?php foreach ($view as $row) :?>
<?php $i = 1;?>
<?php echo "<td>".$row->audio."</td>";?>
<?php echo $i++;?>
<?php endforeach;?>
</tr>
</tbody>
</table>
</div>
<?php include('inc/footer.php');?>
I just want to make the place id increase from one to the as many records and arrange them into one table.
Your foreach loop should be like this
<tbody>
<?php
$i = 1;
foreach ($view as $row)
{
echo "<tr>";
echo "<td>".$i."</td>";
echo "<td>".$row->audio."</td>";
$i++;
echo "</tr>";
}
?>
</tbody>
And <thead> should be
<thead>
<tr>
<th>ID:</th>
<th>Name:</th>
</tr>
</thead>
Try This Code
<?php
$i=1;
foreach ($view as $row)
{
?>
<tr>
<td><?php echo $i; ?></td>
<td><?php echo $row->audio;?></td>
</tr>
<?php
$i++;
} ?>
You can try this
<?php $i = 1;?>
<?php foreach ($view as $row) :?>
<tr>
<?php echo "<td>".$i++."</td>";?>
<?php echo "<td>".$row->audio."</td>";?>
</tr>
<?php endforeach;?>
Try the following code:
<?php
$i=0;//place the initial value outside the loop
foreach ($view as $row)
{
$i++;//increment the value
?>
<tr>
<td><?php echo $i;//display the value ?></td>
<td><?php echo $row->audio;?></td>
</tr>
<?php
} ?>

Split foreach code based on even/odd

I currently use a code to display some content in my Magento shop.
But now I want to split the loaded content based on even/odd into two different divs.
My current code is displayed below.
How can I split the code based on even/odd so that I get to <div class="block-specs">.
I want a div <div class="block-specs odd"> and <div class="block-specs even">
How can I achieve that?
Current code:
<?php if($_additionalgroup = $this->getAdditionalData()): ?>
<section id="additional">
<div class="box-collateral box-additional">
<h2><?php echo $this->__('Additional Information') ?></h2>
<?php $i=0; foreach ($_additionalgroup as $_additional): $i++; ?>
<div class="block-specs-<?php echo $i?>">
<h3 class="specs-<?php echo $i?>"><?php echo $this->__( $_additional['title'] )?></h3>
<table class="data-table specs-<?php echo $i?>" id="product-attribute-specs-table-<?php echo $i?>">
<col width="25%" />
<col />
<tbody>
<?php foreach ($_additional['items'] as $_data): ?>
<?php $_attribute = $_product->getResource()->getAttribute($_data['code']);
if (!is_null($_product->getData($_attribute->getAttributeCode())) && ((string)$_attribute->getFrontend()->getValue($_product) != '')) { ?>
<tr>
<th class="label"><?php echo $this->htmlEscape($this->__($_data['label'])) ?></th>
<td class="data"><?php echo $_helper->productAttribute($_product, $_data['value'], $_data['code']) ?></td>
</tr>
<?php } ?>
<?php endforeach; ?>
</tbody>
</table>
</div>
<script type="text/javascript">decorateTable('product-attribute-specs-table-<?php echo $i?>')</script>
<?php endforeach; ?>
</div>
</section>
<?php endif;?>
Check if the index is evenly divisable by 2 with '%' this returns the remainder after dividing (0 if even).
<?php foreach ($_additionalgroup as $i => $_additional):
// if evenly divisable by 2, it is even
$oddEven =($i % 2) ? 'odd':'even';
?>
<div class="block-specs-<?php echo $oddEven; ?>">

Inserting delete button for each table not working

I did try some solutions from the same problem with mine but nothings working. I bet it's totally in my code. I'm trying to place them in every table that has been looped, It worked I was able to get a button on every table but I can't get them to work. Here's my code
<?php
$con = new PDO('mysql:host=localhost; dbname=library_member', $username = 'root', $password = '');
$q = "SELECT * FROM user_list";
$stmt = $con->prepare($q);
$stmt -> execute();
?>
<table border="1">
<td>ID</td>
<td>Firstname</td>
<td>Lastname</td>
<td>Address</td>
<td>Contact</td>
<td>Email</td>
<?php while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['firstname']; ?></td>
<td><?php echo $row['lastname']; ?></td>
<td><?php echo $row['address']; ?></td>
<td><?php echo $row['contact']; ?></td>
<td><?php echo $row['email']; ?></td>
<td><button><a href='library-delete.php?id=$id/'>Delete</a></button></td>
</tr>
<?php } ?>
</table>
And this is the code for where the deleting happens.
<?php
$con = new PDO('mysql:host=localhost; dbname=library_member', $username = 'root', $password = '');
$q = "DELETE FROM user_list WHERE id = :id";
$stmt = $con->prepare($q);
$stmt->bindParam( ':id' , $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
echo "<script type='text/javascript'>
alert('Information have been deleted.');
window.location='library-showlist.php';
</script>";
?>
It would just directly send me on the prompt part. None of my input data is deleted.
Try to change your code like this:
library-delete.php?id=<?php echo $row['id']?>

How to display Serial Numbers with mysql query result?

I have a script that displays information of these fields- batchname, class, batchinstructor from the table "batch". But I want to display dynamically generated serial number on the left side when I show the data. For example:
Serial Number BatchName Class Batch Instructor
1. Solar Class Five John
2. Lunar Class six Bon Jovi
I have tried a lot but its not working. Would you please kindly help me to solve this? Please note that these serial number are not from database.
Here's my Controller:
<?php
class Batchlist extends CI_Controller{
function index(){
$this->load->library('pagination');
$config['base_url'] = base_url().'batchlist/index';
$config['total_rows'] = $this->db->get('batch')->num_rows();
$config['per_page'] = 20;
$config['num_links'] = 20;
$config['full_tag_open'] = '<div class="pagination" align="center">';
$config['full_tag_close'] = '</div>';
$this->pagination->initialize($config);
$this->load->model('mod_batchlist');
$data['records']= $this->mod_batchlist->batch_list($config['per_page'],$this->uri->segment(3));
$data['main_content']='view_batchlist';
$this->load->view('includes/template',$data);
}
}
?>
Here's my Model:
function batch_list($perPage,$uri) {
$this->db->select('*');
$this->db->from('batch');
$this->db->join('teacher', 'batch.batchinstructor = teacher.teacherid');
$this->db->order_by('batchid','DESC');
$getData = $this->db->get('', $perPage, $uri);
if($getData->num_rows() > 0)
return $getData->result_array();
else
return null;
}
Here's my View
<h1>Batch List </h1>
<?php if(count($records) > 0) { ?>
<table id="table1" class="gtable sortable">
<thead>
<tr>
<th>Batch Name</th>
<th>Class</th>
<th>Batch Instructor</th>
<th>Edit/Delete</th>
</tr>
</thead>
<tbody>
<?php foreach ($records as $row){ ?>
<tr>
<td><?php echo $row['batchname'];?></td>
<td><?php echo $row['class'];?></td>
<td><?php echo $row['teachername'];?></td>
<td> <img src="<?php echo base_url(); ?>support/images/icons/edit.png" alt="Edit" />
<img src="<?php echo base_url(); ?>support/images/icons/cross.png" alt="Delete" />
</td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } ?>
<div class="tablefooter clearfix">
<div class="pagination">
<?php echo $this->pagination->create_links(); ?>
</div>
</div>
Maybe I misunderstood, but...what about a simple counter?? (after you ordered your records in SQL).
You need to pass to the view the number of items per page (in this snippet: $per_page), then you retrieve the current page from the URI ($this->uri->segment(n)).
At page 1, counter starts from (20*0)+1, i.e. 1. At page 2, starts from (1*20)+1 ie 21, at page 3 from (2*20)+1 ie 41 and so on...
<?php
$cur_page = $this->uri->segment(n) ? intval($this->uri->segment(n)) : 1;
$i = (($cur_page-1) * $per_page) +1;
foreach ($records as $row) :
?>
<tr>
<td><?php echo $i;?>.</td>
<td><?php echo $row['batchname'];?></td>
<td><?php echo $row['class'];?></td>
<td><?php echo $row['teachername'];?></td>
<td> <img src="<?php echo base_url(); ?>support/images/icons/edit.png" alt="Edit" /><img src="<?php echo base_url();?>support/images/icons/cross.png" alt="Delete" />
</td>
</tr>
<?php
++$i;
endforeach;
?>
You can place the counter wherever you want, I added a column for simplicity but if you want it somewhere else just place the counter there.
You said the serial numbers are not from the database. Where are they from then? If you want the database to generate them you can create a column named id and set it as the primary key and have it auto increment.