Rows are not being deleted - php

Here is my php code to select and delete rows form table:
<h1>Deleting Multiple Records using PHP & MySQL</h1>
<p> </p>
<?php
These are my db connection:
$host = "localhost"; // Host name
$username = "root"; // Mysql username
$password = ""; // Mysql password
$db_name = "project"; // Changed database name
$tbl_name = "users";
mysql_connect($host, $username, $password) or die("cannot connect");
mysql_select_db($db_name) or die("cannot select DB");
$sql = "SELECT * FROM $tbl_name";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
?>
Here is my html code to retrieve data from database:
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr><td><form name="form1" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC"><tr>
<td bgcolor="#FFFFFF"> </td>
<td colspan="4" bgcolor="#FFFFFF"><strong>Delete multiple rows in mysql</strong> </td> </tr>
<tr><td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>First Name</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Last Name</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Gender</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Phone Number</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Experiance</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>User Name</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Password</strong></td>
</tr>
<?php while ($rows = mysql_fetch_array($result, MYSQL_ASSOC)) { ?>
<tr>
<td align="center" bgcolor="#FFFFFF">
<input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['id']; ?>"></td>
<td bgcolor="#FFFFFF"><?php echo $rows['id']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows['fname']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows['lname']; ?> </td>
<td bgcolor="#FFFFFF"><?php echo $rows['gend']; ?> </td>
<td bgcolor="#FFFFFF"><?php echo $rows['phone']; ?> </td>
<td bgcolor="#FFFFFF"><?php echo $rows['exp']; ?> </td>
<td bgcolor="#FFFFFF"><?php echo $rows['uname']; ?> </td>
<td bgcolor="#FFFFFF"><?php echo $rows['pwd']; ?> </td>
</tr>
<?php } ?>
<tr><td colspan="5" align="center" bgcolor="#FFFFFF">
<input name="delete" type="submit" id="delete" value="Delete" onclick="javascript:confirm('Are you sure to delete')"></td></tr>
<?php
if(isset($_POST['delete'])){
$checkbox = $_POST['checkbox'];
for($i=0;$i<count($_POST['checkbox']);$i++){
$del_id = $checkbox[$i];
$sql = "DELETE FROM $tbl_name WHERE id='$del_id'";
print $sql;
$result = mysql_query($sql);}
if($result){echo "<meta http-equiv=\"refresh\" content=\"0;URL=index.php\">";}}
mysql_close();
?>
</table></form></td></tr></table>
<p>Record count: <?php echo number_format($count) ?></p>*/
I tried many times but it not deleting a single row from table.
just now i changed the code of executing query....please check it and inform me...

What is this query
$sql = "DEFRE FROM users WHERE id in (" . implode(",", $deleteIds) . ") ";
??
For deleting you should do something like this
$sql = "DELETE FROM users WHERE id IN (" . implode(",", $deleteIds) . ") ";

In the code
if (isset($_POST['checkbox']) && count($_POST['checkbox']) > 0)
{
$deleteIds = $_POST['checkbox']; // it will be an array
$sql = "DELETE FROM users WHERE id in (" . implode(",", $deleteIds) . ") ";
// run the query
}
We need to see the actual code trying to "delete". The usual mysql_query($sql) won't work. You have to use mysql_exec() instead of mysql_query().
Update: Sorry, I was confusing another form of query. mysql_query("delete from table where (whatever)") should work, though it returns true on success or false on failure, not a rowset.

I deleted one line ID from my program and i got the answer and it's working fine.
<tr>
<td align="center" bgcolor="#FFFFFF">
<input name="checkbox[]" type="checkbox" id="checkbox[]" value='<?php echo $row['id']; ?>'></td>
<td bgcolor="#FFFFFF"><?php echo $row['fname']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $row['lname']; ?> </td>
<td bgcolor="#FFFFFF"><?php echo $row['gend']; ?> </td>
<td bgcolor="#FFFFFF"><?php echo $row['phone']; ?> </td>
<td bgcolor="#FFFFFF"><?php echo $row['exp']; ?> </td>
<td bgcolor="#FFFFFF"><?php echo $row['uname']; ?> </td>
<td bgcolor="#FFFFFF"><?php echo $row['pwd']; ?> </td>
</tr>
<?php } ?>
<tr><td colspan="5" align="center" bgcolor="#FFFFFF">
<input name="delete" type="submit" id="delete" value="Delete" onclick="javascript:confirm('Are you sure to delete')"></td></tr>
<?php
if(isset($_POST['delete'])){
$checkbox = $_POST['checkbox'];
for($i=0;$i<count($_POST['checkbox']);$i++){
$del_id = $checkbox[$i];
//print '$del_id';
$sql = "DELETE FROM users WHERE id='$del_id'";
//print $sql;
$result = mysql_query($sql);}
}
if($result){
echo"successfully deleted";
}
mysql_close();
?>
</table></form></td></tr></table>
<p>Record count: <?php echo number_format($count) ?></p>

Related

Back to previous page after deletion of row

<?php
include_once "library/inc.sesadmin.php";
include_once "library/inc.library.php";
include_once "mhsfunc.php";
$filterSQL = "";
if(isset($_POST['btnSubmit'])) {
$txtNim = trim($_POST['txtNim']);
$txtNama = trim($_POST['txtNama']);
$cmbProdi = trim($_POST['cmbProdi']);
$txtSmt = trim($_POST['txtSmt']);
$cmbSmt = trim($_POST['cmbSmt']);
if($cmbSmt<>""){
$filterSQL = "WHERE khs.nim='$txtNim' AND khs.smt='$cmbSmt'";
}else {
$filterSQL = "WHERE khs.nim='$txtNim'";
}
} else {
$filterSQL = "WHERE khs.nim='zzz'";
}
#tampilkan hasil isian di form
$dataNim =isset($_POST['txtNim']) ? $_POST['txtNim'] : '';
$dataNama =isset($_POST['txtNama']) ? $_POST['txtNama'] : '';
$dataProdi =isset($_POST['cmbProdi']) ? $_POST['cmbProdi'] : '';
$dataSmtMhs =isset($_POST['txtSmt']) ? $_POST['txtSmt'] : '';
$dataSmtKrs =isset($_POST['cmbSmt']) ? $_POST['cmbSmt'] : '';
# FOR PAGING (PEMBAGIAN HALAMAN)
$baris = 50;
$hal = isset($_GET['hal']) ? $_GET['hal'] : 1;
$pageSql = "SELECT * FROM khs $filterSQL";
$pageQry = mysql_query($pageSql, $koneksidb) or die ("error paging: ".mysql_error());
$jumlah = mysql_num_rows($pageQry);
$maks = ceil($jumlah/$baris);
$mulai = $baris * ($hal-1);
$jmlsks = 0;
$jmlbobot = 0;
$ipk = 0;
?>
<table width="800" border="0" cellpadding="2" cellspacing="0" class="table-border">
<tr>
<td colspan="3" align="right"><h1><b>DATA KRS MAHASISWA </b></h1></td>
</tr>
<tr>
<td colspan="3">
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="post" name="form1" target="_self">
<table class="table-list" width="1000" border="0" cellpadding="2" cellspacing="1" >
<tr>
<td colspan="3" style="font-size:20px; font-family:Cambria" bgcolor="#F5F5F5"><b>FILTER DATA</b></td>
</tr>
<tr>
<td width="169"><b>NIM Mahasiswa</b></td>
<td width="5"><b>:</b></td>
<td width="260"><input name="txtNim" type="text" id="txtNim" value="<?php echo $dataNim; ?>" size="15" maxlength="12" /></td>
</tr>
<tr>
<td><b>Nama Mahasiswa</b></td>
<td><b>:</b></td>
<td><input name="txtNama" type="text" id="txtNama" value="<?php echo $dataNama; ?>" size="40" maxlength="40" /></td>
</tr>
<tr>
<td><b>Program Studi</b></td>
<td><b>:</b></td>
<td><select name="cmbProdi" id="cmbProdi">
<option value="KOSONG">....</option>
<?php
$dataSql = "SELECT * FROM prodi ORDER BY kode";
$dataQry = mysql_query($dataSql, $koneksidb) or die ("Gagal Query".mysql_error());
while ($dataRow = mysql_fetch_array($dataQry)) {
if ($dataRow['kode'] == $cmbProdi) {
$cek = " selected";
} else { $cek=""; }
echo "<option value='$dataRow[kode]' $cek> [$dataRow[kode]] $dataRow[nama]</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td><b>Semester Mahasiswa</b></td>
<td><b>:</b></td>
<td><input name="txtSmt" type="text" id="txtSmt" value="<?php echo $dataSmtMhs; ?>" size="3" maxlength="1" /></td>
</tr>
<tr>
<td><b>Semester KRS</b></td>
<td><b>:</b></td>
<td><select name="cmbSmt" id="cmbSmt">
<option value="">ALL</option>
<?php
$pilihan = array("1", "2", "3", "4", "5","6");
foreach ($pilihan as $semester) {
if ($dataSmtKrs==$semester) {
$cek="selected";
} else { $cek = "";}
echo "<option value='$semester' $cek>$semester</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input name="btnSubmit" type="submit" value=" Submit" id="btnSubmit" /></td>
</tr>
</table>
</form>
<tr>
<td colspan="3"> </td>
</tr>
<tr>
<td colspan="3">
<table class="table-list" width="100%" border="0" cellspacing="1" cellpadding="2">
<tr>
<td colspan="5"><img src="images/btn_add_data.png" height="30" border="0" /></td>
</tr>
<tr>
<td width="28" align="center" bgcolor="#F5F5F5"><b>No</b></td>
<td width="63" bgcolor="#F5F5F5"><b>NIM</b></td>
<td width="53" bgcolor="#F5F5F5"><b>KDMK</b></td>
<td width="368" bgcolor="#F5F5F5"><b>NAMA MK</b></td>
<td width="35" bgcolor="#F5F5F5"><b>SMT</b></td>
<td width="30" bgcolor="#F5F5F5"><b>SKS</b></td>
<td width="26" bgcolor="#F5F5F5"><b>TM</b></td>
<td width="21" bgcolor="#F5F5F5"><b>PR</b></td>
<td width="19" bgcolor="#F5F5F5"><b>LP</b></td>
<td width="252" bgcolor="#F5F5F5"><b>DOSEN (NIDN/NAMA)</b></td>
<td align="center" bgcolor="#CCCCCC"><b>Tools</b></td>
</tr>
<?php
$mySql = "SELECT khs.id_khs, khs.nim, khs.kdmk, khs.nmmk, khs.smt, mtkul.sks, mtkul.tm, mtkul.pr, mtkul.lp,mtkul.nodos
FROM khs
INNER JOIN mtkul
ON khs.tahun=mtkul.tahun AND khs.prodi=mtkul.prodi AND khs.smt=mtkul.smt AND khs.kdmk=mtkul.kode $filterSQL
ORDER BY khs.smt, khs.kdmk LIMIT $mulai, $baris";
$myQry = mysql_query($mySql, $koneksidb) or die ("Query salah : ".mysql_error());
$nomor = $mulai;
while ($myData = mysql_fetch_array($myQry)) {
$nomor++;
$nidn = $myData['nodos'];
$Kode = $myData['id_khs'];
$jmlsks = $jmlsks+$myData['sks'];
$qryDosen = "SELECT * from dosen WHERE nidn=$nidn";
$qryCek = mysql_query($qryDosen, $koneksidb) or die ("Eror Query".mysql_error());
$myData2 = mysql_fetch_assoc($qryCek);
if(mysql_num_rows($qryCek)>=1){
$namaDosen=$myData2['nama'];
} else {$namaDosen=$nidn;}
// Gradasi warna baris
if($nomor%2==1) { $warna="#FFFFFF"; } else {$warna="#F5F5F5";}
?>
<tr bgcolor="<?php echo $warna; ?>">
<td align="center"><?php echo $nomor; ?></td>
<td><?php echo $myData['nim']; ?></td>
<td><?php echo $myData['kdmk']; ?></td>
<td><?php echo $myData['nmmk']; ?></td>
<td align="center"><?php echo $myData['smt']; ?></td>
<td align="center"><?php echo $myData['sks']; ?></td>
<td><?php echo $myData['tm']; ?></td>
<td><?php echo $myData['pr']; ?></td>
<td><?php echo $myData['lp']; ?></td>
<td><?php echo $namaDosen ?></td>
<td width="56" align="center">Delete</td>
//here is the KRS-Delete.php
<?php
include_once "library/inc.sesadmin.php";
// Get From URL
if(empty($_GET['Kode'])){
echo "<b>Data yang dihapus tidak ada</b>";
}
else {
$Kode = $_GET['Kode'];
$mySql = "DELETE FROM khs WHERE id_khs='$Kode'";
$myQry = mysql_query($mySql, $koneksidb) or die ("Eror hapus data".mysql_error());
if (mysql_affected_rows() > 0) {
header('location: ' .$_GET['Kode']);
echo "<script type=\"text/javascript\">".
"alert('Data Berhasil Di Hapus');".
"</script>";
echo "<meta http-equiv='refresh' content='0; url=?open=KRS-Data'>";
} else {
echo "Data tidak ditemukan !! <br><br>";
}
My Problem is that when I successfully delete a row, I want my page to go back showing the previous table shown, minus the row that I have already deleted with the exact same page number. What I need to parse into and out of KRS-Delete.php
When building UI pages that involve multiple steps, I prefer to put all steps in the same PHP file. I start with $foo = #$_GET['foo']; if ($foo) DoFoo(); to see if this call needs to do the "foo" step (such as doing the DELETE). After DoFoo(), I usually fall into the main code, which presents the UI page identical to (or similar to) the original page.
In addition to avoiding navigation problem you mentioned, it allows me to have 'all' the stuff for this UI in one file. Often there is a lot of common code, too.

PHP error: Undefined variable [duplicate]

This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 8 years ago.
I am trying to delete some rows when users check them with check button. I have created a button called delete, but I have a problem. It said to me that variable delete that I use here
// Check if delete button active, start this if($delete){ for($i=0;$i<$count;$i++){ $del_id = $checkbox[$i]; $sql = "DELETE FROM Aktivitet WHERE Id_Akt='$del_id'"; $result = mysql_query($sql); } is not defined... But why because I have declared it as the name of Delete button...here I have created the Delete button;
print("<tr>");
print("<td><input name='delete' type='submit' id='delete' value='Delete'></td>");
print("</tr>");
Please can you help me? What can I do? My php file is below:
<?php
$con = mysql_connect('127.0.0.1','root','');
if (!$con)
{
die('Lidhja me databazen nuk mund te kryhet' .mysql_error(). ' </body></html>');
}
if(!mysql_select_db("Axhenda",$con))
die('Nuk mund te hapet databaza Axhenda'.mysql_error(). '</body></html>');
$result = mysql_query("SELECT * FROM Aktiviteti where Data= '$_POST[dataoutput]'");
mysql_close($con);
?>
<div class="title"> Aktivitetet per daten <?php print ("$_POST[dataoutput]"); ?></div>
<table>
<?php
print("<th >");
print("<form name='form1' method='post' action=''>");
print("<td>Emertimi takimit</td>");
print("<td>Pershkrimi takimit</td>");
print("<td>Oraa takimit</td>");
print("</th >");
while($rows=mysql_fetch_row($result))
{
if (!empty($rows))
{
print("<tr >");
print("<td align='center' bgcolor='#FFFFFF'><input
name='checkbox[]' type='checkbox' id='checkbox[]' value='$rows[0]'></td>");
print("<td bgcolor='#FFFFFF'>$rows[2]</td>");
print("<td bgcolor='#FFFFFF'>$rows[3]</td>");
print("<td bgcolor='#FFFFFF'>$rows[5]</td>");
print("</tr>");
}
else
echo "ska aktivitet";
}
print("<tr>");
print("<td><input name='delete' type='submit' id='delete' value='Delete'></td>");
print("</tr>");
?>
<?php
// Check if delete button active, start this
if($delete){
for($i=0;$i<$count;$i++){
$del_id = $checkbox[$i];
$sql = "DELETE FROM Aktivitet WHERE Id_Akt='$del_id'";
$result = mysql_query($sql);
}
// if successful redirect to delete_multiple.php
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=delete_multiple.php\">";
}
}
print("</form>");
?>
</table>
I modified the function like below, but it still dont delete anything:
if(isset($_POST['delete'])){
$checkbox = $_POST['checkbox'];
$count = count($checkbox);
for($i = 0; $i < $count; $i++) {
$id = (int) $checkbox[$i];
if ($id > 0) { // and check if it's bigger then 0
mysql_query("DELETE FROM Aktiviteti WHERE Id_Akt= $id");
}
}
}
please help me..
Tested on my own server. You will need to modify it for your own columns as well as other elements that need to be translated in your language.
Change settings for the following:
DEFINE ('DB_HOST', 'xxx');
DEFINE ('DB_USER', 'xxx');
DEFINE ('DB_PASSWORD', 'xxx');
DEFINE ('DB_NAME', 'xxx');
And: (Note: the # is just a reference character. You can change it to what you like.)
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>Link ID</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Link Name</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Link Email</strong></td>
And change: (The rows you wish to show up. There are two of these. One is to show the rows, while the other is used for deletion.)
<td bgcolor="#FFFFFF"><?php echo $row['id']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $row['name']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $row['email']; ?></td>
And change: (delete.php is this file to redirect to after deleting)
echo "<meta http-equiv=\"refresh\" content=\"3;URL=delete.php\">";
And change: ( your_table ) and the id depending on which column you want to ORDER BY
$query = "select * from your_table ORDER BY id ASC";
And change:
$sql = "DELETE FROM your_table WHERE link_id='$del_id'";
And change: all instances of link_id being the id (column name) associated with the deletion.
Full script: (delete.php)
<html>
<head>
<title></title>
</head>
<body>
<h2>Choose and delete selected items.</h2>
<?php
DEFINE ('DB_HOST', 'xxx');
DEFINE ('DB_USER', 'xxx');
DEFINE ('DB_PASSWORD', 'xxx');
DEFINE ('DB_NAME', 'xxx');
$dbc = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
OR die("could not connect");
$query = "select * from your_table ORDER BY id ASC";
$result = mysqli_query($dbc,$query)
or die('Error querying database');
$count=mysqli_num_rows($result);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td><form name="form1" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td bgcolor="#FFFFFF"> </td>
<td colspan="3" bgcolor="#FFFFFF"><strong>Delete multiple items</strong> </td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>Link ID</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Link Name</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Link Email</strong></td>
</tr>
<?php
while ($row=mysqli_fetch_array($result)) {
?>
<tr>
<td align="center" bgcolor="#FFFFFF">
<input name="checkbox[]" type="checkbox" value="<?php echo $row['link_id']; ?>">
</td>
<td bgcolor="#FFFFFF"><?php echo $row['id']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $row['name']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $row['email']; ?></td>
</tr>
<?php
}
?>
<tr>
<td colspan="4" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" value="Delete"></td>
</tr>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td><form name="form1" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td bgcolor="#FFFFFF"> </td>
<td colspan="3" bgcolor="#FFFFFF"><strong>Delete multiple items</strong> </td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>Link ID</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Link Name</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Link Email</strong></td>
</tr>
<?php
while ($row=mysqli_fetch_array($result)) {
?>
<tr>
<td align="center" bgcolor="#FFFFFF">
<input name="checkbox[]" type="checkbox" value="<?php echo $row['link_id']; ?>">
</td>
<td bgcolor="#FFFFFF"><?php echo $row['id']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $row['name']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $row['email']; ?></td>
</tr>
<?php
}
?>
<tr>
<td colspan="4" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" value="Delete"></td>
</tr>
<?php
if(isset($_POST['delete']))
{
$checkbox = $_POST['checkbox'];
for($i=0;$i<count($checkbox);$i++){
$del_id = $checkbox[$i];
$sql = "DELETE FROM your_table WHERE link_id='$del_id'";
$result = mysqli_query($sql);
}
// if successful redirect to delete.php
if($result){
echo "<meta http-equiv=\"refresh\" content=\"3;URL=delete.php\">";
// echo "Got results.";
}
}
mysqli_close($dbc);
?>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>
Try this:
if(isset($_POST['delete'])){
foreach($_POST['checkbox'] as $del_id){
$sql = "DELETE FROM Aktivitet WHERE Id_Akt='$del_id'";
$result = mysql_query($sql);
}
}

Undefined variable: delete in C:\xampp\htdocs\xampp\Test\HRMS\try\search1.php on line 61

I am trying very hard for the last 2 hours but am not able to understand. Why am I getting undefined variable in DELETE. Please please look in to my code and help me out.
My main intention is to delete multiple rows at once using checkboxes.
When I am trying to run the below codes it gives me following errors:
Undefined variable: delete in C:\xampp\htdocs\xampp\Test\HRMS\try\search1.php on line 61
But I already have used it in following way:
<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td>
Thanks in advance.
my php codes :
<?php
$host="localhost"; // Host name
$username="a"; // Mysql username
$password="a"; // Mysql password
$db_name="b"; // Database name
$tbl_name="emp_info"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td><form name="form1" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td bgcolor="#FFFFFF"> </td>
<td colspan="4" bgcolor="#FFFFFF"><strong>Delete multiple rows in mysql</strong> </td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Name</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Password</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Address</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Source</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>salary</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Zip</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Mobile</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Email</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td align="center" bgcolor="#FFFFFF"><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['eid']; ?>"></td>
<td bgcolor="#FFFFFF"><? echo $rows['eid']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['ename']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['password']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['address']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['source']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['salary']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['zip']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['mobile']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['email']; ?></td>
</tr>
<?php
}
?>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td>
</tr>
<?php
// Check if delete button active, start this
if($delete){
for($i=0;$i<$count;$i++){
$del_id = $checkbox[$i];
$sql = "DELETE FROM $tbl_name WHERE eid='$del_id'";
$result = mysql_query($sql);
}
// if successful redirect to search1.php
if($result){
echo "<meta http-equiv=\"refresh\" content=\"0;URL=search1.php\">";
}
}
mysql_close();
?>
</table>
</form>
</td>
</tr>
</table>
Register globals is off (and this is good) so the line
if($delete){
should be
if (isset($_POST['delete'])) { ...
Moreover you need to restructure your code as it's absolutely unnecessery to make a select query to database when you have a post request to delete records.
Here is a complete code you need. Just replace yours with this one.
<?php
error_reporting(E_ALL);
$host = "localhost"; // Host name
$username = "a"; // Mysql username
$password = "a"; // Mysql password
$db_name = "b"; // Database name
$tbl_name = "emp_info"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Delete records
if (isset($_POST['delete']))
{
// Concatenate ids in a comma-separated string
$ids = implode(',', $_POST['checkbox']);
if (!empty($ids))
{
$sql = "DELETE FROM $tbl_name WHERE eid IN ($ids)";
$result = mysql_query($sql) or die(mysql_error());
}
// Redirect back
header('Location: search1.php');
die();
}
// Select records
$sql = "SELECT * FROM $tbl_name";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<form name="form1" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td bgcolor="#FFFFFF"> </td>
<td colspan="4" bgcolor="#FFFFFF"><strong>Delete multiple rows in mysql</strong></td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Name</strong></td>
</tr>
<?php while ($rows = mysql_fetch_array($result)) { ?>
<tr>
<td align="center" bgcolor="#FFFFFF">
<input name="checkbox[]" type="checkbox" id="checkbox[]"
value="<?php echo $rows['eid']; ?>">
</td>
<td bgcolor="#FFFFFF"><?php echo $rows['eid']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows['ename']; ?></td>
</tr>
<?php } ?>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF">
<input name="delete" type="submit" id="delete" value="Delete">
</td>
</tr>
</table>
</form>
</td>
</tr>
</table>
Before looping results from MySQL result variable, you should ALWAYS have to make sure that it contain any values:
if($total > 0)
{
while ($rows = mysql_fetch_array($result))
{
//your code goes here
}
}
Another issue you have here, is same as in your previous question, variable $delete is not defined, based on your code, it is not clear where it is coming from.
So, if $delete is actually a $_POST variable, your if statement should look like this:
if(isset($_POST['delete'])){}
Another issue, $checkbox it is not defined to. I would recommend you to read more about filter_input method as it can be very handy on sanitizing user submitted data.
Also you are using incorrect html tags instead of:
<td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td>
use correct TD tag which aligns text in center and makes it bold, also bgcolor should be defined in CSS file.
<th bgcolor="#FFFFFF">Id</th>
Your final code should look like this:
<?php
$host = "localhost"; // Host name
$username = "a"; // Mysql username
$password = "a"; // Mysql password
$db_name = "b"; // Database name
$tbl_name = "emp_info"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// Make sure that delete action was called using
//$delete = isset($_POST['delete']);
//OR
//$delete = array_key_exists('delete', $_POST);
//OR
$delete = filter_input(INPUT_POST, 'delete');
$selected = filter_input(INPUT_POST, 'checkbox', FILTER_VALIDATE_INT, FILTER_REQUIRE_ARRAY);
if ($delete && !empty($selected))
{
foreach ($selected as $id)
{
$sql = "DELETE FROM $tbl_name WHERE eid='$id'";
$result = mysql_query($sql);
}
// if successful redirect to search1.php
echo "<meta http-equiv=\"refresh\" content=\"0;URL=search1.php\">";
}
$sql = "SELECT * FROM $tbl_name";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
?>
<form name="form1" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<th bgcolor="#FFFFFF"> </th>
<th colspan="9" bgcolor="#FFFFFF">Delete multiple rows in mysql</th>
</tr>
<tr>
<th bgcolor="#FFFFFF">#</th>
<th bgcolor="#FFFFFF">Id</th>
<th bgcolor="#FFFFFF">Name</th>
<th bgcolor="#FFFFFF">Password</th>
<th bgcolor="#FFFFFF">Address</th>
<th bgcolor="#FFFFFF">Source</th>
<th bgcolor="#FFFFFF">salary</th>
<th bgcolor="#FFFFFF">Zip</th>
<th bgcolor="#FFFFFF">Mobile</th>
<th bgcolor="#FFFFFF">Email</th>
</tr>
<?php
if ($count)
{
while ($rows = mysql_fetch_array($result))
{
?>
<tr>
<td align="center" bgcolor="#FFFFFF">
<input name="checkbox[]" type="checkbox" id="checkbox" value="<?php echo $rows['eid']; ?>">
</td>
<td bgcolor="#FFFFFF"><?php echo $rows['eid']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows['ename']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows['password']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows['address']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows['source']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows['salary']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows['zip']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows['mobile']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $rows['email']; ?></td>
</tr>
<?php
}
}
mysql_close();
?>
<tr>
<td colspan="10" align="center" bgcolor="#FFFFFF">
<input name="delete" type="submit" id="delete" value="Delete">
</td>
</tr>
</table>
</form>
Please don't just copy paste it, read it and try to understand it.

Delete multiple rows with checkbox form DB table

Here is my code -
<?php
$host = "localhost"; // Host name
$username = ""; // Mysql username
$password = ""; // Mysql password
$db_name = "test"; // Database name
$tbl_name = "test_mysql"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
$sql = "SELECT * FROM $tbl_name";
$result = mysql_query($sql);
$count = mysql_num_rows($result);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<form name="form1" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td bgcolor="#FFFFFF"> </td>
<td colspan="4" bgcolor="#FFFFFF"><strong>Delete multiple rows in mysql</strong></td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Name</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Lastname</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Email</strong></td>
</tr>
<?php
while ($rows = mysql_fetch_array($result)) {
?>
<tr>
<td align="center" bgcolor="#FFFFFF"><input name="checkbox[]" type="checkbox"
id="checkbox[]" value="<? echo $rows['id']; ?>">
</td>
<td bgcolor="#FFFFFF"><? echo $rows['id']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['name']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['lastname']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['email']; ?></td>
</tr>
<?php
}
?>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete"
value="Delete"></td>
</tr>
<?
// Check if delete button active, start this
if ($delete) {
for ($i = 0; $i < $count; $i++) {
$del_id = $checkbox[$i];
$sql = "DELETE FROM $tbl_name WHERE id='$del_id'";
$result = mysql_query($sql);
}
// if successful redirect to delete_multiple.php
if ($result) {
echo "<meta http-equiv="refresh" content="0;URL = delete_multiple . php">";
}
}
mysql_close();
?>
</table>
</form>
</td>
</tr>
</table>
What I want is that data rows of the table, whose checkboxes are checked,
to be Deleted from the Database on click of Delete button.
I have tried these but it doesn't work well.
Please suggest me regarding the above code how to delete the selected rows
from DB, onclick of Delete button.
Theoretically it should work, but I have not tested
<?php
$host = 'localhost'; // Host name
$username = ''; // Mysql username
$password = ''; // Mysql password
$db_name = 'test'; // Database name
$tbl_name = 'test_mysql'; // Table name
// Connect to server and select databse.
mysql_connect($host, $username, $password) or die('cannot connect');
mysql_select_db($db_name) or die('cannot select DB');
$sql = 'SELECT * FROM `'.$tbl_name.'`';
$result = mysql_query($sql);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<form name="form1" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td bgcolor="#FFFFFF"> </td>
<td colspan="4" bgcolor="#FFFFFF"><strong>Delete multiple rows in mysql</strong> </td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Name</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Lastname</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Email</strong></td>
</tr>
<?php while ($rows = mysql_fetch_array($result)): ?>
<tr>
<td align="center" bgcolor="#FFFFFF"><input name="need_delete[<? echo $rows['id']; ?>]" type="checkbox" id="checkbox[<? echo $rows['id']; ?>]" value="<? echo $rows['id']; ?>"></td>
<td bgcolor="#FFFFFF"><? echo $rows['id']; ?></td>
<td bgcolor="#FFFFFF"><? echo htmlspecialchars($rows['name']); ?></td>
<td bgcolor="#FFFFFF"><? echo htmlspecialchars($rows['lastname']); ?></td>
<td bgcolor="#FFFFFF"><? echo htmlspecialchars($rows['email']); ?></td>
</tr>
<?php endwhile; ?>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td>
</tr>
<?php
// Check if delete button active, start this
if ( ! empty($_POST['delete'])) {
foreach ($_POST['need_delete'] as $id => $value) {
$sql = 'DELETE FROM `'.$tbl_name.'` WHERE `id`='.(int)$id;
mysql_query($sql);
}
header('Location: delete_multiple.php'); exit();
}
mysql_close();
?>
</table>
</form>
</td>
</tr>
</table>
Tested version:
Change lines 45-55 to
if($_POST['delete']){
$i = 0;
while(list($key, $val) = each($_POST['checkbox'])) {
$sql = "DELETE FROM $tbl_name WHERE id='$val'";
mysql_query($sql);
$i += mysql_affected_rows();
}
// if successful redirect to delete_multiple.php
if($i > 0){
echo '<meta http-equiv="refresh" content="0;URL=delete_multiple.php">';
}
}
The file should start with "<?php" and it is considered bad style to mix "<?" and "<?php" in the same file (lines 31-35 and line 43).
EDIT: forgot the $_POST[''] from $delete on line 45. If you have the register_globals ini-directive on, it does not matter (It's still dangerous and bad style though).

How to fetch data from database and display it in PHP?

How do I get data from a database using php and show it?
The database table has columns, labeled as ID & Number. ID is unique & fixed whereas Number is just a non-unique number. If someone visits
http://example.com/show.php?ID=32, and show.php should fetch the Number & display "Your number is XXX”
Please provide the code-samples.
<?php
//Connect to DB
$db = mysql_connect("localhst","user","pass") or die("Database Error");
mysql_select_db("db_name",$db);
//Get ID from request
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
//Check id is valid
if($id > 0)
{
//Query the DB
$resource = mysql_query("SELECT * FROM table WHERE id = " . $id);
if($resource === false)
{
die("Database Error");
}
if(mysql_num_rows($resource) == 0)
{
die("No User Exists");
}
$user = mysql_fetch_assoc($resource);
echo "Hello User, your number is" . $user['number'];
}
This is very basic but should see you through.
First get the id of the user(it may given while visiting or based on the details given while visiting)
Then write select query to the table which contains 'number' field.like
SELECT number FROM table1 WHERE table1.ID=IDFromtheuser;
try
SELECT number from numberTable nt
JOIN idTable it ON it.ID = nt.ID
WHERE it.ID = `your given id`
as i think your both tables are referenced with id
<?php
$host="localhost";
$username="";
$password="";
$db_name="multiple_del";
$tbl_name="test_mysql";
// Connect to server and select databse.
mysql_connect("$host", "root", "")or die("cannot connect");
mysql_select_db("multiple_del")or die("cannot select DB");
$sql="SELECT * FROM test_mysql";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td><form name="form1" method="post" action="">
<table width="400" border="0" cellpadding="3" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<td bgcolor="#FFFFFF"> </td>
<td colspan="4" bgcolor="#FFFFFF"><strong>Delete multiple rows in mysql</strong> </td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Name</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Lastname</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Email</strong></td>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td align="center" bgcolor="#FFFFFF"><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<? echo $rows['id']; ?>"></td>
<td bgcolor="#FFFFFF"><? echo $rows['id']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['name']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['lastname']; ?></td>
<td bgcolor="#FFFFFF"><? echo $rows['email']; ?></td>
</tr>
<?php
}
?>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete"></td>
</tr>
<?php
if($delete){
for($i=0;$i<$count;$i++){
$del_id = $checkbox[$i];
$sql = "DELETE FROM test_mysql WHERE id='$del_id'";
$result = mysql_query($sql);
}
}
?>
</table>
</form>
</td>
</tr>
</table>
its my code but its not working and error are show in this code:-
<?php
if($delete){
for($i=0;$i<$count;$i++){
$del_id = $checkbox[$i];
$sql = "DELETE FROM test_mysql WHERE id='$del_id'";
$result = mysql_query($sql);
}
}
?>
please help me.

Categories