Button not being called with isset() function - php

I'm having some trouble trying to build a very simple inventory management system.
What I'm doing is showing the data from a database in a html table and in each row a create two buttons: one to edit and one to delete the item. The problem is that I'm not being able to call these buttons with the isset() function and I can't understand why. I've tried to create a specific function for these but still doesn't work. Anybody has any idea?
Here is the code:
P.S.: Don't mind small english erros or a lack of of brackets. I had to change the code a little bit.
function searchTablet(){
if(isset($_POST['btnSearchTablet'])){
global $connection;
$query="SELECT * FROM tablet";
$run=mysqli_query($connection, $query);
echo "<table class='table table-striped'>";
echo "<thead>";
echo "<tr>";
echo "<th>ID</th>";
echo "<th>Brand</th>";
echo "<th>Model</th>";
echo "<th>Color</th>";
echo "<th>Price</th>";
echo "<th>Fabrication Date</th>";
echo "<th>Provider</th>";
echo "<th>Registration Date</th>";
echo "<th>Edit</th>";
echo "<th>Delete</th>";
echo "</tr>";
echo "</thead>";
while($obj=mysqli_fetch_object($run)){
echo "<tr>";
echo "<td>$obj->id</td>";
echo "<td>$obj->idBrand</td>";
echo "<td>$obj->idModel</td>";
echo "<td>$obj->idColor</td>";
echo "<td>$obj->price</td>";
echo "<td>$obj->fabricationDate</td>";
echo "<td>$obj->idProvider</td>";
echo "<td>$obj->registrationDate</td>";
echo "<td><a href='resultTablet.php?btnEditTablet{$obj->id}'class='btn btn-primary' name='btnEditTablet'>Alterar</a></td>";
echo "<td><a href='resultTablet.php?btnDeleteTablet{$obj->id}' class='btn btn-danger' name='btnDeleteTablet'>Excluir</a></td>";
echo "</tr>";
if(isset($_POST["btnDeleteTablet{$obj->id}"])){
$idTablet=$obj->id;
$delQuery="DELETE FROM tablet WHERE id='$idTablet'";
$delRun=mysqli_query($connection, $delQuery);
if($delRun){
echo "<div class='alert alert-success' role='alert'>Device was successfuly deleted.</div>";
}else{
echo "<div class='alert alert-danger' role='alert'>Error.</div>";
}
}
}

As always... looks like StackOverflow users are toxic and unfriendly and don't even try to help new people who want to get into programming.
So I will try to help you a little bit.
If you are passing parameters via URL you have to use $_GET not $_POST method.
Also, I would change
<a href='resultTablet.php?btnEditTablet{$obj->id}'class='btn btn-primary' name='btnEditTablet'>Alterar</a>
to
<a href='resultTablet.php?btnEditTablet={$obj->id}'class='btn btn-primary' name='btnEditTablet'>Alterar</a>
So you could do this:
if(isset($_GET["btnDeleteTablet"])){
and you would get id via $_GET like this:
$idTablet=$_GET["btnDeleteTablet"];
After this change, you can close while loop you used before
this if(isset($_GET["btnDeleteTablet"])) line, also you wont need $obj->id
anymore, because you will $_GET data decoupled from while loop or any other code you wrote before.
On another note, I see you forgot <tbody> </tbody> in your table.
EDIT:
Also, what are you doing with
if(isset($_POST['btnSearchTablet'])){
This wont work after delete button click.
You shouldn't use it like that, because after the delete button click your page will go to URL with $_GET parameters and that if logic will prevent
if(isset($_GET["btnDeleteTablet"])){
logic working.
So move whole
if(isset($_GET["btnDeleteTablet"])){
...
}
out of if(isset($_POST['btnSearchTablet'])){
Read up about $_POST and $_GET methods also, read about forms
you really need it.
Also, I recommend you to get program to profile requests so you could see how post and get data moves.
I recommend you to install Fiddler program, so you would be able to see how post, get data moves.
Ok, I will try to fix your code at last so it could work:
<?php
function searchTablet(){
global $connection;
if(isset($_GET['btnDeleteTablet'])){
deleteTablet();
}
//I dont why are you using it so I commented it out.
//if(isset($_POST['btnSearchTablet'])){
//}
displaySearchTablet();
}
function displaySearchTablet(){
global $connection;
$query = "SELECT * FROM tablet";
$run = mysqli_query($connection, $query);
while($obj = mysqli_fetch_object($run)){
//Combine all rows into one variable
$table_rows .= "
<tr>
<td>{$obj->id}</td>
<td>{$obj->idBrand}</td>
<td>{$obj->idModel}</td>
<td>{$obj->idColor}</td>
<td>{$obj->price}</td>
<td>{$obj->fabricationDate}</td>
<td>{$obj->idProvider}</td>
<td>{$obj->registrationDate}</td>
<td>
<a href='resultTablet.php?btnEditTablet={$obj->id}' class='btn btn-primary' name='btnEditTablet'>Alterar</a>
</td>
<td>
<a href='resultTablet.php?btnDeleteTablet={$obj->id}' class='btn btn-danger' name='btnDeleteTablet'>Excluir</a>
</td>
</tr>";
}
$result_table =
"<table class='table table-striped'>
<thead>
<tr>
<th>ID</th>
<th>Brand</th>
<th>Model</th>
<th>Color</th>
<th>Price</th>
<th>Fabrication Date</th>
<th>Provider</th>
<th>Registration Date</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
$table_rows
</tbody>
</table>";
echo $result_table;
}
function deleteTablet(){
global $connection;
$id = $_GET['btnDeleteTablet'];
$query = "DELETE FROM tablet WHERE id = '$id'";
$run = mysqli_query($connection, $query);
if($run){
echo "<div class='alert alert-success' role='alert'>Device was successfuly deleted.</div>";
}else{
echo "<div class='alert alert-danger' role='alert'>Error.</div>";
}
}
I kept it very basic, so you would be able to understand.
I didn't pass parameters or returned anything so it would be more understandable to you.
Good luck on your journey to programming.

isset() will return false if an empty string is being submitted, so try using !empty() instead.

Related

Unable to submit my form with Javascript Link

I have tried to submit my form which is having two different links leading to the delete and edit php files but i noticed that the links do not submit the value of the radio button to php files especially the delete php file. But when i changed the links to buttons the value was submitted. Please i do not want to use the button tag, how can i make the value get across to the php files with with my links?
Here is the form:
<form action="del_cn_rec.php" method="POST" id="consignments" >
<table id="example1" class="table table-hover table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Consignment No</th>
<th>Sender</th>
<th>Reciever</th>
<th>Pickup Date/Time</th>
<th>Msg_Status</th>
<th>Status</th>
<th>Action</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php
$sqlc="SELECT * FROM consignments";
$resultc= mysql_query($sqlc) or die(mysql_error());
while($rwsc= mysql_fetch_array($resultc)){
echo "<tr>";
echo "<td><input type='radio' class='flat-red' name='cn_id' value=".$rwsc[0];
echo " /></td>";
echo "<td>".$rwsc[1]."</td>";
echo "<td>".$rwsc[16]." ".$rwsc[17]."</td>";
echo "<td>".$rwsc[21]." ".$rwsc[22]."</td>";
echo "<td>".$rwsc[6]." ".$rwsc[7]."</td>";
$sqli='SELECT * FROM admin_inbox WHERE cn="'.$rwsc[1].'"';
$resulti= mysql_query($sqli);
$rwsi= mysql_fetch_array($resulti);
$mstatus= $rwsi[4];
if("$mstatus" === "Unreplied"){
$moutput = "<span class='label label-danger'><i class='fa fa-circle'></i> Unreplied</span>";
}
if("$mstatus" === "Replied"){
$moutput = "<span class='label label-success'><i class='fa fa-check-circle'></i> Replied</span>";
}
if("$mstatus" === ""){
$moutput = "<span class='label label-warning'><i class='fa fa-circle-o'></i> No Message</span>";
}
echo "<td>".$moutput."</td>";
$status= $rwsc[9];
if("$status" === "Delivered"){
$output = "<span class='label label-success'><i class='fa fa-check-square-o'></i> Delivered</span>";
}
if("$status" === "On Hold"){
$output = "<span class='label label-danger'><i class='fa fa-hand-stop-o'></i> On Hold</span>";
}
if("$status" === "Arrived"){
$output = "<span class='label label-primary'><i class='fa fa-motorcycle'></i> Arrived</span>";
}
if("$status" === "In Transit"){
$output = "<span class='label label-warning'><i class='fa fa-truck'></i> In Transit</span>";
}
echo "<td>".$output."</td>";
echo "<td><span class=\"label label-primary\"><i class=\"fa fa-edit\"></i> Edit Rec.</span></td>";
echo "<td><span class=\"label label-danger\"><i class=\"fa fa-times\"></i> Delete Rec.</span></td>";
echo "</tr>";}
?>
</tbody>
<tfoot>
<tr>
<th>ID</th>
<th>Consignment No</th>
<th>Sender</th>
<th>Reciever</th>
<th>Pickup Date/Time</th>
<th>Msg_Status</th>
<th>Status</th>
<th>Action</th>
<th>Action</th>
</tr>
</tfoot>
</table>
</form>
</div>
<script>
form=document.getElementById("consignments");
function askForEdit_Rec() {
form.action = <?php echo json_encode($urlc); ?>;
form.submit();
}
</script><script>
form=document.getElementById("consignments");
function askForDelete_Rec() {
form.action="del_cn_rec.php";
form.submit();
}
</script>
Here is the Delete php file: del_cn_rec.php
<?php
session_start();
include '_inc/dbconn.php';
$sql="SELECT * FROM admin WHERE id='1'";
$result= mysql_query($sql);
$rws= mysql_fetch_array($result);
$email_1= $rws[3];
$email_2= $rws[4];
$phone= $rws[5];
$address= $rws[6];
$url= $rws[7];
if(!isset($_SESSION['admin_login']))
header("location:$url/server-side");
?>
<?php
$id= mysql_real_escape_string($_REQUEST['cn_id']);
$sql1="SELECT * FROM consignments WHERE id='$id'";
$result1= mysql_query($sql1);
$rwsn= mysql_fetch_array($result1);
$cn= $rwsn[1];
$sql2="DROP TABLE IF EXISTS ".$cn."status ";
mysql_query($sql2) or die(mysql_error());
$sql3="DROP TABLE IF EXISTS ".$cn."msg ";
mysql_query($sql3) or die(mysql_error());
$sql6 = mysql_query("SELECT * FROM admin_inbox WHERE cn='$cn'");
if (mysql_fetch_row($sql6)){
$sql4="DELETE FROM admin_inbox WHERE cn='$cn'";
mysql_query($sql4) or die(mysql_error());
}
$sql5="DELETE FROM consignments WHERE id='$id' AND cn='$cn'";
mysql_query($sql5) or die(mysql_error());
//Consignment Remove Success Msg
$msg = "<i class=\"fa fa-check\"></i> Consignment: $cn Has Been Successfully Deleted!";
header("Location:$url/server-side/consignments?msg=$msg");
?>
this should generally work, just ensure you don't have any errors or notices in your php log, or in the generated html, or any javascript errors in the browser console. Ensure that the value for the radio button is filled in the html (maybe you are getting wrong result from the sql).
Also I hope you know you have to first select the radio button and only after that click the "Delete" or "Edit" link - it is a little confusing here, since you put the link on every row. Radio buttons send values only when they are selected, otherwise they will not even appear in the POST data.
If you wanted to use the links on every row without first selecting the radio button, you have to pass the cn_id as a parameter to the askForDelete_Rec() function and then use it there. An input type="hidden" might be usefull for that, or just append it to the action as a GET parameter.

I have a record Id that needs to be selected to be updated

I have a simple issue I cannot figure out. I am trying to get the id of the record setup as a link to go to a second page that updates the record. I have the update working when I click on update it takes me to the record. I want the id to do the same.
<html>
<?php
require_once("../db_connect.php");
$stmt = $db->prepare("SELECT * FROM Users");
$stmt->execute();
?>
<?php while( $row = $stmt->fetch(PDO::FETCH_ASSOC) ) { ?>
<table bgcolor=F2F2F2 width=1080 border='2'table-layout: fixed >
<br>
<tr>
<th>Id</th>
<th>Update</th>
<th>First Name</th>
<th>Last name</th>
<th>Address</th>
<th>Bio</th>
</tr>
<tr>
<?php echo "<td>
<a href='../update.php?id=" . $row['id'] . "'>ID</a></td>"?>
<?php echo "<td>
<a href='../update.php?id=" . $row['id'] . "'>Update</a></td>"?>
<td><?php echo $row['First Name']; ?></td>
<td><?php echo $row['Last Name']; ?></td>
<td><?php echo $row['Address']; ?></td>
<td><?php echo $row['Bio']; ?></td>
</tr>
<?php } ?>
</table>
</body>
</html>
In general, it is a good practice to put duplicated content into a function or variable and then call it when needed, to improve code readability & to save time/space.
I have also noticed many people struggling with new syntax so I have split the "one-liners" and left comments explaining how does new syntax works.
function col_gen($slug,$id=''){
return (!empty($id))? // If ID parameter exist and not empty generate column with a link
'<td>'.$slug.'</td>': //else
'<td>'.$slug.'</td>';
}
And then, in your case, you can run this function inside a loop:
....
foreach($row as $k=>$slug){
echo ($k==='id')? //if key equals "id"
col_gen($slug,$slug) // Output column for ID
.col_gen('Update',$slug) // Output column for keyword Update
:col_gen($slug); //else output just column with the slug
/**
* Learn one-line PHP, you will love it, once you understand it...
* Full Example Above:
* echo ($k==='id') ? col_gen($slug,$slug).col_gen('Update',$slug):col_gen($slug);
**/
}

How to echo html and row from database

I have a script written to grab a row from my database based on current session user, which outputs the row correctly, however I want to insert a small image to be displayed alongside of the echo'd row, and cannot figure out the proper syntax.
if ($row['lifetime']!="")
echo "<div style ='font:12px Arial;color:#2F6054'> Lifetime Member: </div> ".$row['lifetime'];
else
echo '';
?>
basically I want the image to appear right before or after the .$row appears, either or.
You can try:
<?php
if ($row['lifetime'] !== "") {
echo "<div style ='font:12px Arial;color:#2F6054'> Lifetime Member: </div>";
echo $row['lifetime'];
echo "<img src='' alt='' style='width:100px'/>";
}
?>
Just put the HTML for the image into the string you're echoing:
echo "<div style ='font:12px Arial;color:#2F6054'><img src="fill in URL here"> Lifetime Member: </div> ".$row['lifetime'];
You can try as below example
HTML
<table>
<thead>
<tr>
<th>No.</th>
<th>Customer Name</th>
<th>Photo</th>
<th ></th>
</tr>
</thead>
<tbody>
<?php
$tst=0;
$result = mysql_query("select * from acc_cust");
while($row = mysql_fetch_array($result))
{
echo "<tr class='odd gradeX'>";
echo "<td width=5%'>" . $row['ent_no']. "</td>";
echo "<td>" . $row['cust_name']. "</td>";
echo "<td><img src='[path]" . $row['cust_img'] . "' /></td>";
}
?>
</tbody>
</table>

Issue including page.php on page

I am trying to include a vbijreizen_kaart.php within some code. When I put it outside of the echo, but within the loop (i think this is correct terminology). It will load my google map, however, it will not bring back the rest of the results in my (while) results. When I remove it, the results appear, so I'm doing something wrong but I just don't know what.
The bit of code that is where I am having problems is:
$result = mysql_query($sql);
echo "<br />"; ?>
<?php include('vbijreizen_kaart.php');?>
<?php
echo "<table border='0' cellspacing='0'>
<tr>
<th width='20' valign='top'><div align='left'> </div></th>
</tr>
<tr>
<th height='1' colspan='9' valign='top' bgcolor='#333333'></th>
</tr>";
while($row = mysql_fetch_array($result)){
$row_color = ($row_count % 2) ? $color1 : $color2;
echo "<td bgcolor='$row_color'>" .date("d-M-Y H:i",
strtotime($row['vertrekdatum2'])). "</td>";
echo "<td bgcolor='$row_color'><img src='../flags/".$row['countryflag']."'>
<abbr title=\"".htmlspecialchars($row['luchthavennaam'])."\">
".$row['luchthavencode']."</abbr></td>";
echo "<td bgcolor='$row_color'><img src='../flags/".$row['countryflagaankomst']."'>
<abbr title=\"".htmlspecialchars($row['aankomstnaam'])."\">
".$row['aankomstluchthaven']."</abbr></td>";
I have tried doing just
echo "<br />";
echo include('vbijreizen_kaart.php');
echo " blah blah blah
and I've tried as above, and nothing will let me display the map that exits on vbijreizen_kaart.php as well as the data that would display in the while results.
I can verify in Toad that I have the Query working as it should.
include is not a method, so syntax can look like: include 'vbijreizen_kaart.php';, but that's not the problem. include basically allows you to access the classes, functions, and variables that are on the included page. You don't echo or print the included page itself, but rather the classes, functions, and any variables on the included page. Also, the included page can echo or print to the page you include it into, so it could be a matter of position.

Pass a dynamic variable through URL php

I'm not sure about the title, I tried my best.
I have a table displayed with information from a database using this file
display.php
<?php
mysql_connect("localhost", "root", "root") or die(mysql_error());
mysql_select_db("tournaments") or die(mysql_error());
$result = mysql_query("SELECT * FROM tournies")
or die(mysql_error());
echo '<table id="bets" class="tablesorter" cellspacing="0" summary="Datapass">
<thead>
<tr>
<th>Tournament <br> Name</th>
<th>Pot</th>
<th>Maximum <br> Players</th>
<th>Minimum <br> Players</th>
<th>Host</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>';
while($row = mysql_fetch_array( $result )) {
$i=0; if( $i % 2 == 0 ) {
$class = "";
} else {
$class = "";
}
echo "<tr" . $class . "><td>";
echo $row['tour_name'];
$tour_id = $row['tour_name'];
echo "</td><td>";
echo $row['pot']," Tokens";
echo "</td><td class=\"BR\">";
echo $row['max_players']," Players";
echo "</td><td class=\"BR\">";
echo $row['min_players']," Players";
echo "</td><td class=\"BR\">";
echo $row['host'];
echo "</td><td>";
echo "<input id=\"delete_button\" type=\"button\" value=\"Delete Row\" onClick=\"SomeDeleteRowFunction(this)\">";
echo "</td><td>";
echo "<form action=\"join.php?name=$name\" method=\"POST\" >";
echo "<input id=\"join_button\" type=\"submit\" value=\"Join\">";
echo "</td></tr>";
}
echo "</tbody></table>";
?>
Basically I want the user to press a button from a row of the table and they go to a new page called join.php. I need the persons username and the name of the tournament from the row the clicked.
For example here's my page:
When they click the join button at the end of row one it should send them to
'join.php?name=thierusernamehere&tourname=dfgdds'
Any help much appreciated. Thanks.
echo '<td>Join</td>'
There are many way to approach.
The easiest way is just echo 'JOIN';
or you can use a form with hidden input and submit button.
BUT
Your code is really a mess, try to make your code more maintainable and readable. And do NOT use any mysql_* functions, they are deprecated.
Read more about PDO:
http://php.net/manual/en/book.pdo.php
http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/

Categories