edit row from mysql - php

Ok, I'm not very good at php but trying to learn as much as possible. So I've made website with admin panel. In admin panel I show all rows from database with 2 buttons - 'Delete' and 'Edit'. Delete button is working but I have trouble with Edit. So here is how I show results with the buttons
for ($i = $start; $i < $end; $i++)
{
// make sure that PHP doesn't try to show results that don't exist
if ($i == $total_results) { break; }
// echo out the contents of each row into a table
echo "<tr>";
echo '<td><p>' . mysql_result($result, $i, 'id') . '</p></td>';
echo '<td>' . mysql_result($result, $i, 'caption') . '</td>';
echo '<td>' . mysql_result($result, $i, 'name') . '</td>';
echo '<td>' . mysql_result($result, $i, 'alt') . '</td>';
echo '<td>' . mysql_result($result, $i, 'title') . '</td>';
echo '<td>Delete</td>';
echo '<td>Edit</td>';
echo "</tr>";
}
When I click on Edit page goes to edit.php and url is with ID of choosen image. For ex (/edit.php?id=68). Here is edit.php
<form action="" method="post" enctype="multipart/form-data">
Choose category
<select name="img_category">
<option value="1">Cars</option>
<option value="2">Animals</option>
<option value="3" >PC's</option>
<option value="4" >Sport</option>
</select><br/><br />
Caption
<input type="text" name="caption" /><br /><br />
Alt
<input type="text" name="alt" /><br /><br />
Title
<input type="text" name="title" /><br /><br />
<input type="submit" name="submit" id="submit" value="Edit" /><br /><br />
</form>
<?php
if (isset($_POST['submit']))
{
require_once("../include/db.php");
$id =$_POST['id'];
$caption = $_POST['caption'];
$title = $_POST['title'];
$query = "UPDATE images SET caption = '$caption', title = '$title' WHERE id = '$id'";
$result = mysqli_query($con, $query) or die("Error in query: ".mysqli_error($con));
}
?>
I want to be able to edit caption, alt and title of the image. Now when I press 'Edit' nothing happen. I'm sure is not so hard but for me is kind of.

In your sql-statement, you don't seem to add in your id.
$query = "UPDATE images SET caption = '$caption', title = '$title' WHERE id = 'id'";
You should add the $
$query = "UPDATE images SET caption = '$caption', title = '$title' WHERE id = '$id'";
Update:
There doesn't seem to be an ID field in your form. You try to retrieve it in POST, but there is no such field to retrieve data from. You should pass the id to the query through the form or an other way.
Update2:
As others have said, easiest way to do this is gonna be to get your ID from GET instead of POST.
Change your
$id =$_POST['id'];
to
$id =$_GET['id'];

use GET method to catch id from url
just change
$id =$_POST['id'];
to
$id =$_GET['id'];

You are trying to retrieve a $_GET value with a $_POST, which would leave the $id variable empty.
Change the $id =$_POST['id']; to $id = $_GET['id'];
Also change your query to
$query = "UPDATE images SET caption = '$caption', title = '$title' WHERE id = '$id'";

Add an
<input type="hidden" name="id" value='<?=(int)$_GET['id'] ?>'/>
somewhere in the form.
Have to add: there are a couple of security issues with your code. Remember your code is not production ready! But that is not your question so i wont go into that.

try this
<?php
if (isset($_POST['submit']))
{
require_once("../include/db.php");
$id =$_GET['id'];
$caption = $_POST['caption'];
$title = $_POST['title'];
$query = "UPDATE images SET caption = '$caption', title = '$title' WHERE id = '$id'";
$result = mysqli_query($con, $query) or die("Error in query: ".mysqli_error($con));
}
?>

Related

Value not saving after form is submitted

I've created a mysql table with two columns. One is ID and other is Heading. I have a textarea on which I run UPDATE code and whenever someone submits a form its being updated in the datebase column under heading. And that works fine but I want to show the last inputted submit inside my textarea.
My code is showing the last inputted value but when I reset the page it all turns out blank and its not showing anymore. I looked out in datebase and the heading is still there so I don't know why its dissapearing from the front end.
My page:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
So for example if I type Aleksa, after submit it will get url like edit.php?heading=Aleksa&submit=Submit. And then when I delete url just to edit.php, the value is missing.
You can test the page here: https://www.easybewussterschaffen.com/admin/edit.php
This is happening, because it's always trying to insert the heading when you refresh the page. You should check to see if the request is GET or the request is POST, and only insert it if they're submitting the form.
Update your form method, specify it to POST, and specifically check the method or check for the existance of $_POST['submit'] as shown below:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
// Use one of the 2 if statements:
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Trying to insert a new heading
if (isset($_POST['submit'])) { // Alternative
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="POST">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
Alternatively, if you still wish to make a GET request, you should check to make sure that the heading is set:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
if (isset($_GET['submit'])) {
$heading = mysqli_real_escape_string($link, $_GET['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="GET">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
I did it like this, is this good tho? Its working
<?php
$sql = "SELECT * FROM content";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo '';
while($row = mysqli_fetch_array($result)){
echo $row['heading'];
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>

how to update form data with submit button in a while loop

I am trying to figure out mysqli (I am just a starting scripter). I created the following script to grab 3 different values from my database. And it prints it on the screen in different textareas and input fields.
What I want to be able to do is when I press the update button that it'll update the records in the database for the form where the button is attached to.
Can anyone give me some tips on how to achieve something like that?
<?php
$sqlserver = <SQLSERVER>;
$sqluser = <SQLUSER>;
$sqlpassword = <SQLPASSWORD>;
$sqldatabase = <SQLDATABASE>;
$mysqli = new mysqli($sqlserver, $sqluser, $sqlpassword, $sqldatabase);
$loggedinuserid= "5";
$standaardtekstlabel = $mysqli->query("SELECT standaardtekst_label FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
$standaardtekstnl = $mysqli->query("SELECT standaardtekst_tekst FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
$standaardteksten = $mysqli->query("SELECT standaardtekst_tekst_en FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
while ($NL_Tekst = mysqli_fetch_row($standaardtekstnl))
{
$label_Tekst = mysqli_fetch_row($standaardtekstlabel);
$EN_Tekst = mysqli_fetch_row($standaardteksten);
print '<form action="" method="POST">
<input type="text" name="standaardtekst_label" value=' . $label_Tekst[0] . '>
<textarea name="standaardtekst_tekst">' . $NL_Tekst[0] . '</textarea>
<textarea name="standaardtekst_tekst_en">' . $EN_Tekst[0] . '</textarea>
<input type="submit" value="update">
</form>';
}
?>
First of all, there is absolutely 0.0 reason why you're using 3 queries for the information you're trying to get. You can simply have: $standaardtekst = $mysqli->query("SELECT standaardtekst_label,standaardtekst_tekst,standaardtekst_en FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
Now regarding your question that is now probably obsolete:
Make the names of the input like this: standaardtekst_tekst[] saving it in an array.
You also need to have a unique(auto increment) key in your database like: id and put it in every form. You can even use the value of this field in the name like this: standaardtekst_tekst[$id].
You could edit your code a bit to look something like this:
<?php
$sqlserver = <SQLSERVER>;
$sqluser = <SQLUSER>;
$sqlpassword = <SQLPASSWORD>;
$sqldatabase = <SQLDATABASE>;
$mysqli = new mysqli($sqlserver, $sqluser, $sqlpassword, $sqldatabase);
$loggedinuserid= "5";
$q = $mysqli->query("SELECT standaardtekst_id, standaardtekst_label,
standaardtekst_tekst, standaard_tekst_tekst_en
FROM Standaardteksten
WHERE standaardtekst_account_pID='".$loggedinuserid."'");
while ($NL_Tekst = mysqli_fetch_row($standaardtekstnl))
{
$row = mysqli_fetch_row($q);
?>
<form action="" method="POST">
<input type="text" name="formData[<?= $row['id']; ?>][standaardtekst_label]" value="<?= $row['standaardtekst_label']; ?>">
<textarea name="formData[<?= $row['id']; ?>][standaardtekst_tekst]"><?= $row['standaardtekst_tekst']; ?></textarea>
<textarea name="formData[<?= $row['id']; ?>][standaardtekst_tekst_en]"><?= $row['standaardtekst_tekst_en']; ?></textarea>
<input type="submit" value="update">
</form>
<?php
}
?>
What I've done:
Made your 3 queries into a single query
Gave each form a unique id
Cleaned up the code a bit
This enables you to do the following:
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['formData'])) {
foreach ($_POST['formData'] as $id => $value) {
$stmt = $mysqli->query("UPDATE standaardtekst SET standaardtekst_label='".$value['standaadtekst_label']."', standaardtekst_tekst='".$value['standaardtekst_tekst']."', standaardtekst_tekst_en='".$value['standaardtekst_tekst_en']."' WHERE standaardtekst_id='".$id."'");
}
}
Thx for the help everyone. Everything is working right now.
This is the script i used to get it to work :-)
<?php
$sqlserver = <SQLSERVER>;
$sqluser = <SQLUSER>;
$sqlpassword = <SQLPASSWORD>;
$sqldatabase = <SQLDATABASE>;
$mysqli = new mysqli($sqlserver, $sqluser, $sqlpassword, $sqldatabase);
$loggedinuserid= "5";
$result = $mysqli->query("SELECT * FROM Standaardteksten WHERE standaardtekst_account_pID='".$loggedinuserid."'");
$row_s = $result->fetch_assoc();
do{
print '<form action="" method="POST">
<input type="text" name="standaardtekst_label" value=' . $row_s['standaardtekst_label'] . '>
<textarea name="standaardtekst_tekst">' . $row_s['standaardtekst_tekst'] . '</textarea>
<textarea name="standaardtekst_tekst_en">' . $row_s['standaardtekst_tekst_en'] . '</textarea>
<input type="text" name="standaardtekst_ID" value="'. $row_s['standaardtekst_ID'] .'"/>
<input type="submit" value="update">
</form>';
} while($row_s = $result->fetch_assoc());
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['standaardtekst_ID']))
{
$updatesql= sprintf("UPDATE Standaardteksten SET standaardtekst_label='%s', standaardtekst_tekst='%s', standaardtekst_tekst_en='%s' WHERE standaardtekst_ID='%s'",
$_POST[standaardtekst_label],
$_POST[standaardtekst_tekst],
$_POST[standaardtekst_tekst_en],
$_POST[standaardtekst_ID]
);
$mysqli->query($updatesql);
echo "Het volgende wordt aangepast: <br />", "Label:", $_POST[standaardtekst_label], "<br />" , "NL tekst:", $_POST[standaardtekst_tekst], "<br />" , "EN tekst:", $_POST[standaardtekst_tekst_en];
echo "<meta http-equiv='refresh' content='1;url=/form.php'>";
}
?>

How to read/send post data with php and hold a variable in it

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.

Why is the same single result looping multiple times?

There are multiple blog entries and each should be shown once. There is a "comment" link that shows and hides the comments for every blog entry. I can't figure out why the same first result keeps showing up. It happens every time I add a new comment (currently there's 5 and the blog section is displayed 5 times and only the first comment is shown for each).
Based on whether the user is logged in the "comments" link either shows a a log in link or (if logged in) a form field to submit a comment.
<?php
$conn = mysql_connect("...", "...", "...");
mysql_select_db("...");
$result = mysql_query("select * from blog");
$result2 = mysql_query("select * from blogcomment where blog.ID = blogcomment.blogID");
$i = 1;
while ($row = mysql_fetch_array($result))
{
echo "<h1>$row[title]</h1>";
echo "<p class ='second'>$row[blog_content]</p> ";
echo "<p class='meta'>Posted by .... • $row[date] • Comments<div id='something$i' style='display: none;'><p class='third' >";
$i++;
while ($row = mysql_fetch_array($result2))
{
echo "$row[commentdate] • $row[username]</p><p>said:</p> <p>$row[comment]</p>";
if (isset ($_SESSION["gatekeeper"])) {
echo '<form method="post" action="postcomment.php"><input name="ID" type = "hidden" value = "' . $row[ID] . '" /><input name="comment" id="comment" type="text" style="margin-left:20px;"/><input type="submit" value="Add comment" /></form></div>';
}
else {
echo '<p class="third">Signup to post a comment</p></div>';
}
}
}
mysql_close($conn);
?>
$i = 1;
while($row = mysql_fetch_array($result))
{

multiple row update with php into mysql database

I am trying to update multiple rows here.However I fail to point the right ID of the row.
<?php
$table = 'DynamicPage';
$query = mysql_query(Query::SelectAllFrom($table));
// Count table rows
$count = mysql_num_rows($query);
while ($row = mysql_fetch_array($query)) {
$id[] = $row['ID'];
echo '
<h3>Column name: </h3><input type="text" name="name" maxlength="30" value="' . $row['Name'] . '" />
<h3>Tekst: </h3><textarea type="text" name="fulltext[]" maxlength="2000">' . $row['FullText'] . '</textarea>';
}
echo '<input name="Submit" type="submit" value="Submit" />
</form>';
// Check if button name "Submit" is active, do this
if (isset($_POST['Submit'])) {
for ($i = 0; $i < $count; $i++) {
$queryUP = mysql_query("UPDATE $table SET Name='" . $_POST['name'] . "' WHERE id='??????????????'");
$result = mysql_query($queryUP);
}
if ($result) {
header("location:index.php");
}
}
?>
So far I can update the first row (if id='1') from the last <h3>Column name: </h3><input type="text" name="name"... I know that I am not passing the ID's in the right way, but I have to idea about the syntax. If anyone has an idea, please let me know :)
Thanks
Perhaps you should add a hidden input field with IDs:
HTML part
<input type="hidden" name="id[]" value="'.$row['ID'].'" />
<h3>Column name: </h3><input type="text" name="name[]" maxlength="30" value="'.$row['Name'].'" />
<h3>Tekst: </h3><textarea name="fulltext[]" maxlength="2000">'.$row['FullText'].'</textarea>';
PHP
for($i=0; $i<count($_POST['ID']); ++$i){
//query goes here
}
SQL QUERY
UPDATE $table SET Name='{$_POST['name'][$i]}', Tekst='{$_POST['fulltext'][$i]}' WHERE id='{$_POST['id'][$i]}'
This is from top off my head, not tested, but should give you an idea.
And of course, escape all the input fields.
Try this after your $_POST['Submit'] isset test:
for($i=0;$i<sizeof($id);$i++) {
$queryUP = mysql_query("UPDATE $table SET Name='".$_POST['name']."' WHERE id = " . $id[$i]);
$result = mysql_query($queryUP);
}
input type="text" ids="id[]" maxlength="30" value="'.$row['id'].'"
//then submit part
for($i=0; $i<count($_POST['id'];$i++) {
$queryUP = mysql_query("UPDATE $table SET Name='".$_POST['name']."' WHERE id='$_POST['id'][$i]'");
$result = mysql_query($queryUP);
}
You may concatenate $row['ID'] and $row['Name'] to create a name you can parse later
<h3>Column name: </h3><input type="text" name="name" maxlength="30"
value="' . $row['ID'] . '_' . $row['Name'] . '" />
then you can use something like:
list($name, $id) = explode($_POST['name'], '_');
** also note you have a security risk using user input directly inside SQL statement

Categories