Ive been working on my delete.php file to delete selected messages for literally hours on end without any headway. How would I delete messages with the codes I have set up?
Heres the code to how my delete.php is set up right now
<?php
session_start();
header("Location:inbox.php");
$user = $_SESSION['username'];
include 'connect.php';
foreach($_POST['messages'] as $num => $messages_id)
mysql_query("DELETE FROM messages WHERE messages_id='$messages_id' AND to_user='$user'");
?>
Here's the code to my entire inbox.php
<?php
require "connect.php";
echo "<hr><br><div id='mail'>";
// get the messages from the table.
$get_messages = mysql_query("SELECT messages_id FROM messages WHERE
to_user='$userfinal' ORDER BY messages_id DESC") or die(mysql_error());
$get_messages2 = mysql_query("SELECT * FROM messages WHERE to_user='$userfinal'
ORDER BY messages_id DESC") or die(mysql_error());
$num_messages = mysql_num_rows($get_messages);
// display each message title, with a link to their content
echo '<ul>';
for($count = 1; $count <= $num_messages; $count++)
{
$row = mysql_fetch_array($get_messages2);
$fromuser = $row['from_user'];
$messageid = $row['messages_id'];
$messagetitle = $row['message_title'];
$messageread = $row['message_read'];
$messagedate = $row['message_date'];
echo " <form name='send' method='post' action='delete.php'><input type='checkbox' name='delete' value='$messageid'></td><font face='helvetica'><font size='3'>$fromuser</font></font> • <div align='right'><a href='read_message.php?messages_id=$messageid'>$messagetitle</a></div>
<center><hr></center>
";
}
?>
<input type="submit" name="Submit" value="Delete Selected">
</table>
</div>
Please help out before my head explodes
You are using header("Location:inbox.php"); in the second line of your code, so the rest of it never gets executed.
Just move it to the end of the script, after you have deleted the messages you wanted to delete.
name='delete[]' value='<?php echo $messageid?>'
$_POST['delete']
What seems to be the problem is that you are adding a form tag for each checkbox (and not closing that form tag). Instead put all the checkboxes in the same form, and name them delete[] the brackets at the end put each checkbox in an array inside the $_POST array. So you can loop through them.
Here is an edited version (Note: not tested)
<?php
require "connect.php";
echo "<hr><br><div id='mail'>";
// get the messages from the table.
$get_messages = mysql_query("SELECT messages_id FROM messages WHERE
to_user='$userfinal' ORDER BY messages_id DESC") or die(mysql_error());
$get_messages2 = mysql_query("SELECT * FROM messages WHERE to_user='$userfinal'
ORDER BY messages_id DESC") or die(mysql_error());
$num_messages = mysql_num_rows($get_messages);
// display each message title, with a link to their content
echo "<form name='send' method='post' action='delete.php'>";
echo '<ul>';
for($count = 1; $count <= $num_messages; $count++)
{
$row = mysql_fetch_array($get_messages2);
$fromuser = $row['from_user'];
$messageid = $row['messages_id'];
$messagetitle = $row['message_title'];
$messageread = $row['message_read'];
$messagedate = $row['message_date'];
echo "
<input type='checkbox' name='messages[]' value='$messageid'></td>
<font face='helvetica' size='3'>$fromuser</font> •
<div align='right'>
<a href='read_message.php?messages_id=$messageid'>$messagetitle</a>
</div>
<center><hr></center>
\n\n\n";
}
echo '</form>';
?>
<input type="submit" name="Submit" value="Delete Selected">
</table>
</div>
Related
So I'm just making a simple program that puts names into a database. I got that part down, I can enter a name into a form, then display it on the page, but now I'd like to know how to delete them from the database, and no longer show them on the page.
I added a button next to each name that triggers the third if statement (with the commented out query), and from what I can tell it's best to run a query based on the element's id (my primary key that auto increments), but I have no idea how to get the id from the element who's button I'm clicking on.
How do I get the id from one of the elements in my while loop? Or if there's a better way to delete them, what's that?
if (mysqli_connect_errno()) {
die('could not connect');
}
if (isset($_POST['first_name'], $_POST['last_name'])){
$first_name = trim($_POST['first_name']);
$last_name = trim($_POST['last_name']);
$putitin = mysqli_query($db, "INSERT INTO names (first_name, last_name) VALUES ('$first_name', '$last_name')");
}
if (isset($_POST['del'])){
//$takeitout = mysqli_query($db, "DELETE FROM names WHERE id = ");
}
?>
<html>
<head>
</head>
<body>
<form action='' method='post'>
<div>
<label for "first_name">First name</label>
<input type="text" name="first_name">
</div>
<div>
<label for "last_name">Last name</label>
<input type="text" name="last_name">
</div>
<div>
<input type="submit" value="Insert">
</div>
</form>
<hr>
<?php
$resultset = $db->query('SELECT * FROM names');
if($resultset->num_rows != 0){
while($rows = $resultset->fetch_assoc()) {
$fname = $rows['first_name'];
$lname = $rows['last_name'];
$id = $rows['id'];
echo "<form action='' method='post'><p>Name: $fname $lname $id<input type='submit' name='del'></form></p>";
}
} else {
echo 'No results';
}
?>
</body>
</html>
This is one way.
change your html part to
<form action='' method='post'>
<input type='hidden' name='id' value='$id' />
<p>Name: $fname $lname $id
<input type='submit' name='del' value=''>
</form></p>
and your php
if (isset($_POST['del'])){
$id = $_POST['id'];
$takeitout = mysqli_query($db, "DELETE FROM names WHERE id = '$id'");
}
Note:
What you can do is to put all your input fields inside your while loop. Then assign values to each of them, but we have to use array to store them accordingly.
We can use checkbox to store the IDs.
What will happen, is user can select from the list of names they wanted to delete by ticking the corresponding checkbox, then pressing the Delete button below.
Your code
<form action="" method="POST">
<?php
$resultset = $db->query('SELECT * FROM names');
if($resultset->num_rows != 0){
while($rows = $resultset->fetch_assoc()) {
$fname = $rows['first_name'];
$lname = $rows['last_name'];
$id = $rows['id'];
echo '<input type="checkbox" name="id[]" value="'.$id.'">'.$fname.' '.$lname.'<br>';
} /* END OF WHILE LOOP */
?>
<input type="submit" value="Delete" name="delete">
</form>
And your PHP that will process the form:
<?php
if(isset($_POST["delete"])){
$counter = count($_POST["id"]);
for($x = 0; $x<$counter; $x++){
if(!empty($_POST["id"][$x])){ /* CHECK IF AN ITEM IS SELECTED */
/* DELETE QUERY */
if($stmt = $db->prepare("DELETE FROM names WHERE id = ?")){
$stmt->bind_param("i",$_POST["id"][$x]);
$stmt->execute();
$stmt->close();
} /* END OF PREPARED STATEMENT */
} /* END OF IF; CHECKING IF IT IS SELECTED */
} /* END OF FOR LOOP */
} /* END OF ISSET DELETE */
?>
I want to display question papers according to student's branch.
I create 5 tables in database "aptitude".
tables are as following:
itque,
etrxque,
extcque,
civilque,
mechque.
branch name is store in 'register' database.
If student is in IT department then only IT's question paper should display.
but there is some problem in logic. question paper is not displayed according to the student's branch.
code of test.php:
<html>
<body>
<?php
require_once('appvars.php');
require_once('connectvars.php');
// Make sure the user is logged in before going any further.
if (!isset($_SESSION['user_id'])) {
echo '<span style="color:#FFF;text-align:center;"><p class="login">Please log in to access this page.</p></span>';
exit();
}
else {
include("menu.php");
}
?>
<?php
$dbc=mysqli_connect("localhost","root","","register");
$query = "SELECT branch FROM user WHERE m_id = '" . $_SESSION['user_id'] . "'";
$data = mysqli_query($dbc, $query);
$row = mysqli_fetch_array($data);
if ($row != NULL) {
$Branch = $row['branch'];
}
else {
echo '<p class="error">There was a problem .</p>';
}
?>
<form action="./result.php" method="post">
<?php
$connect = mysql_connect("localhost" ,"root","");
mysql_select_db("aptitude");
$query = mysql_query("SELECT * FROM `$Branch` ORDER BY RAND() LIMIT 10 ");
while($rows = mysql_fetch_array($query)):
$q = $rows['Q_no'];
$qus = $rows['Question'];
$a = $rows['answer1'];
$b = $rows['answer2'];
$c = $rows['answer3'];
$d = $rows['answer4'];
$ans = $rows['correct'];
echo" <p> </p>";
echo "<p>Q:- $qus <br></p>";
echo "<p> A <input type=radio name = 'answer[$q]' value = '$a'></input>$a    <br>
";
echo " B <input type=radio name = 'answer[$q]' value = '$b'></input>$b    <br>
";
echo " C <input type=radio name = 'answer[$q]' value = '$c'></input>$c    <br>
";
echo " D <input type=radio name = 'answer[$q]' value = '$d'></input>$d <br><br> </p>";
endwhile;
?>
<center><input name="cmdSubmit" type="submit" id="cmdSubmit" value="Submit"/>
</center>
</form>
</body>
</html>
The biggest logic flaw is that if user_id isn't in the session and the user_id isn't in a cookie then you still allow processing to continue. You should force the user to login again.
Apache has the default session time of 20 minutes so you might want to increase the time to allow the students to complete the assessment otherwise when they come to save their answers there will be a server time out and no data saved.
required small changes
$query = mysql_query("SELECT * FROM ".$branch." ORDER BY RAND() LIMIT 10 ");
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 have this code in a loop in my code, The loop makes one submit button for every member found. I need each button to have the members name stored in it, in a way it can be sent though post when that button is clicked. Im not sure if this is possible with post but i was trying a way i do it with URLS. Does anyone know how to do this?
<input type="submit" value="Attack" name="Attack?name=<?php echo $Member_name; ?>" />
<?php
if(isset($_POST['Attack'])){
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_GET['name'])."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
}
Here is the whole code i was trying to store it in a hidden form but it only grabs the last member found and wont get others.
<?php
$sql = "SELECT name, rank FROM users ORDER BY rank DESC"; // Searches the database for every one who has being last active in the last 5 minute
$query = mysql_query($sql) or die(mysql_error());
$count = mysql_num_rows($query);
$i = 1;
while($row = mysql_fetch_object($query)) {
$Member_name = htmlspecialchars($row->name);
$Member_level = htmlspecialchars($row->rank);
?>
<td><?php echo $i; ?></td>
<td><?php echo $Member_name; ?></td><td><?php echo $Member_level; ?></td><td>
<input type="hidden" name="thename" value="<?php echo $Member_name; ?>">
<input type="submit" value="Attack" name="Attack" />
</td>
<?
if($i != $count) { // this counts the amount of people that are online and display the results.
echo "</tr><tr>";
}
$i++;
}
?>
<?php
if(isset($_POST['Attack'])){
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_POST['thename'])."'";
$query = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_object($query);
$profile_id = htmlspecialchars($row->id);
$profile_userip = htmlspecialchars($row->userip);
$profile_name = htmlspecialchars($row->name);
$profile_money = htmlspecialchars($row->money);
$profile_gang = htmlspecialchars($row->gang);
$profile_exp = htmlspecialchars($row->exp);
$profile_profile = htmlspecialchars($row->profile);
$profile_rank = htmlspecialchars($row->rank);
$profile_health = htmlspecialchars($row->health);
$profile_defence = htmlspecialchars($row->defence);
$profile_stanima = htmlspecialchars($row->stanima);
?>
OK, assuming everything else is working ok, and you are retrieving data.
Change this:
<input type="hidden" name="thename" value="<?php echo $Member_name; ?>">
<input type="submit" value="Attack" name="Attack" />
To this:
<form method="POST" action="">
<input type="hidden" name="name" value="<?php echo $Member_name; ?>">
<input type="submit" value="Attack" name="Attack" />
</form>
And also in your PHP, change this line:
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_GET['name'])."'";
To:
$sql = "SELECT * FROM users WHERE name='".mysql_real_escape_string($_POST ['name'])."'";
This isn't the best way to do this, you will be generating loads of HTML elements depending how many users you have, but it should solve you problem (providing everything else is working and receiving data).
HTML 5 & Javascript would be perfect for this and is something you should look into.
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
}
?>