How to delete random row using button in PHP? - php

<?php
include("connection.php");
echo "Do you really want to DELETE this field? " ;
?>
<form method="post">
<input type="submit" name="yes" value="YES" />
<?php
$res = mysql_query("SELECT * FROM members");
while($row = mysql_fetch_array($res))
{
if(isset($_REQUEST['yes']))
{
$id=$row['id'];
echo $id;
mysql_query("DELETE from members WHERE id= '$id' ");
header("location: view.php");
}
}
?>
<input type="submit" name="no" value="NO" />
<?php
if(isset($_REQUEST['no']))
{
header("location: view.php");
}
?>
</form>
</body>
This is my code for delet random row from list view when click on delete button but i m not getting the result so please help me out of these.

Pass db connection as second parameter to your mysql_query() to delete rows from members table:
mysql_query("DELETE from members WHERE id= '$id'" , $dbCon);
Here DB connection I mean something this that you have defined in your connection.php file:
$db_host="localhost";
$db_name="test";
$username="root";
$password="";
$dbCon=mysql_connect($db_host,$username,$password);
I hope this solve your problem!

Change this line:
mysql_query("DELETE from members WHERE id= '$id' ");
to that:
mysql_query("DELETE FROM members WHERE id= '".$id."' ");

Your query SELECT * FROM members without ordering will select all the lines in a unpredictable order.
The ifs in your while loop will be either always true or always false:
if the user click on the YES button, all the rows of the table will be deleted as you don't have exit; after the header("location: view.php"); (see this post)
if the user click the NO button, then every iteration of the while loop won't do nothing.
So what you should do:
Have an hidden parameter in your form containing the id of the field you want to delete.
Test when the user submit the form that the hidden field is present and sanitized.
Do not select all the rows of the table
Delete the rows secificaly by its primary key.
Call exit; after header("location: view.php");
When do an if inside a loop, move it outside the loop if possible if the values do not change.

<?php
include("connection.php");
echo "Do you really want to DELETE this field? " ;
?>
<form method="post">
<input type="submit" name="yes" value="YES" />
<?php
if(isset($_REQUEST['yes']))
{
if(isset($_GET['delet']))
{
$id = $_GET['delet'];
$res = mysql_query("SELECT * FROM members WHERE id = '$id' ");
$row = mysql_fetch_array($res);
$did = $row['id'];
$dname = $row['name'];
$dphn = $row['phn'];
/*echo $did;
echo $dname;
echo $dphn;*/
$ins = "INSERT INTO del (mid,name,phn) values ('$did','$dname','$dphn')";
mysql_query($ins);
mysql_query("DELETE FROM members WHERE id = '$id' ");
header('location: view.php');
}
}
?>
<input type="submit" name="no" value="NO" />
<?php
if(isset($_REQUEST['no']))
{
header("location: view.php");
exit;
}
?>
</form>

Related

insert multiple rows data into database fetched from another table

i am trying to bulid an online attendace in php, i am fetching student list from student table, and want to put all chkboxs if checkd as present and if unchecked as absent,
i am unable to do that.
<div class="attendance">
<form accept="att.php" method="POST">
<?php
$sel_sql = "SELECT * FROM student";
$run_sql = mysqli_query($conn,$sel_sql);
while($rows = mysqli_fetch_assoc($run_sql)){
$id = $rows['id'];
echo '<input type="checkbox" name="status" value="'.$id.'" checked>'.ucfirst($rows['f_name']).'';
}
?>
<input type="submit" name="submit_attendance" value="Post Attendance">
<?php echo $msg; ?>
</form>
</div>
it shows prefect students list, but i dont know how to set insert query for all of these chkboxes
try this query to insert from another table
SELECT * INTO TABLE2 FROM student
use where condition on student table as where student.column value to select checked values
Applied same above things with checkbox input field
echo '<input type="checkbox" name="status" value="'.$id.'" 'if($row['present_field_of_database']) ? 'checked' : ''
'>'.ucfirst($rows['f_name']).'';
it's fine then updated code with your problems i hope it's work for you
<div class="attendance">
<form accept="att.php" method="POST">
<?php
$sel_sql = "SELECT * FROM student";
$run_sql = mysqli_query($conn,$sel_sql);
while($rows = mysqli_fetch_assoc($run_sql)){
$id = $rows['id'];
// if your $id value is right from $rows['id'] then
// change your student table name to the another table where available status of the student
$wh_sql = "SELECT * FROM student WHERE id=".$id;
$run_wh_sql = mysqli_query($conn, $wh_sql);
$Wh_rows = mysqli_fetch_assoc($run_wh_sql);
// add student present or absent value to the rows data
$rows['status'] = $Wh_rows['status'];
}
// set value as A or P respectively absent or present add jquery plugins for onclick event while client click on checkbox change value respectively
echo '<input type="checkbox" name="status" value="'.$rows['status'].'" 'if($rows['status'] == "A") ?'checked': '' '>'.ucfirst($rows['f_name']).' onclick= "$(this).val(this.checked ? P : A)"';
?>
<input type="submit" name="submit_attendance" value="Post Attendance">
<?php echo $msg; ?>
</form>
</div>
if (isset($_POST['send'])) {
$s_id = $_POST['status'];
$id = $_POST['student'];
if ($s_id) {
foreach ($s_id as $s) {
foreach ($id as $i) {
if (mysqli_query($conn, "INSERT INTO attendence(s_id,status) VALUES('".
mysqli_real_escape_string($conn, $s)."','".
mysqli_real_escape_string($conn, $i)."')")) {
$msg = "success";
}else{
$msg = "failed";
}
}
}
}
}
i have 3 students. when i press send it sends 9 entries. i am unable to understand how to insert all students data
This is attendance table
This is attandance table
i want to put entries like this if check box chekd it wil post p and if not it wil post a. i just need how to insert all sutdent at once quert

how to get the last inserted id and how to check in where condition to update query using php

Hi iam inserting the data into database table and redirecting to another page and need to insert the details into the same table by comparing ids and email.But how to get the last inserted id and compare in where condition to update the details.
Here is my code:
index.php
<form method="post" action="properties.php" id="myform">
<input type='hidden' value="<?php echo $username; ?>" name='email'>
<tr><th>Interest Paid</th><td><input type="text" name="house_interest_paid" value=""/></td>
<tr><th>Total Interest Paid</th><input type="text" name="house_total_interest_paid" value=""/></td>
<tr><th>House Number</th><input type="text" name="house_number" value=""/></td>
<tr><th>Street</th><input type="text" name="house_street" value=""/></td>
<button type="submit" class = "large awesome yellows" onClick="document.location.href='ownerproperty.php'"> Specify Co-owners Property</button> </span>
</form>
properties.php
$email=$_POST['email'];
$interest=$_POST['house_interest_paid'];
$interestpaid=$_POST['house_total_interest_paid'];
$number=$_POST['house_number'];
$street=$_POST['house_street'];
$query=mysql_query("INSERT INTO house_details(email,house_interest_paid,house_total_interest_paid,house_number,house_street)values ('$email','$interest','$interestpaid','$number','$street')");
if($query)
{
session_start();
header("Location:ownerproperty.php");
}
else{
echo "Registration has not been completed.Please try again";
}
ownerproperty.php
<form style="display:none" method="POST" action="owner.php">
<h2>Owner Property details</h2>
<input type='hidden' value="<?php echo $username; ?>" name='email'>
<?php include "ownership.php"; ?>
<p><label for="name_coowner">Coowner Name</label> <input value="<?php echo $row['name_coowner'];?>" type="text" name="name_coowner" /></p>
<p><label for="pan_coowner">PAN Of Coowner</label> <input value="<?php echo $row['pan_coowner'];?>" type="text" name="pan_coowner" /></p>
<button type="submit" class = "medium" style="background-color: #2daebf;">Save</button>
</form>
Ownership.php
$res = "SELECT * FROM house_details
WHERE email ='$username'";
$result=mysql_query($res);
$row = mysql_fetch_array($result);
Owner.php
$email=$_POST['email'];
$owner_name=$_POST['name_coowner'];
$pan_owner=$_POST['pan_coowner'];
$query=mysql_query("UPDATE house_details SET name_coowner='$owner_name',pan_coowner='$pan_owner'
WHERE email='$email' AND house_details_id='2'");
if($query)
{
session_start();
header("Location:rentalproperty.php");
}
For the first time when i click on submit button the data is inserting into db and redirecting to ownerproperty.php .in that i need to get the inserted id and need to comapre that id and email and need to update the owner property details in the same column when the email and id are same.But how to get that id and compare in the where condition can anyone help me.
properties.php
$query=mysql_query("INSERT INTO house_details(email,house_interest_paid,house_total_interest_paid,house_number,house_street)values ('$email','$interest','$interestpaid','$number','$street')");
$id = mysql_insert_id(); //For last inserted id.
if($query)
{
session_start();
$_SESSION['sess_id'] = $id; // Set one session variable for last inserted id.
header("Location:ownerproperty.php");
}
owner.php
<?php
session_start(); // Start your session
$id = $_SESSION['sess_id']; // Use this id in query
$email=$_POST['email'];
$owner_name=$_POST['name_coowner'];
$pan_owner=$_POST['pan_coowner'];
$query=mysql_query("UPDATE house_details SET name_coowner='$owner_name',pan_coowner='$pan_owner'
WHERE email='$email' AND house_details_id='2'");
if($query)
{
session_start();
header("Location:rentalproperty.php");
}
[NOTE : mysql extensions are deprecated. Use PDO or mysqli_ database extensions.]
You can add this:
$stmt = 'SELECT LAST_INSERT_ID() as sessionId';
Which should grab the ID from the last insert.
$query=mysql_query("INSERT INTO house_details(email,house_interest_paid,house_total_interest_paid,house_number,house_street)values ('$email','$interest','$interestpaid','$number','$street')");
if($query)
{
//Last inserted ID
$last_id = $query->insert_id;
session_start();
header("Location:ownerproperty.php");
}
else{
echo "Registration has not been completed.Please try again";
}
You can add this:
$stmt = 'SELECT MAX(house_details_id) AS "id" FROM house_details';
$result=mysql_query($stmt);
$row = mysql_fetch_array($result);
$id = $row['id'];

Matching the database records with the textfield value and updating the database in php

I am creating a webpage wherein an admin can update a student's record(here it is the Demand Draft number), it will update the record for a particular student id.
The code I am working is below, the problem is the DD number gets updated for all the records in the database and not for the id mentioned in the textfield.
If anyone could offer a possible solution I would greatly appreciate it.
Here's the code:
<div class="main row">
<?php
$connect_mysql=mysql_connect("localhost","root","");
$mysql_db=mysql_select_db("mca",$connect_mysql);
?>
<form name="form1" method="POST" action="">
Enter the student's Registration ID :<span style="padding-left:20px"> <input type="text" id="studentsearch" name="studentsearch"></span>
</br> </br><span style="padding-left:190px"><input name="submit" type="submit" value="search"></span></br>
<?php
if(isset($_POST['submit']))
{
$id=$_POST['studentsearch'];
$query1="select 1 from user where id=$id" ;
$result1=mysql_query($query1) or die("Query Failed:".mysql_error());
if(mysql_num_rows($result1)>0)
{
echo 'student present';
}
else
{
echo 'student not present';
}
}
?>
</br>
</br>Enter the Demand Draft no : <span style="padding-left:46px"><input type="text" name="dd"></span>
</br></br><span style="padding-left:190px">
<input name="update" type="submit" value="update"></span><span style="padding-left:10px">
<input name="clear" type="submit" value="cancel" ></span>
<?php
if(isset($_POST['update']))
{
$connect_mysql=mysql_connect("localhost","root","") or die("cannot connect");
$mysql_db=mysql_select_db("mca",$connect_mysql);
$id1=$_POST['studentsearch'];
$dd=$_POST['dd'];
$sql="SELECT id FROM user ";
$result1 =mysql_query($sql,$connect_mysql) or die(mysql_error($connect_mysql));
while($row = mysql_fetch_array($result1))
if($id1=$row['id'])
{
$q="UPDATE user SET DD='$dd'";
$result2=mysql_query($q,$connect_mysql) or die("Query Failed".mysql_error());
}
mysql_close($connect_mysql);
}
?>
</form>
</div>
Although mysql_ is deprecated, the problem is here
$q="UPDATE user SET DD='$dd'";
This should be
$q="UPDATE user SET DD='$dd' WHERE id='$id1'";
And the same for this line, it needs a WHERE clause
$sql="SELECT id FROM user ";
AS
$sql="SELECT id FROM user WHERE id='$id1'";
EDIT:
Try this and let me know what your result is
if(isset($_POST['update'])) {
$connect_mysql=mysql_connect("localhost","root","") or die("cannot connect");
$mysql_db=mysql_select_db("mca",$connect_mysql);
$id1=$_POST['studentsearch'];
$dd=$_POST['dd'];
$sql="SELECT id FROM user WHERE id='$id1'";
$result1 =mysql_query($sql,$connect_mysql) or die(mysql_error($connect_mysql));
while($row = mysql_fetch_array($result1)) {
if(($row['id']) == $id1) {
$q="UPDATE user SET DD='$dd' WHERE id='$id1'";
$result2=mysql_query($q,$connect_mysql) or die("Query Failed".mysql_error());
}
mysql_close($connect_mysql);
} // Close While Loop
}
Add for troubleshooting data issues underneath the $dd variable:
echo $id1;
echo $dd;
Add the following just above the update submit button input:
<input type="hidden" name="ssresult" value="<?php if(isset($_POST['studentsearch'])) { echo $_POST['studentsearch']; } ?>">
And change your code to this:
if(isset($_POST['update'])) {
$connect_mysql=mysql_connect("localhost","root","") or die("cannot connect");
$mysql_db=mysql_select_db("mca",$connect_mysql);
$id1=$_POST['ssresult'];
$dd=$_POST['dd'];
$sql="SELECT id FROM user WHERE id='$id1'";
$result1 =mysql_query($sql,$connect_mysql) or die(mysql_error($connect_mysql));
while($row = mysql_fetch_array($result1)) {
if(($row['id']) == $id1) {
$q="UPDATE user SET DD='$dd' WHERE id='$id1'";
$result2=mysql_query($q,$connect_mysql) or die("Query Failed".mysql_error());
}
mysql_close($connect_mysql);
} // Close While Loop
}

Update a MySQL Database with a Form

I'm trying to create a form that allows a user to select a field from a drop down box and then change what is currently written in the field.
My current code allows me to view the drop down list select the field I want to change and then enter my new text into a box. But when I click update, nothing happens.
<?php
mysql_connect("", "", "") or die(mysql_error());
mysql_select_db("") or die(mysql_error());
$query = "SELECT * FROM news_updates";
$result=mysql_query($query) or die("Query Failed : ".mysql_error());
$i=0;
while($rows=mysql_fetch_array($result))
{
$roll[$i]=$rows['Text'];
$i++;
}
$total_elmt=count($roll);
?>
---------------------------------------------------------Now I have the form
<form method="POST" action="">
Select the news post to Update: <select name="sel">
<option>Select</option>
<?php
for($j=0;$j<$total_elmt;$j++)
{
?><option><?php
echo $roll[$j];
?></option><?php
}
?>
</select><br />
Text Field: <input name="username" type="text" /><br />
<input name="submit" type="submit" value="Update"/><br />
<input name="reset" type="reset" value="Reset"/>
</form>
-----------------------------------------------Now I have the update php
<?php
if(isset($_POST['submit']))
{
$username=$_POST['username'];
$query2 = "UPDATE news_updates SET username='$username' WHERE rollno='$value'";
$result2=mysql_query($query2) or die("Query Failed : ".mysql_error());
echo "Successfully Updated";
}
?>
Well, you seem to be missing the $value part. Something like this should do, for the last part:
<?php
if(isset($_POST['submit']))
{
$username = mysql_real_escape_string($_POST['username']);
$value = mysql_real_escape_string($_POST['sel']);
$query2 = "UPDATE news_updates SET username='$username' WHERE rollno='$value'";
echo $query2; //For test, to see what is generated, and sent to database
$result2=mysql_query($query2) or die("Query Failed : ".mysql_error());
echo "Successfully Updated";
}
?>
Also, you should not use mysql_* functions as they are deprecated. You should switch to mysqli or PDO.
First, try adding a value to your options, like so:
for($j=0;$j<$total_elmt;$j++)
{
?>
<option value="<?php echo $roll['id']; ?>"><?php echo $roll['option_name']; ?></option>
<?php
}
Then, when you parse your file, go like so:
$value = $_POST['sel']; // add any desired security here
That should do it for you
You need to change this
<?php
for($j=0;$j<$total_elmt;$j++)
{
?><option><?php
echo $roll[$j];
?></option><?php
}
to this
<?php
for($j=0;$j<$total_elmt;$j++)
{
?><option value="<?php echo $roll[$j];?>"> <?php echo $roll[$j];?></option> <?php
}
And you also need to change the update query from this
$query2 = "UPDATE news_updates SET username='$username' WHERE rollno='$value'";
to this
$query2 = "UPDATE news_updates SET username='$username' WHERE rollno='".$_POST['sel']."'";
N. B.: Here I am assuming that $_POST['sel'] has the value selected by the user from the drop down menu because I could not find anything which corresponds to $value

Delete from database php

I have a problem with a delete from database..So, I have:
<?php
include('createdb.php');
if(!empty ($_POST['tribuna']))
{
$delete = mysql_query("DELETE FROM tb_tribuna WHERE id = '".$_POST['tribuna']."';");
header("Location:index.php?a=buy"); //redirect
exit;
}
?>
<form id="formid" action="<?php echo $_SERVER['PHP_SELF'] ?>" method="post">
<label>Tribuna :</label> <select name="tribuna" class="tribuna">
<option selected="selected">-Select-</option>
<?php
$sql=mysql_query("select id,tribune_number from tb_tribuna ");
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$tribune_number=$row['tribune_number'];
echo '<option value="'.$id.'">'.$tribune_number.'</option>';
} ?>
</select><br/><br/>
<input name="delete" type="submit" id="delete" value="Delete">
</form>
When I push on submit nothing happens...
I want that when I select an option and when I press delete to delete from the database row...
Help plizzz friends..
Assuming that "createdb.php" has the correct database connection information:
$conn = mysql_connect("$host","$db_uid","$db_pwd");
mysql_select_db("$db", $conn);
make your delete function look like this:
$sql = "DELETE FROM tb_tribuna WHERE id = '$_POST[tribuna]' ";
$result = mysql_query($sql, $conn) or die(mysql_error());
You need to pass the db connection to mysql_query.
And add "or die mysql_error()" to your mysql statements so that when something doesn't work, you get an error message that helps point you to where the problem is.

Categories