passing variables from views to controllers - php

I'm going to try to explain this as best I can. I'm returning an array of results from my controller. I wish to send over the primary key of the selected row to another controller that will manage inserting the record into the Database when a user clicks the "add employee" button. My primary key is MOVIE_ID. It's currently returning an array of two MOVIE_ID {12341, 31351} like so. My questions are:
How do I associate each movie ID uniquely with that corresponding rows' button?
Can I pass a variable to a controller through the action="" attribute , do I need JS?
<fieldset id= "results">
<?php if (isset($results ) And count($results)) : ?>
<table id="box-table-a" summary="Employee Sheet">
<thead>
<tr>
<th scope="col">Employee</th>
<th scope="col">Salary</th>
<th scope="col">Bonus</th>
<th scope="col">Supervisor</th>
<th scope="col">Action</th>
</tr>
<?php foreach ($results as $result) : ?>
<tr>
//Primary key <?php echo $result['MOVIE_ID!'];?>
<td><span class="Employee_name"><?php echo $result['Employee']; ?> </span></td>
<td><span class="Salary"><?php echo $result['Salary']; ?> </span> </td>
<td><span class="Bonus"><?php echo $result['Bonus']; ?> </span> </td>
<td><span class="Supervisor_name"><?php echo $result['Supervisor']; ?> </span></td>
<td><input type="submit" value="add employee" > </td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</thead>
<tbody>
</fieldset>

One trick is to pass the id via the submit button, like so:
<input name="submit[12341]" type="submit" value="add employee" />
When clicked it would send submit[12341]=add+employee in the POST data (assuming you have wrapped everything inside a <form> tag). The other buttons will not be submitted, only the one that's clicked.
In PHP you can retrieve the id like so:
$id = key($_POST['submit']);

Related

MySQL is deleting the last row of html table / Code Igniter

This is my controller, that i use to send the row to the model:
function excluir(){
$codcliente = $this->input->post('codcliente');
$this->load->model("Cliente_class");
$this->Cliente_class->excluirCliente($codcliente);
redirect('cliente/busca');
}
my model:
function excluirCliente($codcliente){
$this->db->delete('cliente', array('codcliente' => $codcliente));
}
my table (view):
<form action="#" method="POST" id="form">
<div style="float: left;">
<input type="button" onclick="cadastro();" value="Novo cliente" name="botao" class="btn btn-primary">
</div>
<div class="dataTable_wrapper">
<table class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>Código</th>
<th>Nome</th>
<th>Cidade</th>
<th>Telefone</th>
<th> </th>
</tr>
<tbody>
<?php
foreach ($records as $row){ ?>
<tr>
<td><input name="codcliente" id="codcliente" value="<?php echo $row->codcliente ?>"></td>
<td><?php echo $row->nome ?></td>
<td><?php echo $row->cidade ?></td>
<td><?php echo ($row->telefone == null) ? "-" : $row->telefone ?></td>
<td><center><input type="button" onclick="excluir();" value="Delete"></td>
</tr>
<?php } ?>
</tbody>
</form>
</thead>
</table>
and my JS:
function excluir(){
document.forms['form'].action = "<?php base_url();?>excluir";
document.forms['form'].submit();
}
its working fine, but the code is deleting my last row in relation with the table on html. i used the order by too see whats beeing deleted, and it works the same...
i dont know what's wrong
Your problem is that you are using the same form name name="codcliente" for all your rows and then submitting the whole form when you delete. The server sees the last value for codcliente which will be your last row and hence deletes it.
To fix, I suggest you use unique form names for each row for all your row fields. Eg. Instead of name="codcliente" use name="codcliente_<?php echo $row->id ?>". And then when you post to the server to delete, use a data-name=<?php echo $row->codcliente ?> on the delete button and in the onClick handler use $(this).data('name') to get the unique name of the field and post that to the server. I suggest you use ids instead of names as well.

How to delete an HTML table row that's generated by php and sql using checkboxes

I am trying to delete -- using checkboxes -- an HTML table row/s populated by SQL data using PHP. I am new to this, so I would appreciate any improvements to my code. (especially SQL-injection, which I read quite a few times while researching)
Part of HTML with a table - inv_main.php
...
<div class="mid">
<h1>Inventory</h1>
<div class="content">
<!-- buttons -->
<div class="inv_btn">
Add
<!-- button to press to delete ticked checkboxes -->
<form action="inventory.php" method="post">
<input name="delete" type="submit" id="delete" value="Delete"/>
</form>
</div>
<!-- TABLE -->
<div id="inv_tbl">
<table class="table table-striped" id="tblSearch">
<thead>
<tr>
<th>Product Name</th>
<th>Supplier Name</th>
<th>Category</th>
<th>Unit Price</th>
<th>Retail Price</th>
<th>Est. profit per unit</th>
</tr>
</thead>
<tbody>
<?php foreach($allInfo as $info): ?>
<tr>
<td> <?= $info['product'] ?> </td>
<td> <?= $info["supplier_name"] ?> </td>
<td> <?= $info["category"] ?> </td>
<td>$ <?= $info["unit_price"] ?> </td>
<td>$ <?= $info["retail_price"] ?> </td>
<td>$ <?= number_format(($info["unit_price"] - $info["retail_price"]), 2) ?></td>
<td><input type="checkbox" name="checkbox[<?= $info['product'] ?>"] id="checkbox[]" value="<?= $info['product'] ?>" method="post"/></td>
</tr>
<?php endforeach ?>
</tbody>
</table>
</div>
</div>
</div>
...
PHP - inventory.php
<?php
/**
* inventory.php
* configures the inventory page.
*/
// configuration
require("../includes/config.php");
require("../includes/render_dash.php");
// if user reached page via GET...
if($_SERVER["REQUEST_METHOD"] == "GET")
{
// get all the info from the inventory database
$allInfo = [];
$getInfo = query("SELECT * FROM inventory WHERE id = ?", $_SESSION["id"] );
foreach($getInfo as $info)
{
$allInfo[] = [
"product" => $info["product"],
"unit_price" => number_format($info["unit_price"], 2),
"retail_price" => number_format($info["retail_price"], 2),
"supplier_name" => $info["supplier_name"],
"category" => $info["category"],
];
}
// render HTML
render("inv_main.php", ["title" => "Inventory", "allInfo" => $allInfo ] );
}
Note the 'form' right after the comment <!-- button to press to delete ticked checkboxes --> and the last table data inside the tbody tag.
I already saw similar questions but I still can't figure it out. If it helps, my PRIMARY KEYS in the inventory database are the user's id and product. The id is used for the $_SESSION, so using that would delete all the inventory data for, say user id #30 so I'm trying to reach the product, which is a string.

Create and get dynamic variable with php

i know this question probably been asked and answered, and i also not sure what proper question i should ask, so pardon me :D
what im trying to do is:
i got a table, i get the value from mysql and paste it into the table through a LOOP
for each row i give it a button (edit button)
i give each button the id of value through a variable $id (eg. 1 2 3 4 )
my question is how can i get the specify button that i press by $_POST? i tried every way i could think of but it not work ( in my code below i warp the id with another variable=asdf so that it static but i can only get the last value of the id)
$viewvalue = mysqli_fetch_all ($result, MYSQLI_ASSOC);
<?php if (count($viewvalue) > 0): ?>
<table id="t01">
<thead>
<tr>
<th><?php echo implode('</th><th>', array_keys(current($viewvalue))); ?></th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<?php foreach ($viewvalue as $row): array_map('htmlentities', $row); ?>
<tr>
<td><?php echo implode('</td><td>', $row);?></td>
<td><input type="submit" class="edit" name="<?php $a=$row['id']; $$a='asdf'; echo $$a; ?>" value="Edit" /></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
<?php
if(isset($_POST['asdf'])){
echo $a;
}
?>
i know theres a way to use jquery and ajax but sadly i cant get it to work, is it a way to do it with php alone?
I'll offer to replace this row:
<td><input type="submit" class="edit" name="<?php $a=$row['id']; $$a='asdf'; echo $$a; ?>" value="Edit" /></td>
by:
<td><button class="edit" name="act" value="<?php echo $row['id'];?>">Edit</button></td>
after that you'll simply check the value of the $_POST['act']

How do I distinguish between button clicks in a form?

So I'm creating a database for my website and I want to create an admin section that allows you to add or delete from the table. Here is a snapshot of what I want to achieve...
In my php file I have if($_POST['delete_category']) which correctly gets the delete button clicks, but then I'm not sure how to distinguish which delete button was actually clicked. I'm sure this is a very simple solution, but I'm stuck. Thanks!
You can discern which button is submitted by this following markup (based on your example fetched results from DB):
<?php
if(isset($_POST['delete_category'])) {
$id = $_POST['delete_category']; // the value="1" or value="3" goes in here
echo $id;
}
?>
<form method="POST" action="">
<table border="1">
<tr>
<th>ID</th><th>Name</th><th>Delete</th>
</tr>
<tr>
<td>1</td>
<td>Senior Pictures</td>
<td><button typpe="submit" name="delete_category" value="1">Delete</button></td>
<!-- each delete button has the same name, but different values -->
</tr>
<tr>
<td>3</td>
<td>Engagements</td>
<td><button typpe="submit" name="delete_category" value="3">Delete</button></td>
</tr>
</table>
</form>
If I had to guess this makes sense on the fetching: (Note: Just a sample!)
<form method="POST" action="">
<table border="1">
<tr>
<th>ID</th><th>Name</th><th>Delete</th>
</tr>
<?php while($row = $results->fetch_assoc()): ?> <!-- assuming mysqli() -->
<?php while($row = mysql_fetch_assoc($result)): ?> <!-- assuming on mysql (bleh) -->
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td>
<button typpe="submit" name="delete_category" value="<?php echo $row['id']; ?>">Delete</button>
</td>
</tr>
<?php endwhile; ?>
</table>
</form>

PHP - product comparison table displaying only one column

I am trying to compare products and display results in a table. I have a form page and a TABLE page, the problem is that when i select in the FORM page from the two drop-downs the same product(value) it will only display in the table one column and returns an multidimensional array containing one array not two arrays identical. When i select two different values from the from and submit, both selections are displayed. How can I avoid having one empty column if the user select the same product /ID ?
I was thinking maybe load the second drop down and subtracting from the list the value of the first drop down selection? I am not sure how to do it Or maybe there is an easier way like a form validation. Can someone show me how? Thanks
FORM.html
<?php
$products_dropdown = "select * from product_dp" ;
$statement = $dbh->prepare($products_dropdown);
$statement->execute();
$result_dp = $statement->fetchAll();?>
<form action="table.html" method="post">
<fieldset class="custimg">
<legend>Product Comparison</legend>
<div class="row">
<div class="large-block-grid-4"><br /></div>
<div class="large-block-grid-4">
<select name="id1" id="id1" class="small button secondary dropdown radius">`
<?php foreach ($result_dp as $row){
echo "<option value='".$row['id']."'>".$row['sku']."</option>";}?>
</select>
</div>
<div class="large-block-grid-4">
<select name="id2" id="id2" class="small button secondary dropdown radius">
<?php foreach ($result_dp as $row){
echo "<option value='".$row['id']."'>".$row['sku']."</option>"; }?>
</select>
<input type="submit" value="Compare" class="tiny button secondary" />
</div>
</div>
Table.html
$id1 = $_POST[id1];
$id2 = $_POST[id2];
$statement = $dbh->prepare("select * from products_specs where id IN ($id1,$id2)");
$statement->execute(array(':id1' => $id1, ':id2'=> $id2));
$statement->setFetchMode(PDO::FETCH_ASSOC);
$subrows = $statement->fetchAll();
print_r($subrows);
$yes = '<img src="images/icons/yes.png" width="16" height="16" />';
$no = '<img src="images/icons/no.png" width="16" height="16" />';?>
<table >
<thead>
<tr>
<th width="100"></th>
<th width="275"><?php echo $subrows[0][image]; ?></th>
<th width="275"><?php echo $subrows[1][image]; ?></th>
</tr>
<tr text-align="center">
<th width="100"></th>
<th class="centered-cell1"><font color="#990000"><?php echo "ID"." ".$subrows[0][id]; ?></th>
<th class="centered-cell1"><font color="#990000"><?php echo "ID"." ".$subrows[1][id]; ?></th>
</tr>
</thead>
<tbody>
<tr>
<td > Capacity </td>
<td align="center"><?php echo $subrows[0][capacity]; ?> </td>
<td align="center"><?php echo $subrows[1][capacity]; ?> </td>
</tr>
<tr>
<td > Memory </td>
<td align="center"><?php echo $subrows[0][mem]; ?> </td>
<td align="center"><?php echo $subrows[1][mem]; ?> </td>
</tr>
ect....
Very simple solution. After executing query use code:
if (!isset($subrows[1]))
$subrows[1] = $subrows[0];
Let users compare a product with itself if they want it.

Categories