'Edit' function for forum posts and such - php

I was looking online for a script that demonstrates how I would go about making it possible for users on my site able to edit fields and such, but I could not find anything about it. So I was wondering if someone could explain to me how it works or just demonstrate with a script? To make it clear, I want users to be able to edit stuff that they've submitted by simply clicking 'edit' and pressing a button to update whatever it was they changed.
Edit: I forgot to mention that what's been changed should update a table in a MySQL database.

You need 2 PHP files to do this. You could use a single file but the concept is easier to explain this way.
A form that will load the database content into the fields where users can then edit the values and then submit them for change by pressing a button once done.
A file that receives the changed information and updates the database.
Here is a code example for the first file:
<?php
// connect to SQL
$dbcnx = #mysql_connect("localhost", "db_name", "password");
if (!$dbcnx) {
echo( "<P>Unable to connect to the database server at this time.</P>" );
exit();
}
// connect to database
$dbcon = #mysql_select_db("db_table", $dbcnx);
if (!$dbcon) {
echo( "<P>Unable to locate DB table at this time.</P>" );
exit();
}
#data preparation for the query
$id = intval($_GET["id"]);
# selects title and description fields from database
$sql = "SELECT * FROM table_name WHERE id=$id";
$result = mysql_query($sql) or die(mysql_error());
# retrieved by using $row['col_name']
$row = mysql_fetch_array($result);
?>
<h3>Edit</h3>
<form action="save_edit.php" enctype="multipart/form-data" method="post" name="myForm" />
<table>
<tr>
<td><b>Title</b></td>
<td><input type="text" size="70" maxlength="100" name="title" value="<?php echo $row['title'] ?>"></td>
</tr>
<tr>
<td><b>Description</b></td>
<td><textarea cols="80" rows="18" name="description"><?php echo $row['description']; ?></textarea></td>
</tr>
</table>
<input type="hidden" name="id" value="<?php echo $id; ?>" />
<input name="enter" type="submit" value="Edit">
</form>
<?php
mysql_close($dbcnx);
?>
And here is an example of code for the second file where it receives the changes made by the user and updates the database.
<?php
// connect to SQL
$dbcnx = #mysql_connect("localhost", "db_name", "password");
if (!$dbcnx) {
echo( "<P>Unable to connect to the database server at this time.</P>" );
exit();
}
// connect to database
$dbcon = #mysql_select_db("db_table", $dbcnx);
if (!$dbcon) {
echo( "<P>Unable to locate DB table at this time.</P>" );
exit();
}
#data preparation for the query
$id = intval($_POST["id"]);
foreach ($_POST as $key => $value) $_POST[$key] = mysql_real_escape_string($value);
$sql = "UPDATE table_name SET
title='$_POST[title]',
description='$_POST[description]',
WHERE id=$id";
if (!mysql_query($sql,$dbcnx)) {
die('Error: ' . mysql_error());
}
mysql_close($dbcnx);
header ("location: http://www.domain.com/url_to_go_to_after_update");
?>

If you just need an idea how to create a basic edit form in PhP, that's easy enough. When they click the edit button take them to a new form. Pull the content from the database, using whatever database accessing api you are, and then initialize the field with it. For example, where $content has the content of the field:
echo '<textarea name="content">'.htmlspecialchars($content).'</textarea>';
When they submit the form, take whats now in the field and use it to update the table. It's the same as the original insert script, except that you use update statements instead of insert.

I'm not sure I understood what you said. If you want a way to edit things in place, you can use this jQuery plugin: Jeditable (with Ajax).

To extend Daniel's code a bit
<?php
$filename = "file.txt";
if ($_SERVER['REQUEST_METHOD'] == 'POST']) {
file_put_contents($filename, $_POST['content']);
header("Location: ".$_SERVER['PHP_SELF']);
exit;
}
$content = htmlspecialchars(file_get_contents($filename));
?>
<form method="POST">
<textarea name="content"><?php echo $content?></textarea><br>
<input type="submit">
</form>

Related

Post results back to same page as search form

I am doing a project and need some help please :) (full code at bottom)
The project needs to be accessed with PDO.
I need search results to appear on the same page as the search was entered.
This below doesnt seem right to me using GET instead of POST.. is this correct?
This works but I need to remove/hide this bit of code that appears when my page (index.php) first loads.
if(!isset($_GET['search']))
{ echo "Error, Please go back."; exit;}
How do i do that?
Also my second problem is I can not get the search form to search more than one field in a table. It just wont let me. I cant use this bit of code either
%'.$searchterm.'%
as it wont give me any feedback from the search. So i am using the
:searchterm
in
$searchterm = $_GET['search'];
$stmt = $conn->prepare("SELECT * FROM boxer WHERE weightclass LIKE :searchterm OR nationality ");
$stmt->bindValue(':searchterm','%'.$searchterm.'%');
$stmt->execute();
Here is my full code:
<?php
$servername = 'localhost';
$username = "root";
$password = "";
$dbname = "u1360138";
<?php
if(isset($_POST['search'])){
echo 'Search';
}
?>
<!-- Search facility 1 -->
<form action="index.php" method="get">
<label for="search">Enter a weight class. Need to be more than one searchs which wont work</label>
<input type="text" name="search" id="search">
<input type="submit" value="Search">
</form>
<?php
// DB Connection
try {$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);}
catch(PDOException $e)
{echo "Error conntecting to the DB: " . $e->getMessage();}
if(!isset($_GET['search']))
{ echo "Error, Please go back."; exit;}
// DB Connection
$searchterm = $_GET['search'];
$stmt = $conn->prepare("SELECT * FROM boxer WHERE weightclass LIKE :searchterm");
$stmt->bindValue(':searchterm','%'.$searchterm.'%');
$stmt->execute();
// loop displays loop
while ($boxer = $stmt->fetch(PDO::FETCH_OBJ))
{ echo "<ul>";
echo "<a href='details.php?idboxer=".$boxer->idboxer."'>";
echo "<li>".$boxer->firstname." ".$boxer->lastname."</li>";
echo "</a>";
echo "</ul>"; }
$conn=NULL;
?>
In good practices, use POST to send params when user SEND something to the server that will change data on the server (store in db for exemple or send an email). Use GET when user RETRIEVE something from the server, to read data (query a db). So prefer GET here.
To solve your issue, simply enclose the whole code that process the research in a "if(isset($_GET['search'])){}" section as below:
<?php
$servername = 'localhost';
$username = "root";
$password = "";
$dbname = "u1360138";
<?php
if(isset($_GET['search'])){
echo 'Search';
}
?>
<!-- Search facility 1 -->
<form action="index.php" method="get">
<label for="search">Enter a weight class. Need to be more than one searchs which wont work</label>
<input type="text" name="search" id="search">
<input type="submit" value="Search">
</form>
<?php
if(isset($_GET['search'])){
// DB Connection
try {$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);}
catch(PDOException $e)
{echo "Error conntecting to the DB: " . $e->getMessage();}
// DB Connection
$searchterm = $_GET['search'];
$stmt = $conn->prepare("SELECT * FROM boxer WHERE weightclass LIKE :searchterm");
$stmt->bindValue(':searchterm','%'.$searchterm.'%');
$stmt->execute();
// loop displays loop
while ($boxer = $stmt->fetch(PDO::FETCH_OBJ))
{
echo "<ul>";
echo "<a href='details.php?idboxer=".$boxer->idboxer."'>";
echo "<li>".$boxer->firstname." ".$boxer->lastname."</li>";
echo "</a>";
echo "</ul>";
}
$conn=NULL;
}
?>
This below doesnt seem right to me using GET instead of POST.. is this correct? This works but I need to remove/hide this bit of code that appears when my page (index.php) first loads.
It depends on whenever you want to use GET or POST. POST is more secure, so for submitting a form I'm always using POST. In that case you can leave this code:
if(isset($_POST['search'])){
echo 'Search';
}
You do need to change the form's action type to POST:
<form action="index.php" method="post">
....
Then add the end you need to get the search value from the POST instead of GET, because we changed the action type.
$searchterm = $_POST['search'];
So i figured this out and
<!-- HTML FORM SEARCH BAR -->
<form action="index.php" method="post">
<label for="enteredterm">Enter a Weight-class or a Nationality:</label>
<input type="text" name="enteredterm">
<input type="submit" name="search">
</form>
<!-- HTML FORM SEARCH BAR -->
if(isset($_POST['search'])){
$enteredterm = $_POST['enteredterm'];
if ($enteredterm ===""){
echo "error, enter something.";
} else {
$stmt = $conn->prepare("SELECT * FROM boxer WHERE weightclass LIKE :enteredterm OR nationality LIKE :enteredterm or lastname LIKE :enteredterm ORDER BY year");
$stmt->bindValue(':enteredterm','%'.$enteredterm.'%');
$stmt->execute();
$count= $stmt->rowCount();
echo "You entered ".$enteredterm." and returned ";
if($count <= 1){
echo $count." result.";
}else{
echo $count." results.";
}
// loop displays loop
while ($boxer = $stmt->fetch(PDO::FETCH_OBJ))
{ echo "<ul>";
echo "<a href='details.php?idboxer=".$boxer->idboxer."'>";
echo "<li>".$boxer->firstname." ".$boxer->lastname."</li>";
echo "</a>";
echo "</ul>"; }

Updating a database with simple php and mysql

I have a VERY simple form that is not working. What I am trying to accomplish is when the user clicks the update button, they are presented with a form filled in with the information. When they change the information and click update, they are sent back to the main form with all of their changes presented. Everything works but the update. When you change something and click update, nothing is changed. Here is the update form code:
<h4>Update Record</h4>
<?PHP
$con=mysqli_connect("localhost", "root", "", "customers");
//check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
?>
<form action="update_process.php" method="get">
Band: <input type="text" name="artist" value="<?php echo $_GET['artist'] ?>"/><br/>
Album: <input type="text" name="title" value="<?php echo $_GET['title'] ?>" /><br/>
Format: <select name="format">
<option value="Compact Disc" name="compact disc">compact disc</option>
<option value="Album" name="album">album</option>
<option value="Cassette" name="cassette">cassette</option>
<option value="MP3" name="mp3">mp3</option>
</select><br/>
Notes: <TEXTAREA NAME="notes" ROWS="3" COLS="30"><?php echo $_GET['notes'] ?>
</TEXTAREA><br/>
<input type="submit" value="Update" />
</form>
And here is the code for the update_process.php file:
<?php
$artist = $_GET['artist'];
$title = $_GET['title'];
$format = $_GET['format'];
$notes = $_GET['notes'];
//create connection to DB
$con=mysqli_connect("localhost", "root", "", "customers");
//check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "UPDATE music SET title='$title', artist='$artist', format='$format', notes='$notes'
WHERE id='$id'";
if ($con->query($sql) === TRUE) {
header('Location:index.php');
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
?>
In the WHERE clause you says where id = '$id', but where is the $id value set?
I think $id does not have a value.
I see some problems with your code:
1 - where id $id defined?
2 - I guess id is an integer field, so the 's around $id are not needed;
You've mixed object based and function based programming. You started with function based, so I'll show you that way. To query a database, you need to run:
mysqli_query($con,$sql);
Rather than:
$con->query($sql)
There are a few other problems security wise with your code, but skip the rest of my answer if you don't care.
You're not checking to see whether those GET parameters exist before you use them. Use:
if(isset($_GET['artist'],$_GET['track'],...)) {...}
You're also not escaping your query strings, making your site vulnerable to SQL injection. Use:
$artist = mysqli_real_escape_string($con,$_GET['artist']);
Good luck! Just go read the PHP docs, making sure you either take object or function approach for the entire script.

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.

editing existing image php mysql

I have the following code that displays a given image using php echo id from a mysql table. The php is:
<?php include 'dbc.php'; page_protect();
$id=$_GET['id'];
if(!checkAdmin()) {header("Location: login.php");
exit();
}
$host = $_SERVER['HTTP_HOST'];
$host_upper = strtoupper($host);
$login_path = #ereg_replace('admin','',dirname($_SERVER['PHP_SELF']));
$path = rtrim($login_path, '/\\');
foreach($_GET as $key => $value) {
$get[$key] = filter($value);
}
foreach($_POST as $key => $value) {
$post[$key] = filter($value);
}
?>
<?php
if($_FILES['photo'])
{
$target = "images/furnishings/";
$target = $target . basename( $_FILES['photo']['name']);
$title = mysql_real_escape_string($_POST['title']);
$pic = "images/furnishings/" .(mysql_real_escape_string($_FILES['photo']['name']));
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
mysql_query("update `furnishings` set `photo`='$pic' WHERE id='$id'") ;
echo "Image updated";
}
else
{
echo "Please select a new image to upload";
}
}
?>
The HTML is:
<form enctype="multipart/form-data" action="editfurnimage.php" method="POST">
<table width="450" border="2" cellpadding="5"class="myaccount">
<tr>
<td width="35%" class="myaccount">Current Image: </td>
<td width="65%"><img src='<?php
mysql_select_db("dbname", $con);
mysql_set_charset('utf8');
$result = mysql_query("SELECT * FROM furnishings WHERE id='$id'");
while($row = mysql_fetch_array($result))
{
echo '' . $row['photo'] . '';
}
mysql_close($con);
?>' style="width:300px; height:300px;"></td>
</tr>
<tr>
<td class="myaccount">New Image: </td>
<td><input type="file" name="photo" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" class="CMSbutton" value="Add" /></td>
</tr>
</table>
</form>
While the coding is adding the new image to the server, the mysql table doesnt seem to be updating with the new image - in fact no changes are being made - when I adjust the line:
mysql_query("update `furnishings` set `photo`='$pic' WHERE id='$id'") ;
to:
mysql_query("update `furnishings` set `photo`='$pic' WHERE id='8'") ;
it works though so assuming the issue is lying with this part of the code but not sure how to correct the code to pull the $id into the php correctly.
Finally, when the script runs I am trying to get the page "editfurnimage.php?id=$id" to reload following the user clicking the Add button - at the moment the page that is returned is "editfurnimage.php" which obviously doesnt show up any data from the table.
Any help much appreciated - and as always feel free to tear my coding apart - still learning!!
Thanks
JD
try to remove your single quotes around $id.
If your id field in the database in an int, then quotes should not be used around it.
EDIT: Missed this one - Where is $_GET['id'] being sent from, because your form sure isn't sending any id in the $_GET scope? Try adding the input with a name of 'id' and a value for it in to your form. also, use $_POST in your php file, not $_GET.
In your php, replace:
$id=$_GET['id'];
With
if(isset($_POST['id'])){
$id=$_POST['id'];
}else{
$id=$_GET['id'];
}
Then in your html add:
<input type="hidden" name="id" value="<?php echo $id; ?>"/>

search mysql database

Please help, Im trying to search for mysql records using an html form to display the corresponding record for the entered primary key.
Here's my html form:
<td><input type="submit" name="Submit" value="Search"></td>
And here's the new.php form action:,
mysql_select_db("Hospital", $con);
$result = mysql_query("SELECT HOSPNUM FROM t2 WHERE FIRSTNAME='{$_POST["fname"]}'");
while($row = mysql_fetch_array($result))
{
<input name="hnum" type="text" id="hospnum" value="<?php echo $row['HOSPNUM']; ?>" />
}
mysql_close($con);
?>
How do I get to display the hospnum in the html inputbox when I input the fname and then click the search button.
Note: This script, as-is, is vulnerable to sql-injections. The code that follows is not dealing with this, as it's out of the scope of the original question. Do not use this code as-is in a production environment.
You have a small problem jumping from PHP to HTML:
<?php
mysql_select_db("Hospital", $con) or die(mysql_error());
$fname = $_POST["fname"];
$result = mysql_query("SELECT HOSPNUM FROM t2 WHERE FIRSTNAME='{$fname}'");
?>
<h3>Results:</h3>
<?php while ( $row = mysql_fetch_array($result) ) { ?>
<input type="text" name="hnum" value="<?php echo $row["HOSPNUM"]; ?>" />
<?php } ?>

Categories