I want to delete a table row from my database with MySQL and PHP. I have searched through my code and I can't figure out what I'm doing wrong. I think I am close to getting it, probably something simple that I'm not realizing.
If I hover over the delete link there is a link showing with the correct ID number of the row to delete. But if I click it, it isn't working. It just refreshes the screen.
This is my code for index.php:
<!-- Table -->
<form action="index.php" method="get" id="dispatch">
<div class="col-md-8 column">
<fieldset>
<legend>Incident Board (Incidents in red are active)</legend>
<div class="scroll-bar">
<table>
<thead>
<tr>
<th>Incident #</th>
<th>Town</th>
<th>Location</th>
<th>Incident Type</th>
<th>Time/Date</th>
<th>Admin</th>
<th>Delete Entry</th>
</tr>
</thead>
<tbody>
<?php
if( isset($_POST['town']) )
{
$town = $_POST['town'];
}
if( isset($_POST['location']) )
{
$location = $_POST['location'];
}
if( isset($_POST['incident_type']) )
{
$incident_type= $_POST['incident_type'];
}
if( isset($_POST['time_date']) )
{
$time_date= $_POST['time_date'];
}
if( isset($_POST['admin']) )
{
$admin = $_POST['admin'];
}
if( isset($_POST['id']) )
{
$id = $_POST['id'];
}
$db = mysqli_connect('localhost','root','') or die("Database error");
mysqli_select_db($db, 'cad');
$result= mysqli_query($db, "SELECT * FROM `cad` ORDER BY `time_date` DESC LIMIT 20");
while($row = mysqli_fetch_array($result))
{
$town = $row['town'];
$location = $row['location'];
$incident_type = $row['incident_type'];
$time_date = $row['time_date'];
$admin = $row['admin'];
$id = $row['id'];
echo "
<tr>
<td class=\"id-center\">
".$id."
</td>
<td >
".$town."
</td>
<td>
".$location."
</td>
<td >
".$incident_type."
</td>
<td >
".$time_date."
</td>
<td >
".$admin."
</td>
<td>
<span class=\"glyphicon glyphicon-trash\"></span>
</td>
</tr>";
}
mysqli_close($db);
?>
</tbody>
</table>
</div>
</fieldset>
</div>
</form>
<!-- End -->
This is my delete.php code:
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("cad", $dbhandle);
mysql_query("DELETE FROM cad WHERE id = ".$_GET['id']."");
header('location: index.php');
?>
mysql is deprecated, instead of this use mysqli
<?php
$username = "root";
$password = "";
$hostname = "localhost";
$con=mysqli_connect($hostname, $username, $password,"cad");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Perform queries
mysqli_query($con,"DELETE FROM cad WHERE id = ".$_GET['id']."");
mysqli_close($con);
?>
Related
I tried to add a delete "button"(link to file with function) it should delete a row from the database, but it didn't work. I looked for tutorials and answers on forums but found nothing how solve for my problem.
<td>Delete</td>
link from code:
The link works correctly, but when I tried to delete it just doesn't want to take 'commentId' variable and go back to test.php page
Table on website:
dbh.inc.php
<?php
$serverName = "localhost";
$dBUsername = "root";
$dBPassword = "";
$dBName = "php-login";
$conn = mysqli_connect($serverName, $dBUsername, $dBPassword, $dBName);
if (!$conn){
die("connection failed: " . mysqli_connect_error());
}
test.php
<?php
include_once 'header.php';
include "includes/dbh.inc.php";
include 'includes/test.inc.php';
?>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
</head>
<body>
<div class="container">
<div class="box">
<h4 class="display-4 text-center">Comments</h4><br>
<?php if (isset($_GET['success'])) { ?>
<div class="alert alert-success" role="alert">
<?php echo $_GET['success']; ?>
</div>
<?php } ?>
<table class="table table-striped">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Username</th>
<th scope="col">Comment</th>
<th scope="col">Action</th>
</tr>
</thead>
<?php
$i=0;
while($row = mysqli_fetch_array($result)) {
?>
<td><?php echo $row["commentId"]; ?></td>
<td><?php echo $row["usersUid"]; ?></td>
<td><?php echo $row["comment"]; ?></td>
<td>Delete</td>
</tr>
<?php
$i++;
}
?>
</table>
</div>
</div>
</body>
</html>
test.inc.php
<?php
include "dbh.inc.php";
$sql = "SELECT * FROM commenttb ORDER BY commentId DESC";
$result = mysqli_query($conn, $sql);
delete.inc.php
<?php
include "dbh.inc.php";
if(isset($_GET['commentId'])) {
$id = $_GET['commentId'];
$delete = "DELETE FROM `commenttb` WHERE `commentId` ='$id'";
$result = mysqli_query($conn, $delete);
if ($result) {
header("Location: ../test.php?success=successfully deleted");
} else {
header("Location: ../test.php?error=unknown error occurred");
}
}else {
header("Location: ../test.php?error=smth gone wrong");
}
If I press on the link "delete" it should take 'commentId' variable from row e.g. 5 and by SQL query from delete.inc.php file delete row with this id from my database
I tried change $_Get to $_POST and add method="POST" to link on delete.inc.php file, but it didn't work
This question already has answers here:
Show values from a MySQL database table inside a HTML table on a webpage
(9 answers)
Closed 1 year ago.
Would anyone know how to get this result ? Basically I just need to display the columns as well.
Wanted Result image
Current result image
<h1>
Harry Potter Movies
</h1>
<?php
$hostname = "localhost";
$dbUser = "root";
$dbPassword = "root";
$dbName = "harry potter movies";
$port = 3306;
$conn = mysqli_connect($hostname, $dbUser, $dbPassword, $dbName, $port);
$sql = "SELECT * FROM Movies";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["movie"]. " " . $row["rating"]. " " . $row["year"]. "<br>" ;
}
} else {
echo "0 results";
}
?>
You can use a table for that.
<?php
$hostname = "localhost";
$dbUser = "root";
$dbPassword = "root";
$dbName = "harry potter movies";
$port = 3306;
$conn = mysqli_connect($hostname, $dbUser, $dbPassword, $dbName, $port);
if (mysqli_connect_errno()) exit("Failed to connect to MySQL: " . mysqli_connect_error());
?>
<h1>Harry Potter Movies</h1>
<table>
<thead>
<tr>
<th>Movie</th>
<th>Rading</th>
<th>Year</th>
</tr>
</thead>
<tbody>
<?php
$result = $conn->query("SELECT movie, rating, year FROM Movies");
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
<tr>
<td><?= htmlentities($row["movie"], ENT_QUOTES) ?></td>
<td><?= htmlentities($row["rating"], ENT_QUOTES) ?></td>
<td><?= htmlentities($row["year"], ENT_QUOTES) ?></td>
</tr>
<?php
}
} else { ?>
<tr>
<td colspan="3">0 results</td>
</tr>
<?php
}
?>
</tbody>
</table>
What you want is something like this:
<table>
<tr>
<th>
Movie
</th>
<th>
Rating
</th>
<th>
Year
</th>
</tr>
<tr>
<td>
Harry Potter and the Philosopher's Stone
</td>
<td>
7.6
</td>
<td>
2001
</td>
</tr>
So your echo should ouptup some HTML tags with the content.
I have a table and each , I want to select a data from the same table in my database.
For example, first <td> is first name, then the second <td> is phone number.
I got the command, but only the first command is showing output.
This is my php codes to open and connect to the database :
<?php
include("./inc/db_connect.php");
$conn = OpenCon();
?>
This is the php codes for the table including <th> and <td> :
<div class="layer55">
<h3>
<table class="flat-table">
<tbody>
<tr>
<th>
<?php
$sql = "SELECT * FROM sharp_emp WHERE employee_id = 'AA170336'";
if ($result = $conn->query($sql)) {
if ($result->num_rows > 0) {
echo "Name";
}
}
?>
</th>
<th>
<?php
$sql = "SELECT * FROM sharp_emp WHERE employee_id = 'AA170336'";
if ($result = $conn->query($sql)) {
if ($result->num_rows > 0) {
echo "Phone Number";
}
}
?>
</th>
</tr>
<tr>
<td>
<?php
$sql = "SELECT first_name FROM sharp_emp WHERE employee_id = 'AA170336'";
while ($row = $result->fetch_array()) {
echo "" . $row['first_name'] . "";
}
?>
</td>
<td>
<?php
$sql = "SELECT phone FROM sharp_emp WHERE employee_id = 'AA170336'";
while ($row = $result->fetch_array()) {
echo "" . $row['phone'] . "";
}
?>
</td>
</tr>
</tbody>
</table>
</h3>
</div>
This is the php codes for db_connect.php :
<?php
function OpenCon()
{
$dbhost = "localhost";
$dbuser = // Hidden;
$dbpass = // Hidden;
$db = "sharp_db";
$conn = new mysqli($dbhost, $dbuser, $dbpass,$db) or die("Connect failed: %s\n". $conn -> error);
return $conn;
}
function CloseCon($conn)
{
$conn -> close();
}
?>
The expected output :
|----------|----------|
|Name |Phone Number|
|----------|----------|
|John |179898765 |
The current output :
|----------|----------|
|Name |Phone Number|
|----------|----------|
|John |Null (empty) |
You are running the same query multiple times, overwriting the $result variable for no reason, having useless $sql for the later 2 fetch without using them, and fetching a single $result twice by mistake.
So there are multiple concept problem with your code. I think your current code is something equivalant to this:
<div class="layer55">
<h3>
<table class="flat-table">
<tbody>
<tr>
<?php
$sql = "SELECT * FROM sharp_emp WHERE employee_id = 'AA170336'";
if ($result = $conn->query($sql)) {
if ($result->num_rows > 0) {
?>
<th>Name</th>
<th>Phone Number</th>
<?php } else { ?>
<th></th>
<th></th>
<?php } ?>
<?php } ?>
</tr>
<tr>
<?php if ($row = $result->fetch_array()) { ?>
<td><?php echo "" . $row['first_name'] . ""; ?></td>
<td><?php echo "" . $row['phone'] . ""; ?></td>
<?php } else { ?>
<td></td>
<td></td>
<?php } ?>
</tr>
</tbody>
</table>
</h3>
</div>
But frankly, it makes no sense to me to print an empty table when there is no result. So what you need is probably something like this.
<?php
$sql = "SELECT * FROM sharp_emp WHERE employee_id = 'AA170336'";
if (
($result = $conn->query($sql))
&& ($result->num_rows > 0)
&& ($row = $result->fetch_array())
):
?>
<div class="layer55">
<h3>
<table class="flat-table">
<tbody>
<tr>
<th>Name</th>
<th>Phone Number</th>
</tr>
<tr>
<td><?php echo $row['first_name']; ?></td>
<td><?php echo $row['phone']; ?></td>
</tr>
</tbody>
</table>
</h3>
</div>
<?php endif; ?>
I am trying to submit a html table values into mysql table. First two columns of html table are fetched from mysql table 'student' and third column is to be filled online. I want to insert all three columns to another table in msyql. I am just facing problem in inserting all table values. code is as under:-
<html>
<body>
<?php
$connection = mysqli_connect ('localhost', 'user', 'password', 'db');
if (!$connection){
echo 'Not connected to server';
}
$select_db = mysqli_select_db($connection, 'db');
if (!$select_db){
echo 'Not connected to database';
}
$SelectClass = $_POST ['selectclass'];
$sql= "SELECT * FROM students WHERE class = '$SelectClass'";
$query = mysqli_query($connection, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($connection));
}
mysqli_close($connection);
?>
<body>
<div class="container">
<h1><strong>Please enter marks of each student for subject</strong></h1>
<table id = "result" class="data-table">
<caption class="title"></caption>
<thead>
<tr>
<th>Student ID</th>
<th>Student Name</th>
<th>Marks Obtained</th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$total = 0;
while ($row = mysqli_fetch_array($query))
{
$stu = $row['stu_id'] == 0 ? '' : number_format($row['stu_id']);
echo '<tr>
<td>'.$row['student_id'].'</td>
<td>'.$row['student_name'].'</td>
<td>'."<div class='search-block clearfix'><input name='obtmarks' placeholder='' type='number'></div>".'</td>
</tr>';
$total += $row['stu_id'];
$no++;
}?>
</tbody>
</table>
<button type="submit" class="btn btn-warning" value="insert" align="right">Update<span class="glyphicon glyphicon-send"></span></button>
</form>
</div>
</body>
</html>
Have a look at the updated code below :
<body>
<?php
$connection = mysqli_connect ('localhost', 'user', 'password', 'db');
if (!$connection){
echo 'Not connected to server';
}
$select_db = mysqli_select_db($connection, 'db');
if (!$select_db){
echo 'Not connected to database';
}
$SelectClass = $_POST ['selectclass'];
$sql= "SELECT * FROM students WHERE class = '$SelectClass'";
$query = mysqli_query($connection, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($connection));
}
mysqli_close($connection);
//***********Form Submit Goes Here***********//
if($_POST)
{
$student_id = $_POST['student_id'];
$student_name = $_POST['student_name'];
$student_marks = $_POST['obtmarks'];
//your code for insertion....
}
?>
<body>
<div class="container">
<h1><strong>Please enter marks of each student for subject</strong></h1>
<form action="" method="post">
<table id = "result" class="data-table">
<caption class="title"></caption>
<thead>
<tr>
<th>Student ID</th>
<th>Student Name</th>
<th>Marks Obtained</th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$total = 0;
while ($row = mysqli_fetch_array($query))
{
$stu = $row['stu_id'] == 0 ? '' : number_format($row['stu_id']);
echo '<tr>
<td>'.$row['student_id'].'</td>
<input type="hidden" name="student_id" value='.$row['student_id'].'>
<td>'.$row['student_name'].'</td>
<input type="hidden" name="student_name" value='.$row['student_name'].'>
<td>'."<div class='search-block clearfix'><input name='obtmarks' placeholder='' type='number'></div>".'</td>
</tr>';
$total += $row['stu_id'];
$no++;
}?>
</tbody>
</table>
<button type="submit" class="btn btn-warning" value="insert" align="right">Update<span class="glyphicon glyphicon-send"></span></button>
</form>
</div>
</body>
</html>
So the app should read from database if condition is met and print on page in this format:
here are codes and i will post image of my output in the end
lib.php:
<?php
$db_name = "ispit_septembar";
$db_user = "root";
$db_host = "localhost";
$db_pass = "";
function vratiStudente($godina)
{
global $db_name,$db_user,$db_host,$db_pass;
$studenti = array();
$link = mysql_connect("$db_host","$db_user","$db_pass") or die ("Nije moguca konekcija");
mysql_select_db("$db_name",$link) or die ("Nepostojeca baza");
$sql = mysql_query("SELECT * from studenti where godina = '$godina'");
while ($row = mysql_fetch_array($sql) )
{
$indeks = $row["indeks"];
$imeiprezime = $row["imeiprezime"];
$godina = $row["godina"];
$studenti["indeks"] = $indeks;
$studenti[$indeks]["imeiprezime"] = $imeiprezime;
$studenti[$indeks]["godina"] = $godina;
}
return $studenti;
}
function daLiPostojiStudent($indeks)
{
global $db_name,$db_user,$db_host,$db_pass;
$link = mysql_connect("$db_host","$db_user","$db_pass") or die ("Nije moguca konekcija");
mysql_select_db("$db_name","$link") or die ("Nepostojeca baza");
$sql = mysql_query("SELECT * from studenti where indeks = '$indeks'");
$check = mysql_num_rows($sql);
if ($check >0 )
{
$postoji = "postoji";
}
else
{
$postoji = "ne postoji";
}
return $postoji;
}
function dodajStudenta($indeks,$ime,$godina)
{
global $db_name,$db_user,$db_host,$db_pass;
$link = mysql_connect("$db_host","$db_user","$db_pass") or die ("Nije moguca konekcija");
mysql_select_db("$db_name","$link") or die ("Nepostojeca baza");
$result = daLiPostojiStudent($indeks);
if ($result == "postoji")
{
$postoji = "Student sa tim brojem indeksa postoji";
return $postoji;
}
else
{
$sql = ("INSERT INTO studenti (indeks,imeprezime,godina)
VALUES ('$indeks','$ime','$godina' ");
mysql_query($sql);
return 1;
}
}
?>
strana1.php:`
<?php
include "lib.php";
include "Smarty/libs/Smarty.class.php";
$dodaj1 = "strana2.php?godina=1";
$dodaj2 = "strana2.php?godina=2";
$dodaj3 = "strana2.php?godina=3";
$studenti1 = vratiStudente(1);
echo ($studenti1["indeks"]);
$studenti2 = vratiStudente(2);
$studenti3 = vratiStudente(3);
$smarty= new Smarty();
$smarty->assign("dodaj1",$dodaj1);
$smarty->assign("dodaj2",$dodaj2);
$smarty->assign("dodaj3",$dodaj3);
$smarty->assign("studenti1",$studenti1);
$smarty->assign("studenti2",$studenti2);
$smarty->assign("studenti3",$studenti3);
$smarty->display("strana1.tpl");
?>
strana1.tpl
<html>
<head>
</head>
<body>
Godina: 1 <a href ={$dodaj1}>Dodaj</a>
<hr>
<table>
<tr>
<th>Indeks</th>
<th>Ime i Prezime </th>
</tr>
{foreach name="studenti1loop" item=student key=indeks from=$studenti1}
<tr>
<td> {$indeks} </td>
<td> {$student.imeiprezime}</td>
<td>{$student.godina}</td>
</tr>
{/foreach}
</table>
{* druga godina*}
Godina: 2 <a href ={$dodaj2}>Dodaj</a>
<hr>
<table>
<tr>
<th>Indeks</th>
<th>Ime i Prezime </th>
</tr>
{foreach name="studenti2loop" item=student from =$studenti2}
<tr>
<td> {$indeks} </td>
<td> {$student.imeiprezime}</td>
<td>{$student.godina}</td>
</tr>
{/foreach}
</table>
{* treca godina*}
Godina: 3 <a href ={$dodaj3}>Dodaj</a>
<hr>
<table>
<tr>
<th>Indeks</th>
<th>Ime i Prezime </th>
</tr>
{foreach name="studenti2loop" item=student from=$studenti3}
<tr>
<td> {$indeks} </td>
<td> {$student.imeiprezime}</td>
<td>{$student.godina}</td>
</tr>
{/foreach}
</table>
</body>
this is my_sql base structure:
and my output (Wrong one):
and now, questions:
I can't figure out why first member of frist array ($studenty1) as attributes index,imeiprezime and godina has indeks,3,3 - it should be 12345,dusan skoric, 1.
And second question, why is last indeks attribute from last member of first array used as ideks attribute for every member of next two arrays(Studenti2,studenti3)
ok, i've solved my first question:
line studenti["indeks"] = $indeks in lib.php was making problems, but still cant find answer to second question