Codeigniter: Move one row from one table to another at one time - php

I'm kinda stuck here! I have to two tables free_members and domstic_members and I need to move selected rows from free_members tables to the domestic_members table. why I'm saying selected rows because of I at the end of every row in free_members tables there is an upgrade option which will move that row to the domestic_members table. I have the code but it's not working the way I want. right now what is happening is when I click on upgrade option it just copies the whole table records and sends it's to the other table. this here is the code
Controller
function upgradeprofile() {
// $this->load->database();
$this->load->model('freemember_model');
$this->freemember_model->upgrade();
}
model
function upgrade() {
$query = $this->db->get('free_members');
foreach ($query->result() as $row) {
$this->db->where('id', $member_id);
$this->db->insert('domestic_members', $row);
}
}
View
<center> Search Member:
<input type="text" name ='search' id='search' placeholder="Search a member"/></center>
<input type="hidden" name ='limit_from' id='limit_from'/>
</form>
<br><center><button type="button" onclick="CallPrint1('background12')">Print</button>
<div id="background12" class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Sr#</th>
<th><center>Full Name</th>
<th><center>Mobile Number</th>
<th><center>Membership# / CNIC</th>
<th><center>Email Address</th>
<th><center>Province</th>
<th><center>District</th>
<th><center>Tehsil</th>
<th><center>Union Council</th>
<?php /*?> <?php if($sessiondata['deletemembers']):?><?php */?>
<?php if($sessiondata['username'] != 'bilal.sabir'):?>
<th><center>Delete</th>
<?php endif;?>
<?php /*?><?php if($sessiondata['data_modification'] && $sessiondata['username'] != 'bilal.sabir' ):?><?php */?>
<?php if($sessiondata['username'] != 'bilal.sabir'):?>
<th><center>Print</th>
<th><center>Edit</th>
<th><center>Change Pwd</th>
<th><center>Upgrade</th>
<?php endif;?>
</tr>
</thead>
<tbody>
<?php $sr=0;?>
<?php foreach ($freemembers as $member): ?>
<tr><td><center><?php echo $sr+=1; ?></td><td><center><?php echo $member->first_name; ?></td>
<td><center><?php echo $member->mobile; ?></td><td><center><?php echo $member->cnic; ?></td>
<td><center><?php echo $member->email; ?></td>
<td><center><?php echo $member->province; ?></td><td><center><?php echo $member->district; ?></td><td><center><?php echo $member->tehsil; ?></td><td><center><?php echo $member->uc; ?></td>
<?php /*?> <?php if($sessiondata['deletemembers']):?><?php */?>
<?php if($sessiondata['username'] != 'bilal.sabir'):?>
<td><center>delete</td>
<?php endif;?>
<?php /*?><?php if($sessiondata['data_modification'] && $sessiondata['username'] != 'bilal.sabir' ):?><?php */?>
<?php if($sessiondata['username'] != 'bilal.sabir'):?>
<td><center>print</td>
<td><center>edit</td>
<td><center>change pwd</td>
<td><center>Upgrade</td>
<?php endif;?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
this is the view of my table free_members

Based upon your View, you have this...
index.php/admin/upgradeprofile/" . $member->id
So if $member->id = 100 the url will be
index.php/admin/upgradeprofile/100
So you are passing a member_id as mentioned in your model code BUT you are not getting it nor are you using the where correctly.
So you need to get a handle on the member_id...
This is ONE Solution/idea...This relies on you providing a correctly validated integer... You need to always Check/validate your inputs...
Controller
function upgradeprofile($member_id) {
// Need to check that $member_id is an integer
// To be added by the OP
$this->load->model('freemember_model');
// $member_id is passed in via the URL.
$this->freemember_model->upgrade($member_id);
}
Model
function upgrade() {
// Which member do we want to get from the free_members Table?
$this->db->where('id', $member_id);
$query = $this->db->get('free_members');
// Did we get a result? i.e was a valid member id passed in?
if($query !== false) {
$row = $query->row();
$this->db->insert('domestic_members', $row);
} else {
// Do nothing or handle the case where an illegal number was used...
}
}
Note: This code is not tested and is only to be used as a guide.
It can be refactored a number of ways but I am trying to keep it simple for now.
So please, do not just copy and paste this without at least "thinking" about what you are trying to do and how the code might be written to achieve it.
The main points here are...
1. You have to use a member id of some kind so you can retrieve the record for the free member so you can insert it into the other table.
2. You are providing this "member id" in the url so you need to extract it.
3. You can do that by either setting it as a parameter in the method being called... Or you can use segments ( look it up ).
So once you have the member id you can fetch the free member entry and insert it into the other table BUT What do you want to happen to the entry in the free members table because that is still going to be there and now you have two copies of the same information... Delete it?
If you need further explanation - ask.
One last point.
You should be making sure you fully understand what is you are doing and not just doing it because someone said to or you thought it was a good idea... Have a Good Reason and think of the implications...

I'm not familiar with Codeigniter but MySQL syntax should be this:
INSERT INTO table1 (table1.row1, table1.row2)
SELECT table2.row1, table2.row2
FROM table2
WHERE PUT_YOUR_CONDITION_IF_NEEDED
I've found this for Codeigniter.

Related

How to Query multiple variable to show in a View in Codeigniter

I have my little project coding with Codeigniter, I am just stuck in querying the total count of specific column to show in a View. Here are some pieces of my code where I get stuck:
Model:
function get_dailyprob()
{
$date = date('d-m-Y');
$q1 = $this->db->select('client')->like('created_at', $date)->group_by('client')->get('histprob')->result();
$q2 = $this->db->like('created_at', $date)->count_all_results('histprob'); //HERE I HAVE NO IDEA HOW TO GET A TOTAL COUNT OF EACH ROWS THAT ALREADY GROUPED BY COLUMN client
return array('dp_client' => $q1, 'dp_count' => $q2);
}
Controller:
$data['dailyprobs'] = $this->skejuler_m->get_dailyprob();
View:
<table class="table table-hover">
<?php if ($dailyprobs['dp_count'] > 0) {
foreach ($dailyprobs['dp_client'] as $dpc): ?>
<tr>
<td><?php echo $dpc->client; ?></td>
<td><span style="font-size:16px" class="badge bg-red"><?php echo $dailyprobs['dp_count']; ?></span></td>
</tr>
<?php endforeach; ?>
<tr><td><?php } else { echo 'No Issues!'; } ?></td></tr>
</table>
$dpc->client results some rows and each row has different count (filtered by query in Model)
$dailyprobs['dp_count'] is currently showing the whole results, whereas I need showing a total count grouped by client
Sorry if the explanation was confusing. I just added an image of View. As shown in the picture, both American Standard / Grohe & App Sinarmas have each 2 in total number = 4, whereas the actual total row is 1 of each column (client) = 2. I am sorry for my English.
It just solved by changing the query in Model:
function get_dailyprob()
{
$date = date('d-m-Y');
$query = $this->db->select('*, COUNT(*) as cnt')->like('created_at', $date)->group_by('client')->get('histprob');
return $query->result();
}
Then use foreach in View to get Count and Rows Result.

Row within a row with JSON

I have a webpage where it shows the lists of Projects and the monitoring of its progress/finances for every quarter. As shown below:
As you can see, my table is comprises of Project Name and a lists of sub-title's underneath it. And a series of columns per each quarter. Thru PHP I was able to populate the list of sub-titles under the Project Name, which also being fetched from the server side. Here's the code:
$sql = mysqli_query($con," My SELECT Statement ");
$i=0;
while($row = mysqli_fetch_assoc($sql)){
$ptitle = $row['Title'];
$iname = $row['Item'];
if($i%1)
{
?>
<?php } else { ?>
<tr>
<?php } ?>
<td width="25%"><?php echo $ptitle; ?></td>
<td></td>
</tr>
<tr>
<td><?php echo "<ul style='list-style-type: none;'><li>".nl2br($iname)."</li></ul>"; ?></td>
<td contenteditable="true" name="v1"></td>
Note: ptitle = ProjectName and iname = Semi-title underneath the Project's name.
Now, as you can see, the Project Name column literally "conquer" a single row on the left. Yet, the rows under the column of each quarter, should have its own separately, and must be parallel to the every sub-title underneath the Project Name. (Please refer to the image above for this) the only problem am encountering is... how can I make an editable row from inside a row, without affecting mysqli result? coz basically my table right now is kinda look like this:
Anyone who's more experience on this? I need your help.
PS: ...and oh! You might be wondering why do I include JSON in the title? It is because, I originally use JSON for editing those table rows before I even use mysqli_fetch_array. But when I include the results of the array inside the <table> tag, everything's changed and JSON is no longer working. So as of now, I am force to do it manually, meaning typing each <td contenteditable=true> in all of those rows. Yet, its not the desired output since I need another row within an existing row. Ideas? Anyone?
Figure Two:
Figure Three:
Count the number of lines in $iname, and then use a loop to create that many rows of contenteditable cells. You can also use this in the rowspan attribute of the <td> containing the title and subtitles.
$rows = substr_count($iname, "\n") + 1;
for ($i = 0; $i < $rows; $i++) {
echo "<tr>";
if ($i == 0) { ?>
<td rowspan='<?php echo $rows;?>' width='25%'><?php echo $ptitle . "<br>" . nl2br($iname);?></td>
<?php }
?>
<td contenteditable="true" name="v1"></td><td contenteditable="true" name="v2"></td>...
</tr>
<?php }
DEMO

Converting unknown amount of strings into variables

I'm currently working on my computing project which would allow a user to create an indefinite amount of files. What I'm currently stuck on is retrieving these values to let a user select one here is my code:
function DispMonth(){
$dateList=GetDates($_Session['user']);//use session id
foreach($dateList as $value){//get each value
echo '<tr>' .$value.'</tr>';}
}
?>
<body>
<table>
<th><tr> Made Budgets</tr> </th>
<?php DispMonth(); ?>
</body>
</html>
My GetDates function is:
function GetDates($id){
$result=mysql_query('select monthYear from database where userId='.$_Session['user'].'');
while ($row=mysql_fetch_object($result)){
$x[]=$row['monthYear'];}
return x;
}
Essentially I would like the table to look something like this:
|monthYear| edit | delete |
With edit and delete being links/buttons which would send the value of monthYear to a new php page to fetch all the values.(Monthyear is a primary key in my sql table)
There are few issues with your code which you need to fix, and few changes you need to make to make it work, such as:
Your table structure is wrong. <tr> cannot be inside <th>, also the closing </table> tag is missing.
You're fetching rows from the result set using mysql_fetch_object() function but accessing the column values using $row[...], which is wrong. Use mysql_fetch_array() instead.
while ($row=mysql_fetch_array($result)){ ...
Given the fact that monthYear is the primary key of your table, make use of this column value in edit and delele buttons in your foreach loop, like this:
edit
delete
Later, on newPage.php page, you can edit or delete any particular row like this:
if(isset($_GET['edit'])){
$monthYear = $_GET['monthYear'];
// Edit the row
}
if(isset($_GET['delete'])){
$monthYear = $_GET['monthYear'];
// Delete the row
}
So your functions and table structure would be like this:
<table>
<tr>
<th>Made Budgets</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<?php DispMonth(); ?>
</table>
function DispMonth(){
$dateList=GetDates($_Session['user']);
foreach($dateList as $value){
?>
<tr>
<td><?php echo $value; ?></td>
<td>edit</td>
<td>delete</td>
</tr>
<?php
}
}
function GetDates($id){
$result=mysql_query('select monthYear from database where userId='.$_SESSION['user'].'');
$x = array();
while ($row=mysql_fetch_array($result)){
$x[] = $row['monthYear'];
}
return x;
}
Sidenote: Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or pdo instead. And this is why you shouldn't use mysql_* functions.

duplicate answers in table

Hi everyone i am working on a small beginner project currently i am working on displaying two separate table data on a web page in HTML table but i am having some problems with the data. There is a credentials table and an answers table a user first enters its credentials and then presses the button take survay which stores the credentials on to a table and redirects the user to a question page where he picks a multiple choice question and the users choices are saved to a table. all this data then is displayed on web page but when the data is displayed the answers get duplicated fore every user that enter its details. can someone tell me where have i gone wrong ? tnx for your help in advance.
view
<table border="1">
<tr>
<th>Name</th>
<th>Second Name</th>
<th>Phone</th>
<th>Email</th>
<th>Answer</th>
<th>Comment</th>
</tr>
<?php foreach ($query as $row): ?>
<tr>
<td><?php echo $row->name; ?></td>
<td><?php echo $row->second_name; ?></td>
<td><?php echo $row->phone; ?></td>
<td><?php echo $row->email; ?></td>
<td> <?php echo $row->answerA;?>
<?php echo $row->answerB;?>
<?php echo $row->answerC;?></td>
<td><?php echo $row->comment;?><br></td>
</tr>
<?php endforeach; ?>
</table>
controller
function getall(){
$this->load->model('result_model');
$data['query'] = $this->result_model->result_getall();
$this->load->view('result_view', $data);
}
model
function result_getall(){
return $this->db->select('tblanswers.*,credentials.*')
->from('tblanswers, credentials')
->get()
->result_object();
}
You are selecting everything from tblanswers, credentials without joining on any column. You're ending up with a cross join, which pairs each row with every row from the other table. You need to specify which rows from tblanswers relate to which rows from credentials. E.g. if there is an id column in credentials then you need to create a credentials_id column in tblanswers and enter the data so that they match. Your getall() should look something like this:
function result_getall(){
return $this->db->select('tblanswers.*,credentials.*')
->from('tblanswers')
->join('credentials', 'tblanswers.credentials_id = credentials.id')
->get()
->result_object();
}
The line which says
join('credentials', 'tblanswers.credentials_id = credentials.id')
specifies how the two tables relate.
Suppose Mr Jones enters his credentials and they are saved in a row in the credentials table with id 72. Then he enters his answers. You need to make sure that when you save them, you enter "72" in the credentials_id column of the answers table. That signifies that these answers belong to Mr Jones. When you run the query with the join specified above, it will return Mr Jones' credentials against Mr Jones' answers.

SQL Database to php website with javascript

I seem to be stuck on a concept in database query and website development.
I have a website that will reflect what data is stored in a database and the website needs to change depending on that data: therefore, my menu system will not be hardcoded in. It builds my menu system based off a query of all the models in my database. The action of clicking on the menu will show tables without changing the page (a simple javascript "showtables" function). like so:
function showTables(TABLE_NAME)
{
if(TABLE_NAME != "PRINTER_TABLE")
{
document.getElementById("PRINTER_TABLE").style.display ="none";
}
if(TABLE_NAME != "show_ALL_PRINTERS")
{
document.getElementById("show_ALL_PRINTERS").style.display ="none";
}
document.getElementById(TABLE_NAME).style.display ="block";
}
I did not include all of my other if statements because there are about 15 of them. These statements will hide everything and the only show the formatted table of "TABLE_NAME" at the end of that script.
My problem is that, if all of the data will not be hardcoded in either HTML or PHP, I need to pass into my function "showTables" a model type or ID that will come from my query.
My Menu system code snipet:
<li class="hasmore"><span>Printer Parts</span>
<ul class="dropdown">
<?php
include 'connection.php';
$query = "SELECT * FROM all_printers";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
#echo "<h3>" . $row['printer_model'] . "</h3>";
echo "<li>" .$row['printer_model']."</li>\n";
}
?>
This puts the model into the menu system and the "PRINTER_TABLE" will access my showTables function, which then will show that table. But there are many different printer models and I need to tell my table query what specific model to get info on.
I hope this makes sense as there is a lot of logic behind it. Maybe there is an easier way..?
In my tables I have:
<table id="table">
<thead>
<tr>
<th scope="col" id="table">Type</th>
<th scope="col" id="table">Size</th>
<th scope="col" id="table">S/N</th>
<th scope="col" id="table">Model</th>
<th scope="col" id="table">Connection Type</th>
<th scope="col" id="table">Surplus</th>
<th scope="col" id="table">Amount</th>
</tr>
</thead>
<tbody>
<?php
include 'connection.php';
$query_misc = "SELECT * FROM all_parts WHERE part_type='MISC'";
$result_misc = mysql_query($query_misc);
while($row = mysql_fetch_array($result_misc))
{
echo "<tr>";
echo "<td><div align=\"center\">".$row['part_type']."</div></td>";
echo "<td><div align=\"center\">".$row['part_size']."</div></td>";
echo "<td><div align=\"center\">".$row['part_sn']."</div></td>";
echo "<td><div align=\"center\">".$row['part_model']."</div></td>";
echo "<td><div align=\"center\">".$row['part_connection']."</div></td>";
echo "<td><div align=\"center\">".$row['part_surplus']."</div></td>";
echo "<td><div align=\"center\">".$row['part_temp_amount']."/".$row['part_amount']."</div></td>";
echo "</tr>";
}
..... etc
Any ideas?
EDIT:
I do now know how to put what I click on, into the url properly..
<?
$query = 'SELECT printer_id, printer_model FROM printer_table WHERE 1 ORDER BY name';
$products = mysql_query($query);
while ($product = mysql_fetch_assoc($products)) :
{
echo "<li>" .$product['printer_model']."</li>\n";
}
?>
or
<li><?=$product['printer_model']?></li>
doesnt work properly, because i need to call the suggested part list php part, but do not know where to do so..
EDIT:
I placed that php within a div and the echos will fill out my table, but how am I suppose to call that div to only run when that onclick action? I know that is not how divs work, It would seem I would need a JS function but I know you cannot do php within JS. AJAX perhaps?
EDIT----------------------------------------------------
The call here to the DB is correct, tested it manually without any errors, but I am still receiving a syntax error upon loading my home page. Here is my call to the DB via PHP...
<?
if (!isset($_GET['action']))
{
//If not isset -> set with dumy value
$_GET['action'] = "undefine";
}
include 'connection.php';
$query = 'SELECT ppart_table.* FROM ppart_table LEFT JOIN printer_part_relation ON ppart_table.part_id = printer_part_relation.part_id WHERE printer_part_relation.printer_id ='.mysql_real_escape_string($_GET['printer_id']);
$parts = mysql_query($query) or die("Query failed with error: ".mysql_error());
while ($row = mysql_fetch_assoc($parts))
{
echo table blah blah
}
?>
I have tried supressing all errors via this:
<?php error_reporting (E_ALL ^ E_NOTICE); ?>
And the syntax error at page load still exist.
My home page of this site does NOT have the "product_id=" after mysite.php
I would recommend using PHP's PDO class for database access. I would also recommend using JQuery for all of you javascripting. It makes things VERY simple. It would also be advantagious to keep your display code away from your business logic (two languages should for the most part not be in the same source file ie: HTML/PHP/Javascript). I will stick with what is familiar for now however. perhaps something like this?
menu
<ul>
<?
$query = 'SELECT id, name FROM product_category_table WHERE 1 ORDER BY name';
$product_categories = mysql_query($query);
while ($product_category = mysql_fetch_assoc($product_categories)) :
?>
<li>
$product_category['name']
<ul id="<?= $product_category['id'] ?>" style="display: none;">
<?
$query = 'SELECT id, name FROM product_table WHERE category_id = ' . $product_category['id'] . ' ORDER BY name';
$products = mysql_query($query);
while ($product = mysql_fetch_assoc($products)) :
?>
<li><?= $product['name'] ?></li>
<?
endwhile;
?>
</ul>
</li>
<?
endwhile;
?>
</ul>
javascript
function toggleVisibility(category) {
var element = document.getElementById(category);
if (element.style.display == 'none') {
element.style.display = 'block';
} else {
element.style.display = 'none';
}
}
part list
<?
$query = 'SELECT part_table.* FROM part_table LEFT JOIN product_to_part_associations_table ON parts_table.id = product_to_part_associations_table.part_id WHERE product_to_part_associations_table.product_id = ' . mysql_real_escape_string($_GET['product_id']);
$parts = mysql_query($query);
while ($part = mysql_fetch_assoc($parts)) {
echo part table blah blah
}
?>
db tables
product_category_table
id, name, etc
product_table
id, category_id, name, etc
part_table
id, name, etc
part_to_product_association_table
id, product_id, part_id
set the proper indexes on your table columns for speed. the part_to_product_association table allows for a many to many relationship between records in the product table and records in the parts table (needed in the case one part could be used in multiple products, and one product can use multiple parts).

Categories