Remove Delete Button for Wrong User? - php

I currently have a guestbook style thing that users post comments. Their username is stored in a cookie when logged on, and when a post is submitted their username is stored alongside their post in a mySQL database. I'm trying to remove the delete button next to the comment if the user logged in is not the one that posted it. Here is the nonworking code:
<?php
$username = $_COOKIE['sqlusername'];
mysqlLogin();
$sql = mysql_query("SELECT * FROM `posts`");
$sqlCnt = mysql_num_rows($sql);
if($sqlCnt != 0) {
echo "<table align='center'><tr><td class='tdno'><u><H4>Message</H4></u></td><td class='tdno'><u><H4>Poster</H4></u></td><td class='tdno'><u><H4>Time</H4></u></td></tr>";
while($row = mysql_fetch_array($sql)) {
if($row['username'] != $username) {
echo "<script type=\"text/javascript\">";
echo "document.getElementById('delete').innerHTML = \"\";";
echo "</script>";
}
$id = $row['id'];
echo "<form action='delete.php' method='POST'>";
echo "<tr><td>";
echo $row['message'];
echo "</td><td>";
echo $row['poster'];
echo "</td><td align='center' width='10'>";
echo $row['date'];
echo "<td align='left' width='1'>";
echo "<input type='hidden' name='id' value='$id'>";
echo "<span id='delete'><input type='submit' class='submit' value='Delete'></span>";
echo "</td></tr>";
echo "</form>";
}
echo "</table>";
} else {
echo "<div align='center'>Sorry, no posts found!</div>";
}
?>
Any thoughts?

Try:
if ($username == $row['poster']) {
echo "<input type='hidden' name='id' value='$id'>";
echo "<span id='delete'><input type='submit' class='submit' value='Delete'></span>";
} else {
echo " "
}

maybe its the issue with your browser and javascript. Try this :
if (document.getElementById) { // DOM3 = IE5, NS6
document.getElementById(id).style.display = 'none';
}
else {
if{ // IE 4
document.all.id.style.display = 'none';
}
}
else your logic looks fine(assuming you are storing the username and posts properly in database.)

Related

Get values of radio selected values of entire row to next file

I have displayed the values from mysql table along with radio buttons with different values. On submit button it should redirect to next page and display the selected values. My code on first file is as follows :
$query1 = "select * from booking";
$result1 = $connection->query($query1);
echo "<form method='post' action='edit.php'>";
echo "<center>";
echo "<table border='1'>";
$count = 0;
while($row = $result1->fetch_row())
{
echo "<tr>";
echo "<td width=".'10'.">";
$count = $count + 1;
#$sr=$sr+1;
echo "<input type='radio' name='select' value='".$count."' />";
#$row = mysqli_fetch_row($result1);
#echo "<tr>";
echo "<td width=".'10'.">";
$rooms = $row[0];
$srrooms = $rooms;
echo "<input type='text' name='srrooms' value='".$srrooms."' hidden='hidden'>";
#echo $srrooms;
echo $rooms;
echo "</td>";
echo "<td width=".'10'.">";
$no_roomss = $row[1];
$nosrrooms = $no_roomss;
echo "<input type='text' name='nosrrooms' value='".$nosrrooms."' hidden='hidden'>";
echo $no_roomss;
echo "</td>";
echo "<td width=".'10'.">";
$no_dayss = $row[2];
$nodays = $no_dayss;
echo "<input type='text' name='nodays' value='".$nodays."' hidden='hidden'>";
echo $no_dayss;
echo "</td>";
echo "<td width=".'10'.">";
$name = $row[3];
echo $name;
echo "</td>";
echo "</tr>";
#$count++;
}
echo "<input name='count' type='hidden' id='count'>"; // hidden input where counter value will be stored
echo "</table>";
echo "<input type='submit' name='submitRooms' />";
echo "</center>";
echo "</form>";
The javascript code is :
$(function(){
$('input[name="select"]').change(function(){
$('#count').val($("input[name='select']:checked").val());
});
});
edit.php code is :
<?php
if(isset($_POST['submitRooms'])){
#$count = $_POST['count'];
#$srrooms=$_POST['srrooms'.$count];
#$nosrrooms=$_POST['nosrrooms'.$count];
#$nodays=$_POST['nodays'.$count];
echo 'Selected values are: '. $srrooms . $nosrrooms . $nodays;
}
?>
You can use counter for submitting the values of the selected radiobutton's row as:
<?php
$query1 = "select * from booking";
$result1 = $connection->query($query1);
echo "<form method='post' action='edit.php'>";
echo "<center>";
echo "<table border='1'>";
$count = 0; // counter variable
while($row = $result1->fetch_row())
{
echo "<tr>";
echo "<td width=".'10'.">";
echo "<input type='radio' name='select' value='".$count."' />";
echo "<td width=".'10'.">";
$rooms = $row[0];
$srrooms = $rooms;
echo "<input type='hidden' name='srrooms".$count."' value='".$srrooms."' >"; // add counter value to every name of the input fields
echo $rooms;
echo "</td>";
echo "<td width=".'10'.">";
$no_roomss = $row[1];
$nosrrooms = $no_roomss;
echo "<input type='hidden' name='nosrrooms".$count."' value='".$nosrrooms."'>";
echo $no_roomss;
echo "</td>";
echo "<td width=".'10'.">";
$no_dayss = $row[2];
$nodays = $no_dayss;
echo "<input type='hidden' name='nodays".$count."' value='".$nodays."' >";
echo $no_dayss;
echo "</td>";
echo "<td width=".'10'.">";
$name = $row[3];
echo $name;
echo "</td>";
echo "</tr>";
$count++;
}
echo "<input name='count' type='hidden' id='count'>"; // hidden input where counter value will be stored
echo "</table>";
echo "<input type='submit' name='submitRooms' />";
echo "</center>";
echo "</form>";
?>
and then use jquery for saving the active radiobuttons count in the hidden count input field [after the above php code]
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type='text/javascript'>
$(function(){
$('input[name="select"]').change(function(){
$('#count').val($("input[name='select']:checked").val());
});
});
</script>
then on your edit.php fetch the posted data as:
<?php
if(isset($_POST['submitRooms'])){
#$count = $_POST['count'];
#$srrooms = $_POST['srrooms'.$count];
#$nosrrooms = $_POST['nosrrooms'.$count];
#$nodays = $_POST['nodays'.$count];
echo 'Selected values are: '. $srrooms . $nosrrooms . $nodays;
}
?>
You didn't have added the whole form code so please add the above mentioned form code and the reason why your code is not working is that you haven't added the count with the input field names. And their is no use of fetching the posted data with count in the edit.php till you don't have the input fields named with the $count variable
echo "<input type='hidden' name='srrooms".$count."' value='".$srrooms."' >";

MySQLi Update Record via Form loaded from PHP and SQL. Database wont update

I am required to create a drop down box which gathers the records from a database to populate the drop down. When one of the values is selected, a form is to be displayed which contains the data relating to the value selected.
The form is to have the function of showing the selected data, but also to update the record in the database when filled out and Submit.
I have created a php file to try and accomplish this, but Im getting errors such as undefined index and unknown column.
I am only new to PHP so this is a big task for me. Could someone have a look at my code and inform me if there are any errors.
Ive been trying to piece code together here and there from the net but its been tricky trying to get it all to work.
I am not getting any errors now after some tweaking, but the record wont update. I get a 'record updated successfully' message but the record isn't updated.
I am pretty sure the lack of a record update is coming down to the ID not getting collected properly via the $q=$row["BearId"] but if I use $q=$_GET["q"] I get nothing but errors. I am not completely positive this is the problem though, that is why Im asking the question here.
I would appreciate any help that you can give. Ive gotten so far with this thing and yet I cant get it to update the record.
EDIT: I have pinpointed the problem down to the id in
$sql = "UPDATE //snip WHERE BearId = '$q'";
$q=$row["BearId"];
If I manually change BearId to equal '1' then the record is updated.
updatebears.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Update Bears</title>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("result").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("result").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getvalues.php?q="+str,true);
xmlhttp.send();
}
</script>
<style>
// style elements
</style>
</head>
<body>
<h1>Update Bears</h1>
Select a Bear:
<br />
<select name="bears" onchange="showUser(this.value)">
<option value="">Select a BearId</option>
<?php
$query = "SELECT * FROM bears";
$mysqli = new mysqli('localhost','User','123','bears');
$result = $mysqli->query($query);
while($row = $result->fetch_assoc())
echo '<option value="'.$row["BearId"].'">'.$row["BearId"].'</option>';
?>
</select>
<br />
<?php
$q=$row["BearId"];
$mysqli = new mysqli('localhost','User','123','bears');
$sql = "SELECT * FROM bears WHERE BearId='".$q."'";
if(array_key_exists('_submit_check', $_POST))
{
$weight = $_POST['Weight'];
$sex = $_POST['Sex'];
$type = $_POST['Type'];
$colour = $_POST['Colour'];
$breed = $_POST['BreedId'];
$sql = "UPDATE bears SET Weight = '$weight', Sex = '$sex', Type = '$type', Colour = '$colour', Breed = '$breed' WHERE BearId = '$q'";
if($mysqli->query($sql) === TRUE)
{
echo 'Record updated successfully<br />';
}
else
{
echo $sql.'<br />' . $mysqli->error;
}
$mysqli->close();
}
?>
<br />
<div id="result"></div>
<br />
Click here to Visit Task 2 (Insert Bears) | Click here to Visit Task 3 (Display Bears)
</body>
</html>
getvalues.php
<?php
$q=$_GET["q"];
$mysqli = new mysqli('localhost','User','123','bears');
$sql = "SELECT * FROM bears WHERE BearId='".$q."'";
if($stmt = $mysqli->prepare($sql))
{
$stmt->execute();
$stmt->bind_result($BearId, $Weight, $Sex, $Type, $Colour, $Breed);
while ($stmt->fetch())
{
echo "<form method='post' name='form1' onsubmit='return validateForm()' action='updatebears.php'>";
echo "<p>";
echo "<label for='BreedId'>BreedId:</label>";
echo "<br />";
echo "<select id='BreedId' name='BreedId' />";
echo "<option value='".$Breed."'>".$Breed."</option>";
echo "<option value='1'>1. Polar</option>";
echo "<option value='2'>2. Brown</option>";
echo "<option value='3'>3. Panda</option>";
echo "</select>";
echo "</p>";
echo "<p>";
echo "<label for='Weight'>Weight(kg):</label>";
echo "<br />";
echo "<input type='text' id='Weight' name='Weight' value='".$Weight."' />";
echo "</label>";
echo "</p>";
echo "<p>";
echo "Sex: ";
echo "<br />";
echo "<label for='M'>Male</label><input type='radio' id='M' value='M' name='Sex'";
if($Sex=='M') echo "checked";
echo "/>";
echo "<label for='F'>Female</label><input type='radio' id='F' value='F' name='Sex'";
if($Sex=='F') echo "checked";
echo "/>";
echo "</p>";
echo "<p>";
echo "<label for='Type'>Type:</label> ";
echo "<br />";
echo "<input type='text' id='Type' name='Type' maxlength='100' value='".$Type."' />";
echo "</p>";
echo "<p>";
echo "<label for='Colour'>Colour:</label>";
echo "<br />";
echo "<input type='text' id='Colour' name='Colour' maxlength='20' value='".$Colour."' />";
echo "</p>";
echo "<p>";
echo "<input type='submit' value='Submit' />";
echo "<input type='reset' value='Reset' />";
echo "<input type='hidden' name='_submit_check' value=1 />";
echo "</p>";
echo "</form>";
}
}
else
{
echo 'Unable to connect';
exit();
}
?>
Thanks for the help.
I believe what you need to do is create a hidden input type for the BearId within the getvalues.php file. That way when your form performs the post you can get the BearId from the post as opposed to trying to get it from the $row['BearId']. I'm fairly certain $row['BearId'] is not the same $row['BearId'] that the user selected when he first goes to the getvalues.php form. Have you tried printing $row['BearId'] to html to verify it's a legitimate value?
if(array_key_exists('_submit_check', $_POST))
{
$id = $_POST['BearId']
$weight = $_POST['Weight'];
$sex = $_POST['Sex'];
$type = $_POST['Type'];
$colour = $_POST['Colour'];
$breed = $_POST['BreedId'];
$sql = "UPDATE bears SET Weight = '$weight', Sex = '$sex', Type = '$type', Colour = '$colour', Breed = '$breed' WHERE BearId = '$id'";
if($mysqli->query($sql) === TRUE)
{
echo 'Record updated successfully<br />';
}
else
{
echo $sql.'<br />' . $mysqli->error;
}
$mysqli->close();
}
?>
<h1>getvalues.php</h1>
<?php
$q=$_GET["q"];
$mysqli = new mysqli('localhost','User','123','bears');
$sql = "SELECT * FROM bears WHERE BearId='".$q."'";
if($stmt = $mysqli->prepare($sql))
{
$stmt->execute();
$stmt->bind_result($BearId, $Weight, $Sex, $Type, $Colour, $Breed);
while ($stmt->fetch())
{
echo "<form method='post' name='form1' onsubmit='return validateForm()' action='updatebears.php'>";
echo <input type="hidden" name="BearId" value='".$q."'>
echo "<p>";
echo "<label for='BreedId'>BreedId:</label>";
echo "<br />";
echo "<select id='BreedId' name='BreedId' />";
echo "<option value='".$Breed."'>".$Breed."</option>";
echo "<option value='1'>1. Polar</option>";
echo "<option value='2'>2. Brown</option>";
echo "<option value='3'>3. Panda</option>";
echo "</select>";
echo "</p>";
echo "<p>";
echo "<label for='Weight'>Weight(kg):</label>";
echo "<br />";
echo "<input type='text' id='Weight' name='Weight' value='".$Weight."' />";
echo "</label>";
echo "</p>";
echo "<p>";
echo "Sex: ";
echo "<br />";
echo "<label for='M'>Male</label><input type='radio' id='M' value='M' name='Sex'";
if($Sex=='M') echo "checked";
echo "/>";
echo "<label for='F'>Female</label><input type='radio' id='F' value='F' name='Sex'";
if($Sex=='F') echo "checked";
echo "/>";
echo "</p>";
echo "<p>";
echo "<label for='Type'>Type:</label> ";
echo "<br />";
echo "<input type='text' id='Type' name='Type' maxlength='100' value='".$Type."' />";
echo "</p>";
echo "<p>";
echo "<label for='Colour'>Colour:</label>";
echo "<br />";
echo "<input type='text' id='Colour' name='Colour' maxlength='20' value='".$Colour."' />";
echo "</p>";
echo "<p>";
echo "<input type='submit' value='Submit' />";
echo "<input type='reset' value='Reset' />";
echo "<input type='hidden' name='_submit_check' value=1 />";
echo "</p>";
echo "</form>";
}
}
else
{
echo 'Unable to connect';
exit();
}

previously submitted form data disappears when new form is submitted

I have multiple forms on a single page and all gets redirected to same page when form is submitted but the previously submitted form values disappears when new form is submitted.
I tried using sessions didn't worked for me what else? please help
<script language="javascript">
function row(x,y){
//var len=document.forms[x].name.value;
if(x.value.length >=3)
{
//alert("Message form no> "+y+"will be submited");
document.forms[y].submit();
}
}
</script>
</head>
<body >
<center>
<h2>Database App</h2>
<table>
<tr>
<th><lable>Name :</label></th>
<th><label>E_Id :</label></th>
<th><label>Email :</label></th>
<th><label>Other Info :</label></th></tr>
<tr>
<?php
error_reporting(E_ALL ^ E_NOTICE);
// code check for name in database and if exists,displays in table row
//for($i=0;$i<150;$i++)
//{
//$E_id=array();
if($_POST){
$i = $_GET["uid"];
//echo "fhwefwej==".$i;
$x='name'.$i;
// echo 'dasvds'.$x;
if($_POST[$x])
{
$name = strtolower($_POST[$x]);
$E_id[$i] = "";
$Email[$i] = "";
$Otherinfo[$i] = "";
$con = mysql_connect('localhost','root','') or die("npt");
$db = mysql_select_db("trainee")or die("nptdff");
$query = "Select * from reguser where fname like '".$_POST[$x]."%'";
$result = mysql_query($query);
mysql_num_rows($result);
if(mysql_num_rows($result)>0)
{
while($row=mysql_fetch_array($result))
{
$str=$row['fname'];
$initials = strtolower(substr($str,0,3));
if($name == $initials)
{
//echo "exist"."<br>";
$E_id[$i]= $row['fname'];
$Email[$i]=$row['lastname'];
$Otherinfo[$i]=$row['address'];
break;
}
}
}
else
{
$msg[$i] = "no user with these initials";
}
mysql_close($con);
}
}
for($i=0;$i<150;$i++)
{
//session_start();
//echo session_name($i)."<br>";
echo "<form name='form$i' action='new2.php?uid=$i' method='post'>";
echo "<td><input type='text' name='name$i' id='name$i' onkeyup='row(this,$i);' /><br />";
echo "<span id='availability_status' >";
if($_POST[$x]){echo $msg[$i];}
echo "</span> </td>";
echo "<td><input type='text' name='E_id' id='E_id' value='";
if(isset($_POST[$x])){ echo $E_id[$i];}
echo "' disabled='disabled' />";
echo "</td>";
echo "<td><input type='text' name='email' id='email' value='$Email[$i]' disabled='disabled' />";
echo "</td>";
echo "<td><input type='text' name='otherinfo' id='otherinfo' value='$Otherinfo[$i]' disabled='disabled' />";
echo "</td></tr>";
echo " </form>";
}
//echo '<script language="javascript">document.getElementById(\'name0\').focus();</script>';
?>
</table>
</center>
</body>
</html>
Why don't you Use AJAX. It will help to keep you posed different form information in back-end
you can either store those information in database or in file.
It will be the best way.

Restore radio button selection when revisiting a page

I have a PHP script that allows users to enter grades by selecting a radio button that corresponds to the students grade. It allows them to view the selected grades before they can be finally submitted. I also want the page to have the ability to go back to the selection page and remember the radio buttons that were selected so that the user doesn't have to set all of them again when going back. Here is what I have coded so far, it takes the user back to selection page but doesn't restore the radio button selection.
<?php
session_start();
$script_name = $_SERVER["PHP_SELF"];
if(!isset($_SESSION["course"]) || !isset($_SESSION["course"])) {
$_SESSION["course"] = $_POST["coursename"];
$_SESSION["section"] = $_POST["section"];
}
if(($_SESSION["authenticated"] == true || isset($_POST["back"])) && !isset($_POST["continue"])) {
$course = $_SESSION["course"];
$section = $_SESSION["section"];
$file_name = $course.$section.".txt";
$_SESSION["filename"] = $file_name;
// Open file containing student names.
$fp = fopen($_SESSION["filename"], "r") or die("Could not open file");
$students = array();
$i = 0;
echo "<h2>Grades Submission Form</h2>";
echo "<h2>Course: $course, Section: $section</h2>";
echo "<form action=\"$script_name\" method='post'>";
echo "<table border='1'>";
while (!feof($fp)) {
$line = trim(fgets($fp));
$students[$i++] = $line;
echo "<tr><td>$line</td>";
echo "<td><input type='radio' name=\"$line\" value='A'/>A</td>";
echo "<td><input type='radio' name=\"$line\" value='B'/>B</td>";
echo "<td><input type='radio' name=\"$line\" value='C'/>C</td>";
echo "<td><input type='radio' name=\"$line\" value='D'/>D</td>";
echo "<td><input type='radio' name=\"$line\" value='F'/>F</td>";
echo "</tr>";
}
echo "</table><br>";
echo "<input type='submit' name='continue'/>";
echo "</form>";
} elseif($_SESSION["authenticated"] == true && isset($_POST["continue"]) && !isset($_POST["back"])) {
unset($_POST["continue"]);
$keys = array_keys($_POST);
$values = array_values($_POST);
echo "<h2>Grades to Submit</h2>";
echo "<table border='1'>";
echo "<tr><th>Name</th><th>Grade</th></tr>";
for($i = 0; $i < count($keys); $i++) {
echo "<tr><td>{$keys[$i]}</td><td>{$values[$i]}</td></tr>";
}
echo "</table><br>";
echo "<form action='confirmation.php' method='post'>";
echo "<input type='submit' value='Submit Grades'/>";
echo "</form>";
echo "<form action=\"$script_name\" method='post'>";
echo "<input type='submit' value='Back'/>";
echo "</form>";
} else {
header("Location: main.php");
}
?>
You could serialize() an array containing the radio button states and store it in your session. When you go back, all you have to do is unserialize it and set the data again.

Form with radio buttons & checkboxes sending to php

Harmiih really helped me with my script (http://stackoverflow.com/questions/7510546/html-form-name-php-variable). Basically I have a table with questions. The form retrieves the questions from the table and then I need the selected answers to go to answer.php. Everything is working with the radio butttons but with the check boxes it's only sending the last selected checkbox. Can someone please help me?
form
$sql1="SELECT * FROM ex_question WHERE test_name = '$tid' AND q_type = 'mr' ORDER BY RAND() LIMIT 5";
$result1=mysql_query($sql1);
echo "<form method='post' action='answer.php'>";
while($row1 = mysql_fetch_array($result1))
{
$test_name=$row1['test_name'];
$q_nr=$row1['q_nr'];
$q_type=$row1['q_type'];
$question=$row1['question'];
$option1=$row1['option1'];
$option2=$row1['option2'];
echo "<P><strong>$q_nr $question</strong><BR>";
if ($q_type != 'mr') {
if($option1!="") {
echo "<input type='radio' name='question[$q_nr]' value='$option1'>$option1<BR>";
} else {
echo '';
}
if($option2!="") {
echo "<input type='radio' name='question[$q_nr]' value='$option2'>$option2<BR>";
} else {
echo '';
}
} else {
if($option1!="") {
echo "<input type='checkbox' name='question[$q_nr]' value='$option1'>$option1<BR>";
} else {
echo '';
}
if($option2!="") {
echo "<input type='checkbox' name='question[$q_nr]' value='$option2'>$option2<BR>";
} else {
echo '';
}
}
echo "<BR>";
echo "<BR>";
echo "</p>";
}
echo "<input type='submit' value='Send Form'>";
echo "</form>";
answer.php
<?php
//Key is $q_nr and $answer is selected $option
foreach($_POST['question'] as $key => $answer) {
echo $key;
echo $answer;
}
?>
You can use this as name:
name="question[$q_nr][]"
This will make sure you return an array containing all values of the selected checkboxes.
You need to have different name values in checkboxes.
For example name='question1[$q_nr]' and name='question2[$q_nr]'. The same name works only with grouping elements witch radio buttons are.
Or passing them as arrays:
name='question[$q_nr][1]' and name='question[$q_nr][2]'

Categories