I have a script that prints in the screen all the data of a table. Associated to each row of data, I have a delete button, and I would like that, when a button of any row is cliked, the row is deleted. To do so, I have got the following code:
$con = mysqli_connect("","","","");
$result = mysqli_query($con,"SELECT * FROM `clientes_pmt`");
while($row = mysqli_fetch_array($result)){
?> <button name="delete" value="<?php echo $row['id']; ?>" type="submit"><img src="paginas/borrar.jpg" /></button>
<a href="page<?php echo $row['nombre']; ?>">
<div><p><?php echo $row['nombre']; ?></p></div>
<div><p><?php echo $row['pais']; ?></p></div>
</a>
<section class="clearboth"></section><br><?php
}
if(isset($_POST['delete'])){
$id = $_POST['delete'];
$result = mysqli_query($con,"DELETE FROM `clientes_pmt` WHERE id = '$id'");
}
mysqli_close($con);
I receive no errors but the row is not being deleted.
Enclose the button inside a form element and set appropriate action and method attributes, something like:
<form action="/delete.php" method="POST">
<button ...> [your button]
</form>
You have to modify these line
$con = mysqli_connect("localhost","root","","YOUR DATABASE NAME");
To see the result you can put a header() to the end of this part of code:
if(isset($_POST['delete'])){
$id = $_POST['delete'];
$result = mysqli_query($con,"DELETE FROM `clientes_pmt` WHERE id = '$id'");
header('location:your_page_where_the_rows_are.php');
}
I think it may be because the $id was not getting added into the query.
Try bellow?
if(isset($_POST['delete'])){ $id = $_POST['delete']; $result = mysqli_query($con,"DELETE FROM clientes_pmt WHERE id = '".$id."'); }
Use Form tag and Header for redirect your page on same page.
Try This -
<?php
$con = mysqli_connect("","","","");
$result = mysqli_query($con,"SELECT * FROM `clientes_pmt`");
while($row = mysqli_fetch_array($result)){
?>
<form action="" method="post" >
<button name="delete" value="<?php echo $row['id']; ?>" type="submit"><img src="paginas/borrar.jpg" /></button>
</form>
<a href="page<?php echo $row['nombre']; ?>">
<div><p><?php echo $row['nombre']; ?></p></div>
<div><p><?php echo $row['pais']; ?></p></div>
</a>
<section class="clearboth"></section><br><?php
}
if(isset($_POST['delete'])){
$id = $_POST['delete'];
$result = mysqli_query($con,"DELETE FROM `clientes_pmt` WHERE id = '$id'");
header('location:'.$_SERVER['PHP_SELF']);
}
mysqli_close($con);
?>
Related
I am coding a website for an online university portal where I have a programs/courses page in which I am displaying the programs/courses on the page using data from the database in a PHP while-loop I have the enroll buttons also being displayed in that same while loop. but I'm having a bit of difficulty submitting the enroll buttons as when I click one of them all of them get submitted.
can anyone please let me know what I'm doing wrong here or if I have to use any javascript in this case!
<?php
session_start();
$con = mysqli_connect('localhost', 'root', '');
mysqli_select_db($con, 'htdatabase');
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
$id = $_SESSION['userID'];
$sql = "SELECT * FROM programs";
$result = $con->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$i = '';
$progID = $row["progID"];
$name = $row["progName"];
$halfTime = $row["halfTDuration"];
$fullTime = $row["fullTDuration"];
$fee = $row["fee"];
$descrip = $row["description"];
$stringname = strval($name);
$spaceRemoved = str_replace(' ', '', $stringname);
?>
<div class="card-header" id="headingOne">
<h5 class="mb-0">
<?php echo "<button class='btn btn-link' type='button' data-toggle='collapse' data-target='#$spaceRemoved' aria-expanded='false' aria-controls='$spaceRemoved'> $name </button>"; ?>
</h5>
</div>
<?php echo "<div id='$spaceRemoved' class='collapse' aria-labelledby='headingOne' data-parent='#accordionExample'>"; ?>
<div>
<div class="ccard-body col-md-9">
<h6><?php echo $descrip; ?></h6>
<hr>
<h5>Duration:</h5>
<h6>Full time: <?php echo $fullTime; ?></h6>
<h6>Half time: <?php echo $halfTime; echo $i; ?></h6>
<hr>
<h5 style="display: inline-block;">Estimated fees: $</h5><h5 style="display: inline-block;"><?php echo $fee ?></h5>
</div>
<form action="programs.php" method="post">
<div id="enroll" class="col-md-3">
<?php
$sql1 = "SELECT * FROM userprograms WHERE userID = '$id' AND progID = '$progID'";
$result1 = $con->query($sql1);
if ($result1->num_rows > 0) {
echo '<div id="enrolled" name="enrolled">ENROLLED</div>';
} else {
if (isset($_POST["enroll"])) {
$enrollqry = "insert into userprograms (userID, progID) values ('$id' , '$progID')";
mysqli_query($con, $enrollqry);
}
echo "<button name='enroll'type='submit'>ENROLL</button>";
}
?>
</div>
</form>
</div>
</div>
<?php
}
} ?>
You can specify a value for the button. like
<button name='enroll' value="<?php echo $program_id?>" type='submit'>ENROLL</button>
Then when checking for $_POST['enroll'] check the value and also validate it before entry to db.
After clicking the submit button a browser will send a POST request to programs.php with a form data, that includes values of input & button tags.
<input type="submit" name="course1" value="42">Subscribe</input>
<input type="text" name="first_name" placeholder="Your name"/>
Will send
course1=42
first_name=...
So you should either give a unique name to each submit button to be able to distinguish them on the server-side, or set up distinct values, as #mohamed-jailam mentioned above.
I am querying table in a while loop and has a button to update data for each row when clicked. But the update isn't happening .
The table column "Enroll" is to be updated based on clicking the submit button for that row.
<?php
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('mydata');
$query = "SELECT * FROM internship";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
if($row['Enroll']=="unenroll")
{
echo '<div class="intern">';
echo '<h1>'.$row['course'] . "</h1>" ;
echo '<h2>'.$row['compay'] . "</h2>";
echo "<h3>Stipend:Rs." . $row['stipend'] ."<h3>";
echo "<h3>Duration:".$row['duration']."month</h3>";
echo "<h3>Start-date:".$row['start date']."</h3>";
echo '</div>';
echo '<form method="post" action="">';
echo '<button name="add_to_cart" type="submit" ><h2>Enroll</h2></button>';
echo '</form>';
if(isset($_POST["add_to_cart"]))
{
$selectedProduct = $row["ID"];
$sql='UPDATE internship SET Enroll="enrolled" WHERE ID="$selectedProduct"';
mysql_query($connection,$sql);
header("location:enrolled.php");
}
}
}
mysql_close($connection);
?>
I am not able to update. Please help.
There are few issues with your code, such as:
You haven't included any ID value in the button of each row.
echo '<button name="add_to_cart" type="submit" ><h2>Enroll</h2></button>';
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ --> no value="..."
You are not using the selected row i.e. the row for which the button has been clicked to update the table row with enrolled.
$selectedProduct = $row["ID"];
^^^^^^^^^^
So your code should be like this:
<?php
$connection = mysql_connect('localhost', 'root', '');
mysql_select_db('mydata');
if(isset($_POST["add_to_cart"])){
$selectedProduct = $_POST['add_to_cart'];
$sql ="UPDATE internship SET Enroll = 'enrolled' WHERE ID = '$selectedProduct'";
mysql_query($connection,$sql);
header("location:enrolled.php");
exit();
}
$query = "SELECT * FROM internship";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)){
if($row['Enroll']=="unenroll"){
?>
<div class="intern">
<h1><?php echo $row['course']; ?></h1>
<h2><?php echo $row['compay']; ?></h2>
<h3>Stipend:Rs <?php echo $row['stipend']; ?><h3>
<h3>Duration: <?php echo $row['duration']; ?> month</h3>
<h3>Start-date: <?php echo $row['start date']; ?></h3>
</div>
<form method="post" action="">
<button name="add_to_cart" value="<?php echo $row['ID']; ?>" type="submit"><h2>Enroll</h2></button>
</form>
<?php
}
}
mysql_close($connection);
?>
Sidenote: Don't use mysql_* functions, they are deprecated as of PHP 5.5 and are removed altogether in PHP 7.0. Use mysqli or pdo instead. And this is why you shouldn't use mysql_* functions.
Update
My Page is not pulling information from the form for some reason it wants to keep all the fields empty even though if it is checked it should change the value of the QuestionOptionId. What i want it to do is when you check the radio button it saves the value to the session so it can be submitted later like a quiz. For some reason my code wont change the value or even obtain the value of QuestionOptionId
Code below
<?php
session_start();
//check if the user is already logged in.
if (!isset($_SESSION['username'])) {
header('Location: login.php');
}
$QuestionOptionId = "";
//get value from post data and store into session
if (isset($_POST['QuestionOptionId'])){
$_SESSION['QuestionOptionId'] = $_POST['QuestionOptionId'];
}
//get back from session
if (isset($_SESSION['QuestionOptionId'])){
$QuestionOptionId = $_SESSION['QuestionOptionId'];
}
print $_SESSION['username'];
?>
<?php
$con=mysqli_connect("localhost","root","root","root") or die();
//execute query
$query ="SELECT UserId from user where username = '".$_SESSION['username']."'";
$result=mysqli_query($con, $query);
$UserId=$result->num_rows;
while ($row = $result->fetch_assoc()) {
echo $row['UserId'];
$UserId=$row['UserId'];//etc...
}
?>
<body>
<header>
<p class="text-center">
Welcome :<?php echo $_SESSION['username'];
echo $UserId;
?>
</p>
<?php
$query="SELECT * from testview";
$res=mysqli_query($con, $query);
$rows=$res->num_rows;
$i=1;
while($result=mysqli_fetch_array($res))
{?>
<?php if($i==1){?>
<div id='question<?php echo $i;?>' class='cont'>
<form name="QuestionTime"Method="post" action="push.php">
<p class='questions' id="qtext<?php echo $i;?>"> <?php echo $i?>.<?php echo $result['QuestionText'];?></p>
<input <?php if ($QuestionOptionId=='3'){ echo 'checked="checked"';} ?>type="radio" value="1" id='radio1_<?php echo $result['QuestionOptionId'];?>'name="1"/>
<?php
$query="SELECT OptionChoiceName FROM testview WHERE OptionChoiceId=3";
$res=mysqli_query($con, $query);
$rows=$res;
$i=1;
while($result=mysqli_fetch_array($res))
echo $result['OptionChoiceName'];?>
<input <?php if ($QuestionOptionId=='4'){ echo 'checked="checked"';} ?> type="radio" value="2"id='radio1_<?php echo $result['QuestionId'];?>'name="1"/>
<?php
$query="SELECT OptionChoiceName FROM testview WHERE OptionChoiceId=4";
$res=mysqli_query($con, $query);
$rows=$res;
$i=1;
while($result=mysqli_fetch_array($res))
echo $result['OptionChoiceName'];
?>
<br><br>Selected Value: <?php echo $QuestionOptionId; ?>
<br/>
<?php
$_SESSION['UserId']=$UserId;
?>
<button id='next<?php echo $i;?>' class='next btn btn-success' type='submit'>Finish</button>
</div>
<?php } $i++;} ?>
</form>
</div>
</div>
</header></header>
any help would be grand thanks
You were not fethcing QuestionOptionId & QuestionId. Try with this query -
SELECT OptionChoiceName, QuestionOptionId, QuestionId FROM testview WHERE OptionChoiceId=3
This should be -
if(isset($_SESSION['QuesitonOptionId']))
{
$QuestionOptionId= $_SESSION['QuesitonOptionId'];
}
I can't seem to be able to update any records except the first one.
I am not sure how to modify any of the displayed records.
<?php
if(isset($_POST["action"]) == "update")
{
$id = $_POST['m_id'][0];
$type = $_POST['type'][0];
// if I echo $id & $type, it only gives me the first record.**
mysql_query("
UPDATE membership_type
SET mt_type ='$type'
WHERE mt_id = '$id'"
);
}
?>
ALl of this is within the same php page.
<form name=form action='' method='post'>
<?php
$result=mysql_query("SELECT * FROM membership_type;");
while($rows=mysql_fetch_array($result))
{ ?>
<input size=35 class=textField type=text name='type[]' value='<?php echo $rows['mt_type']; ?>'>
<input type=hidden name='m_id[]' value="<?php echo $rows['mt_id']; ?>">
<input type=submit value="Update">
<?php
}
?>
How do I edit any of the displayed records by simply clicking Update button???
First: You should NEVER use the mysql_* functions as they are deprecated.
Second: Try this code:
<?php
// Get a connection to the database
$mysqli = new mysqli('host', 'user', 'password', 'database');
// Check if there's POST request in this file
if($_POST){
foreach($_POST['m_id'] as $id => $type){
$query = "UPDATE membership_type
SET mt_type = '".$type."'
WHERE mt_id = '".$id."'";
// Try to exec the query
$mysqli->query($query) or die($mysqli->error);
}
}else{
// Get all membership_type records and then iterate
$result = $mysqli->query("SELECT * FROM membership_type") or die($mysqli->error); ?>
<form name='form' action='<?php echo $_SERVER['PHP_SELF'] ?>' method='post'>
<?php while($row = $result->fetch_object()){ ?>
<input size='35'
class='textField'
type='text'
name='m_id[<?php echo $row->mt_id ?>]'
value='<?php echo $row->mt_type; ?>'>
<input type='submit' value="Update">
<?php } ?>
</form>
<?php } ?>
Third: In order to add more security (this code is vulnerable), try mysqli_prepare
Only the first record is updated on every form submission because you have set $id = $_POST['m_id'][0], which contains the value of the first type[] textbox. To update all the other records as well, loop through $_POST['m_id'].
Replace it. Hope this works.
<?php
if(isset($_POST["action"]) == "update")
{
$id = $_POST['m_id'];
$type = $_POST['type'];
$i = 0;
foreach($id as $mid) {
mysql_query("UPDATE membership_type
SET mt_type='".mysql_real_escape_string($type[$i])."'
WHERE mt_id = '".intval($mid)."'") OR mysql_error();
$i++;
}
}
?>
Try this :
if(isset($_POST["action"]) == "update")
{
$id = $_POST['m_id'];
$type = $_POST['type'];
$loopcount = count($id);
for($i=0; $i<$loopcount; $i++)
{
mysql_query("
UPDATE membership_type
SET mt_type ='$type[$i]'
WHERE mt_id = '$id[$i]'"
);
}
}
You HTML was malformed and you were passing as an array but then only using the first element. Consider:
<form name="form" action="" method="post">
<?php
$result = mysql_query("SELECT * FROM membership_type;");
while($row = mysql_fetch_array($result))
echo sprintf('<input size="35" class="textField" type="text" name="m_ids[%s]" value="%s" />', $row['mt_id'], $row['mt_type']);
?>
<input type="submit" value="Update">
</form>
Then the server script:
<?php
if(isset($_POST["action"]) && $_POST["action"] == "Update"){
foreach($_POST['m_ids'] as $mt_id => $mt_type)
mysql_query(sprintf("UPDATE membership_type SET mt_type ='%s' WHERE mt_id = %s LIMIT 1", addslashes($mt_type), (int) $mt_id));
}
There are other things you could be doing here, eg. prepared statements, but this should work.
I need some help with PHP and SQL. Im doing a website where you can post notes in different subjects (Work, Home, School, and so on). After every note that being selected from my database I want a button that can delete that specific post when it's not needed anymore. I can make it delete but is deletes wrong note, always the one above or below. I don't know whats wrong with my code? Please help me.
<?php
$query = "SELECT * FROM notes WHERE subject='Work' order by id desc";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$subject = $row['subject'];
$date = $row['date'];
$note = $row['note'];
print "<p><strong>$subject</strong> ($id), $date </p>";
print "<p> $note </p>";
?>
//delete button starts here here
<form id="delete" method="post" action="">
<input type="submit" name="delete" value="Delete!"/>
<?php
if(isset($_POST['delete'])){
$query = "DELETE FROM notes WHERE id=$id";
$result = mysql_query($query);
}
?>
</form>
<?php
}
?>
And when I press delete I get this:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/mirho663/www-pub/webbpage/menu2.php on line 40
What does that mean and how do I fix it?
I updated your script below, try it if it works.
<?php
if(isset($_POST['delete'])){
$id = $_POST['delete_rec_id'];
$query = "DELETE FROM notes WHERE id=$id";
$result = mysql_query($query);
}
$query = "SELECT * FROM notes WHERE subject='Work' order by id desc";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$subject = $row['subject'];
$date = $row['date'];
$note = $row['note'];
print "<p><strong>$subject</strong> ($id), $date </p>";
print "<p> $note </p>";
?>
//delete button starts here here
<form id="delete" method="post" action="">
<input type="hidden" name="delete_rec_id" value="<?php print $id; ?>"/>
<input type="submit" name="delete" value="Delete!"/>
</form>
<?php
}
?>