I can't delete a row that I choose with the input delete. I think that I have to set other parameters in the querydelete but i dont know exactly what.
Can anyone help me because Im a beginner? Is there another way to do something like that?
My purpose is to push the delete input and then delete the customer with the specific id (in the same raw with the delete input).
Can anyone give me a link with an example?
<!DOCTYPE html>
<html>
<head>
<title>Table with database</title>
<style>
table {
border-collapse: collapse;
width: 100%;
color: #588c7e;
font-family: monospace;
font-size: 25px;
text-align: left;
}
th {
background-color: #588c7e;
color: white;
}
tr:nth-child(even) {background-color: #f2f2f2}
</style>
</head>
<body>
<table>
<tr>
<th>ID</th>
<th>Room</th>
<th>Name</th>
<th>Check In</th>
<th>Check Out</th>
</tr>
<?php
include('db_connection.php');
$conn = OpenCon();
//SQL query
$query = "Select * from ergazomenos";
if(isset($_POST['delete'])){
$querydelete = "delete from ergazomenos where trim(ID)
='$_POST[hidden]'";
$queryexee = mysqli_query($conn, $querydelete);
}
$result = mysqli_query($conn, $query);
if (!$result){
echo("Error description: " . mysqli_error($conn));
}
//query database
while($rows = mysqli_fetch_array($result)){
$ID = $rows['ID'] ;
$Room = $rows['Room'] ;
$Name = $rows['Name'];
$CheckIn = $rows['Check In'] ;
$CheckOut = $rows['Check Out'] ;
//echo "</td><td>" . $ID. "</td><td>" "<input type=hidden ID=hidden
value=" . $rows['ID'] . $Room. "</td><td>". $Name. "</td><td>" . $CheckIn. "
</td><td>" . $CheckOut. "</td><td>";
echo "</td><td>" . $ID. "</td><td>" . $Room. "</td><td>". $Name.
"</td><td>" . $CheckIn. "</td><td>" . $CheckOut. "</td><td>";
</td>";
echo ("<form action=delete.php method=post>");
echo ("<tr><td><div align=\"center\"> $ID </div>" . "<input
type=hidden name=hidden value=".$rows['ID'] . "</td> <td><div
align=\"center\">
$Room </div></td> <td><div align=\"center\"> $Name </div></td> <td><div
align=\"center\"> $CheckIn </div></td> <td><div align=\"center\"> $CheckOut
</div></td> <td><div align=\"center\"> <td><div ");
echo ("<td>" . "<input type=submit name=delete value=delete" . "
</td>");
//
echo ($rows['ID']);
//echo '<td><input type="button" name="delete"
value="delete"></td>';
echo ("</tr>");
echo ($_POST['hidden']);
}
CloseCon($conn);
?>
</table>
<button type="button" onclick="alert('Hello world!')">Insert</button>
<button type="button" onclick="alert('Hello world!')">Update</button>
</body>
</html>
You should using prepare statement to prevent SQL injection
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$id = $_POST['hidden'];
// if you are using ID, make sure variable is number
if (is_numeric(id)) {
delete from ergazomenos where trim(ID)
='$_POST[hidden]'
/* create a prepared statement */
if ($stmt = mysqli_prepare($link, "DELETE FROM ergazomenos WHERE trim(ID) = ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $id);
/* execute query */
mysqli_stmt_execute($stmt);
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
}
?>
it's more secure this way.
Try with changing the $querydelete from:
$querydelete = "delete from ergazomenos where trim(ID)
='$_POST[hidden]'";
to
$querydelete = "delete from ergazomenos where trim(ID)=". $_POST['hidden'];
This should help. I didn't test the code, tho.
You have to use (single or escaped double) quotes for the attribute values in your input tag/s:
<input type='hidden' name='hidden' [etc.]
Sharing my style.
Create a column in grid named Action and along each db driven record.
<td>
Delete
</td>
In delete.php file:
include('connection.php');
$id = $_GET['id'];
$query= "delete from table where id = '$id'";
mysqli_query($conn, $query); // or $dbConn->query($query);
Redirect to grid page.
Related
Here is what I have for my php coding.
<?php
$USER_NAME = ' ';
$USER_PASSWORD = ' ';
$DB_SERVER = " ";
$DB_NAME = $USER_NAME."_db";
$conn = mysqli_connect($DB_SERVER, $USER_NAME, $USER_PASSWORD, $DB_NAME);
$result = mysqli_query($conn," SELECT * FROM employee,workson where workson.ESSN = employee.SSN and workson.Projnum ='" . $_GET["PNO"] . "'");
$notincluded = mysqli_query($conn, "SELECT SSN, FName, Lname FROM employee where NOT EXISTS (SELECT * FROM workson WHERE employee.SSN = workson.ESSN and workson.Projnum ='" . $_GET["PNO"] . "')") ;
if (!$conn) {
echo "Could not connect: ";
echo mysqli_connect_error(); }
?>
<table border = "1">
<b>Employee List: <b>
<td>Project Number</td>
<td>SSN</td>
<td>First Name</td>
<td>Last Name</td>
<td>Working Hours</td>
<td>Delete</td>
<td>Update</td>
</tr>
<?php
$i=0;
while($row = mysqli_fetch_array($result)) {
?>
<td style = "text-align:center; vertical-align: middle;"> <?php echo $row["Projnum"]; ?></td>
<td style = "text-align:center; vertical-align: middle;"> <?php echo $row["SSN"]; ?></td>
<td style = "text-align:center; vertical-align: middle;"> <?php echo $row["FName"]; ?></td>
<td style = "text-align:center; vertical-align: middle;"> <?php echo $row["Lname"]; ?></td>
<td style = "text-align:center; vertical-align: middle;"> <?php echo $row["NoHours"]; ?> </td>
<td>Delete</td>
<td>Update Hours</td>
</tr>
<?php
$i++;
}
?>
</table>
<br>
<br>
<form method=POST action="http://mkimas.student.ust.hk/cgi-bin/mini_project_5.php">
<b> Employee not included : </b>
<?php
$notincluded = mysqli_query($conn,
"SELECT SSN, FName, Lname FROM employee where NOT EXISTS (SELECT * FROM workson WHERE employee.SSN = workson.ESSN and workson.Projnum ='" . $_GET["PNO"] . "')") ;
$employees = mysqli_fetch_all($notincluded);
$projnum = $_GET["PNO"];
print("<select name='Employees' id='employees'>");
foreach($employees as $employee){
//You can use the index 0, which corresponds with the first selected column in query
print("<option value='$employee[0]'>$employee[0]</option>");
}
print("</select>")
?>
<br>
Input the amount of hours and which project number new employee worked on: <br>
Hours: <input name=hours type =text> <br>
<input type=submit value="Submit">
</form>
For the second part of my php, a selection list of employees not included in the table above is printed. Then, I have the php file that has a SQL query that inserts the not included employee.
<?php
echo "Start \n";
echo "<hr>";
$USER_NAME = " ";
$USER_PASSWORD = " ";
$DB_SERVER = " ";
$DB_NAME = $USER_NAME."_db";
$ESSN = $_POST["Employees"];
$Projnum = $_POST["projnum"];
$NoHours = $_POST["hours"];
$conn = mysqli_connect($DB_SERVER, $USER_NAME, $USER_PASSWORD, $DB_NAME);
if (!$conn) {
echo "Could not connect: ";
echo mysqli_connect_error(); }
$sql="insert into workson(ESSN, Projnum, NoHours) values('$ESSN', '$Projnum', '$NoHours')";
$result=mysqli_query($conn,$sql);
if($result){
echo "insert success"; }
else{
echo "insert fail"; }
mysqli_close($conn);
?>
Somehow, my coding always outputs "insert fail". What might be the problem?
Have you tried :
$sql="INSERT INTO workson(ESSN, Projnum, NoHours) VALUES (".$ESSN.", ".$Projnum.", ".$NoHours.")";
Could you dump the result ?
Regards,
i need to get the counting of the table rows in order as a column in column "N"
also i need to make the column"N" width looks smaller than others columns
i think i have done everything but this is the only point i couldn't achieved
the output should be as the picture :
i hope you could help me guys, thank you
here is my codes :
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<?php
// DataBase connection
$host = "localhost";
$user = "root";
$password = "";
$db = "worksheet9";
$con = mysqli_connect($host, $user, $password, $db);
//verfiy Connection
if( mysqli_connect_errno()) {
echo " Connection Error:" . mysqli_connect_error();
}
if(isset($_POST['submit'])) {
$task=$_POST['task'];
// insert sql query
$sql = "INSERT INTO dolist (task) VALUES ('$task')";
$result=mysqli_query($con, $sql);
// verify query
if ($result) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($con);
}
}
?>
<form method='POST'>
<input type="text" name="task" id="task" required
placeholder="add task" oninvalid="this.setCustomValidity('you must fill the task')"
oninput="this.setCustomValidity('')">
<input type="submit"name="submit"value="add task" ><!-- comment -->
</form>
<table border="1">
<tr>
<th> N </th>
<th>ID </th>
<th>task</th>
<th>delete</th><!-- comment -->
<th>update</th>
</tr>
<?php
// Select sql query
$sql = "SELECT ID,task FROM dolist";
$result = mysqli_query($con, $sql);
while ($rows = mysqli_fetch_array($result)) {
echo"<form method ='POST'>";
echo "<tr>";
echo "<td>" . "<input type='number' readonly name='number' value='" . $rows[''] . "'></td>";
echo "<td>" . "<input type='text' readonly name='id' value='" . $rows['ID'] . "'></td>";
echo "<td>" . "<input type='text' name='task' value= '" . $rows['task'] . "'></td>";
echo "<td>" . "<input type='submit' name='delete' value='x'>" . "</td>";
echo "<td>" . "<input type='submit' name='update' value='update'>" . "</td>";
echo "</tr>";
echo "</form>";
}
if(isset($_POST['update'])) {
$sql = "UPDATE dolist SET task='$_POST[task]'WHERE ID=$_POST[id]";
$result = mysqli_query($con,$sql) or die(mysqli_connect_errno());
if($result){
echo "updated";
} else {
echo "update faild";
}
}
//perform only when the user click on Delete
if(isset($_POST['delete'])) {
$sql = "DELETE FROM dolist WHERE ID=$_POST[id]";
$result = mysqli_query($con,$sql) or die(mysqli_connect_errno());
if($result){
echo "DELETED";
}else{
echo "delete faild";
}
}
?>
</table>
</body>
</html>
For row numbering add a counter to your PHP code:
$rowNumber = 1;
while ($rows = mysqli_fetch_array($result)){
echo"<form method ='POST'>";
echo "<tr>";
echo "<td>" . $rowNumber++. "</td>";
// echo other fields...
echo"</tr>";
For formatting, give your table an ID (not essential but it makes the CSS styling more specific)
This should then generate HTML like this:
<table id="results">
<tr><th>N</th><th>ID</th><th>task</th><th>Delete</th><th>Update</th></tr>
<tr><td>1</td><td>11</td><td>task</td><td>X</td><td>Update</td></tr>
<tr><td>2</td><td>12</td><td>task</td><td>X</td><td>Update</td></tr>
</table>
Now you can style it with CSS:
/* Border around the table */
#results {
border: 1px solid grey;
}
/* Border around the individual cells */
#results th, #results td {
border: 1px solid gray;
}
/* Set the width of the first TH. Also sets the width of the res of the column */
#results th:first-of-type {
width:1em;
}
/* Set the width of the 3rd column (the 'task' column */
#results th:nth-of-type(3) {
width:10em;
}
Output:
Note: you could do this by adding class attributes to the <th> elements and styling those. It makes for easier maintenance later.
Use of formatting attributes in HTML tags (like BORDER="1") is considered bad practice and should be avoided.
Don't use JS or PHP to count something pure CSS can help you with
Use CSS Counters
Use <thead> and <tbody> table elements
Use width: 0%; for the td you want really condensed in width
.tbodyCount {
counter-reset: rowIndex;
}
.tbodyCount tr {
counter-increment: rowIndex;
}
.tbodyCount td:nth-child(1)::before {
width: 0%; /* Make as smaller as possible */
content: counter(rowIndex); /* Learn about counters*/
}
<table>
<thead>
<tr>
<th>N</th>
<th>ID</th>
</tr>
</thead>
<tbody class="tbodyCount">
<tr>
<td></td>
<td>Foo</td>
</tr>
<tr>
<td></td>
<td>Bar</td>
</tr>
<tr>
<td></td>
<td>Baz</td>
</tr>
</tbody>
</table>
This is a demo of a code Im working on, I have links in MySQL table and want to display them on a website table, but instead of showing the links I want to display a name same as Hyperlinks from Excel.
example: If I would just use a href=www.google.com Link
My code:
<!DOCTYPE HTML>
<html>
<head>
<title>Pagina teste</title>
<div align="center">
<font size="+3">Lista de Websites</font>
</div>
</head>
<body>
<style>
table, td, th {border: 1px solid black; border-collapse: collapse; }
tr:nth-child(even) {background-color: #dcdddd;}
</style>
<table>
<tr>
<th><font size="+2">Website Name</font></th>
<th><font size="+2">Link</font></th>
</tr>
<?php
$conn = mysqli_connect("localhost", "root", "", "test");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_GET['order'])){
$order = $_GET['order'];
}else{
$order = 'websitename';
}
if(isset($_GET['sort'])){
$sort = $_GET['sort'];
}else{
$sort = 'ASC';
}
$sql = "SELECT websitename, link FROM websites ORDER BY $order $sort";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>" . $row["websitename"]. "</td>
<td>" . $row["link"]. "</td>
</tr>";
}
echo "</table>";
} else { echo "0 results"; }
$conn->close();
?>
</table>
</body>
</html>
The bull in the China shop method, surround the output with the tag markup:
echo "<tr>
<td>" . $row["websitename"]. "</td>
<td>" . $row['websitename'] . "</td>
</tr>";
You can use anchor link inside table.
<?php
echo "<tr>
<td>" . $row["websitename"]. "</td>
<td><a href=".$row["link"]." target='_blank'>" . $row["link"]. "</a></td>
</tr>";
?>
Try this
<!DOCTYPE HTML>
<html>
<head>
<title>Pagina teste</title>
<div align="center">
<font size="+3">Lista de Websites</font>
</div>
</head>
<body>
<style>
table, td, th {border: 1px solid black; border-collapse: collapse; }
tr:nth-child(even) {background-color: #dcdddd;}
</style>
<table>
<tr>
<th><font size="+2">Website Name</font></th>
<th><font size="+2">Link</font></th>
</tr>
<?php
$conn = mysqli_connect("localhost", "root", "", "test");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(isset($_GET['order'])){
$order = $_GET['order'];
}else{
$order = 'websitename';
}
if(isset($_GET['sort'])){
$sort = $_GET['sort'];
}else{
$sort = 'ASC';
}
$sql = "SELECT websitename, link FROM websites ORDER BY $order $sort";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>
<td>".$row["websitename"]."</td>
<td><a href=".$row["link"]." target='_blank'>" . $row["link"]. "</a></td>
</tr>";
}
echo "</table>";
} else { echo "0 results"; }
$conn->close();
?>
</table>
</body>
</html>
I am just starting with SQL, PHP, and HTML and I plan to take some courses, but I need a basic working model before I can move forward. I have an SQL database that has a few fields. I can display this data without a problem. I would like to filter this data with a drop-down box. Currently, I have the drop-down box populated with a Select Distinct command. I can not seem to figure out the syntax to modify my SQL Select command to only show records that match my pull-down box. Ha, I will be the first to admit that I have no clue what I am doing, but my problem is that I might not know the term I need to look up how to solve my problem. Google and I are tight, but we just can't put our finger on this one. Can you point me in the right direction? Thanks!
<!DOCTYPE html>
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even){
background-color: #dddddd;
}
</style>
<body>
<form action='new1.php' method="get" name='fPIC'>
<select class="form-dropdown validate[required]" style="width:150px" id="input_PIC" name="sPIC">
<?php
$link = mysqli_connect("localhost", "root", "**********", "pd4poc");
mysqli_select_db($link,'pd4poc');
$query = "SELECT DISTINCT PIC FROM dummydata order by PIC asc";
$result = mysqli_query($link,$query);
$menu=" ";
while($row = mysqli_fetch_array($result))
{
$menu .= "<option value=".$row['PIC'].">" .$row['PIC']. "</option>";
}
echo $menu;
echo "<table>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" . $row['PIC'] . "<td><td>" , $row['Reason'] . "<td><td>", $row['Status'] . "</td></tr>";
}
echo "</table>";
mysqli_close($link);
?>
</select>
<input type="submit" name="nPIC" value="Filter">
</form>
<?php
$link = mysqli_connect("localhost", "root", "**********", "pd4poc");
mysqli_select_db($link,'pd4poc');
$query = "SELECT * FROM dummydata"; //need to be picked from the pull down
$result = mysqli_query($link,$query);
echo "<table>";
echo "<tr>
<th>PIC</th>
<th>Reason</th>
<th>PlanApply</th>
<th>HOT</th>
<th>Status</th>
<th>Comments</th>
</tr>\n";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" .
$row['PIC'] . "<td>",
$row['Reason'] . "<td>",
$row['PlanApply'] . "<td>",
$row['HOT'] . "<td>",
$row['Status'] . "<td>",
$row['Comments'] . "</td>\n</tr>";
}
echo "</table>";
mysqli_close($link);
?>
</body>
</head>
I want to delete record from checkbox. I have a form to display data from database like this
$connect = mysqli_connect('Ian', 'root', '', 'penduduk');
$call_db = mysqli_query($koneksi, "select * from tabel_data_penduduk");
<form action="deleteData.php" method="post">
<table style="border:black solid; width: 100%">
<tr style="font-weight: bold">
<th style="width: 2%"><input type="checkbox"/></th>
<th style="width: 3%">No. Identity</th>
<th style="width: 4%">No. Driving License</th>
<th style="width: 10%">Name</th>
<th style="width: 12%">Birth Date</th>
<th style="width: 9%">City Code</th>
</tr>
<?php
$counter=0;
while($db = mysqli_fetch_array($call_db, MYSQLI_NUM)){
echo "<tr>"
. "<td style='text-align:center; width:2%'>"
. "<input type='checkbox' name='deleteNetizen[$counter]' value='". $db[0] ."'/>"
. "</td>"
. "<td style='width: 3%'>". $db[0]. "</td>"
. "<td style='width: 4%'>". $db[1]. "</td>"
. "<td style='width: 10%'>". $db[2]. "</td>"
. "<td style='width: 12%'>". $db[3]. "</td>"
. "<td style='width: 9%'>". $db[4]. "</td></tr>";
++$counter;
}
?>
</table>
<button type="submit" name="btnNetizen" value='ButtonNetizen'>Delete Data Netizen Table</button>
</form>
`
and then the deleteData.php (which is same file as the form) is:
<?php
$netizenData= $_POST['deleteNetizen'];
echo "$netizenData";
$hapusPenduduk = $_POST['btnNetizen'];
$db = mysqli_connect('Ian', 'root', '', 'netizen');
if($hapusPenduduk){
$deleteData_Netizen = mysqli_query($db, "delete from table_data_netizen where No_Identity = $netizenData");
}
?>
The $netizenData return a value when i debug it, but somehow it can't be deleted from database. I wonder where did i go wrong?
Thanks for help
It's hard to debug completely from this code snippet, but here are some tips for improving / debugging:
Use bind variables instead of strings in your queries. So change your last code snippet to something like:
<?php
$netizenData= $_POST['deleteNetizen'];
$db = mysqli_connect('Ian', 'root', '', 'netizen');
$delete_stmt = mysqli_prepare($db, "delete from table_data_netizen where No_Identity = ?"); // note that you can / should re-use this prepared statement
if($hapusPenduduk){
mysqli_stmt_bind_param($delete_stmt, $netizenData);
mysqli_stmt_execute($delete_stmt);
// some debug info:
printf("%d rows deleted.", mysqli_affected_rows($delete_stmt));
}
// if necessary
mysqli_stmt_close($delete_stmt);
?>
This change will make it clearer what's happening in your code. For example, if someone put a quote in $netizenData, you'd get weird results. (This is, in fact, where SQL injection attacks come from and why your code is unsafe.) And then you should start to be able to debug things like: did you make it into your if block? Did any rows get deleted? Etc.
Another thing to look at is whether you are committing / need to commit your data. For example, see http://php.net/manual/en/mysqli.autocommit.php for info on autocommit. If it's off (and you're using transactional tables), then you may need to manually commit (or set autocommit to true).
Hope that helps.
It works now. I change the code to:
Form:
<?php
$connect = mysqli_connect('Ian', 'root', '', 'netizen');
$call_db = mysqli_query($connect, "select * from tabel_data_penduduk");
?>
<form action="deleteData.php" method="post">
<table style="border:black solid; width: 100%">
<tr style="font-weight: bold">
<th style="width: 2%"><input type="checkbox"/></th>
<th style="width: 3%">No. Identity</th>
<th style="width: 4%">No. Driving License</th>
<th style="width: 10%">Name</th>
<th style="width: 12%">Birth Date</th>
<th style="width: 9%">City Code</th>
</tr>
<?php
$counter=0;
while($db = mysqli_fetch_array($call_db, MYSQLI_ASSOC)){
echo "<tr>"
. "<td style='text-align:center; width:2%'>"
. "<input type='checkbox' name='deleteNetizen[$counter]' value='". $db['No_Identity'] ."'/>"
. "</td>"
. "<td style='width: 3%'>". $db['No_Identity']. "</td>"
. "<td style='width: 4%'>". $db['No_Driving_License']. "</td>"
. "<td style='width: 10%'>". $db['Name']. "</td>"
. "<td style='width: 12%'>". $db['BOD']. "</td>"
. "<td style='width: 9%'>". $db['City_Code']. "</td></tr>";
++$counter;
}
?>
</table>
<input type="submit" name="btnNetizen" value='Delete Data Netizen Table'/>
</form>
deleteData.php:
<?php
$netizenData= $_POST['deleteNetizen'];
$hapusPenduduk = $_POST['btnNetizen'];
$db = mysqli_connect('Ian', 'root', '', 'netizen');
if($hapusPenduduk){
$delete_stmt = mysqli_prepare($db, "delete from table_data_netizen where No_Identity = ?");
foreach ($netizenData as $del) {//array processed using foreach
mysqli_stmt_bind_param($delete_stmt, 's', $del);
//'s' is type of parameter $del which is string
mysqli_stmt_execute($delete_stmt);
}
}
?>