Updating database using php - php

This code looks horrible and I know. I don't know how to fix it though. When I try and update the table using the edit web page, only the first row in the first column updates but the subtitle is not updating in the second column, first row. Is there a way to change this? Sorry for the terrible explanation.
Update Page
//Home Title
$homeTitleUpdate = $_POST["homeTitleChange"];
$editRow = $_POST["rowID"];
$query = " UPDATE Home SET title = '$homeTitleUpdate' WHERE homeID = '$editRow' ";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if ($result) {
echo "<p> - Title updated succesfully to $homeTitleUpdate.</p>";
} else {
echo "<p> - Title did not update. Something went wrong</p>";
}
//Home Subtitle
$homeSubtitleUpdate = $_POST["homeSubtitleChange"];
$query1 = " UPDATE Home SET subtitle = '$homeSubtitleUpdate' ";
$result1 = mysqli_query($conn, $query) or die(mysqli_error($conn));
if ($result) {
echo "<p> - Subtitle updated successfully to $homeSubtitleUpdate.</p>";
} else {
echo "<p> - Subtitle did not update. Something went wrong</p>";
}
Edit Page
<?php
echo "<h2 style='color:black'>";
echo "<input type'text' name='homeTitleChange' value=$homeTitle>";
echo "<input type='hidden' name='rowID' value=$getID>";
echo "</h2>";
echo "<h4 style='color:black'>";
echo "<input type'text' name='homeSubtitleChange' value=$homeSubtitle>";
echo "<input type='hidden' name='rowID' value=$getID>";
echo "</h4>";
?>
<input type="submit" value="save" />

<?php
echo "<h2 style='color:black'>";
echo "<form action="change to your file" method="post">
echo "<input type'text' name='homeTitleChange' value=$homeTitle>";
echo "<input type='hidden' name='rowID' value=$getID>";
echo "</h2>";
echo "<h4 style='color:black'>";
echo "<input type'text' name='homeSubtitleChange' value=$homeSubtitle>";
echo "<input type='hidden' name='rowID' value=$getID>";
echo "</h4>";
?>
<input type="submit" name="submit" value="save" />
</form>
You did not have a form
//Home Title
if(isset($_POST['submit'])){
if
(
!empty($_POST["homeTitleChange"])
&&
!empty($_POST["homeSubtitleChange"]) &&
!empty($_POST["rowID"])
)
{
$homeTitleUpdate = $_POST["homeTitleChange"];
$homeSubtitleUpdate = $_POST["homeSubtitleChange"];
$editRow = $_POST["rowID"];
$query = "UPDATE Home SET title = '$homeTitleUpdate', subtitle ='$homeSubtitleUpdate' WHERE homeID = '$editRow' ";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn));
if ($result) {
echo "<p> - Title/Subtitle updated succesfully to $homeTitleUpdate.</p>";
} else {
echo "<p> - Title/Subtitle did not update. Something went wrong</p>";
}
}
}
You can change your php and do it all within one query

You need to add 'where' condition while updating subtitle as well
$query1 = " UPDATE Home SET subtitle = '$homeSubtitleUpdate' WHERE homeID = '$editRow' ";
on other hand, you can update both of them in single query, like this
$query = " UPDATE Home
SET title = '$homeTitleUpdate', subtitle = '$homeSubtitleUpdate'
WHERE homeID = '$editRow' ";
wouldn't this be better? unless you have some specific reason

Related

Hidden input gets wrong ID

I have a php scripts whit a table thats sorts after time.
in that table i have a check box to mark if somthings is deleverd and i have a hidden input thats get the id. it worked yesterday but know it gets the id lowest on the table.
$sql = "SELECT * FROM `bestalning` WHERE lev=0
ORDER BY tid";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
echo "<form method='POST' action='ID_change.php'>";
echo "<div class='continer bg-vit table-rsponsive-sm '><table class='table'><thead class='thead-dark'>
<tr><th >".'Lev'."</th><th>".' '."</th><th >".'Artikelnr'."</th><th >".'Antal'."</th>
<th >".'Singnatur'."</th><th >".'Önskad ankomst'."</th><th >".'Skickad'."</th></tr></thead></div>";
while($row = mysqli_fetch_array($result)){
echo "<tbody><tr><td><input style='margin-right:5px;' name='levJA' type='checkbox' value='1'></td><td>
<input style='margin-right:5px;' name='RowID' type='hidden' value='".$row['ID']."'></td><td>".$row['artikelnr']."</td>
<td>".$row['antal']."</td><td>".$row['ovrigt']."</td><td>".$row['Tid']."</td><td>".$row['date']."</td></tr></tbody>";
}
echo " <input class='btn btn-dark m-1' type='submit' value='submit'></form>";
mysqli_close($conn);
ID_change.php
$Lev = $_POST['levJA'];
$ID = $_POST['RowID'];
$sql = "UPDATE bestalning SET lev='".$Lev."' WHERE ID='".$ID."'";
echo $sql;
if (mysqli_query($conn, $sql,)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>

Having issues updating an SQL table on submit with an HTML form

I am trying to create a function where a user can edit a preexisting post. When the user is taken to edit.php, they are presented with a form that shows them the existing data associated with that post. They can then make changes to any of the fields (description, category, add additional images, etc.) and, upon hitting a submit button, the updated information will show on the post page.
My issue with this is actually getting it to update the information. The form will show up with the preexisting info, and I can make changes to any of the fields. However, when I press submit, I am taken to the list of posts, yet the changes I made have not been updated in the SQL table.
There aren't any errors that are being returned upon hitting submit. Everything is running smoothly except for the fact things aren't actually being updated in the database.
I have been looking on several different sites for help on the matter, and I have tried several variations of my UPDATE query thinking that maybe I am calling it incorrectly. This is the iteration I am currently working with after attempting several other examples I found:
if($title && $price && $description && $category){
$editquery = "UPDATE post SET title='$title', price='$price', description='$description', category='$category' WHERE post_id='$id'";
$edquery = $db->prepare($editquery);
$edquery->bind_result("ssss", $title, $price, $description, $category);
$edquery->execute();
if($edquery){
echo "Updated!";
}else{
echo "error";
}
}else{
echo "missing data";
}
I am fairly new to PHP, so it is very possible that I am making simple syntax errors that I am not noticing. Or it could be some other portion of my code that I am not executing properly. If anyone could have a look at my code and help point me in the right direction, I would greatly appreciate it.
Also, I would like to add that yes, I know my code is vulnerable to injection. My only concern right now is getting this function to work. Any security measures I will deal with after getting this to work.
PHP
<?php
if(!isset($_GET['id'])){
header('Location: modify.php');
exit();
}else{
$id = $_GET['id'];
}
include('../includes/db_connect.php');
if(!is_numeric($id)){
header('Location: inventory.php');
}
if(isset($_POST['submit'])){
$title = $_POST['title'];
$price = $_POST['price'];
$description = $_POST['description'];
$category = $_POST['category'];
$title = $db->real_escape_string($title);
$price = $db->real_escape_string($price);
$description = $db->real_escape_string($description);
if($title && $price && $description && $category){
$editquery = "UPDATE post SET title='$title', price='$price', description='$description', category='$category' WHERE post_id='$id'";
$edquery = $db->prepare($editquery);
$edquery->bind_result("ssss", $title, $price, $description, $category);
$edquery->execute();
if($edquery){
echo "Updated!";
}else{
echo "error";
}
}else{
echo "missing data";
}
$postid = $db->insert_id;
for($i=0; $i<count($_FILES["images"]["name"]); $i++)
{
$filetmp = $_FILES["images"]["tmp_name"][$i];
$filename = $_FILES["images"]["name"][$i];
$filetype = $_FILES["images"]["type"][$i];
$filepath = "images/".$filename;
move_uploaded_file($filetmp, $filepath);
$sql = "INSERT INTO images (img_name, img_path, img_type, post_id) VALUES
('$filename', '$filepath', '$filetype', '$postid')";
$result = mysqli_query($db, $sql);
}
}
?>
The HTML form This is the only portion of the HTML that pertains to this function.
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST" enctype="multipart/form-data">
<?php
$editsql = "SELECT * FROM post INNER JOIN categories ON categories.category_id=post.category_id WHERE post_id=' ".$id." '";
$editquery = $db->query($editsql);
if($editquery->num_rows !=1){
header('Location: inventory.php');
exit();
}
$editrow = $editquery->fetch_object();
echo "<div class='form-group'>";
echo "<label>Title*</label>";
echo "<input type='text' name='title' class='form-control' value='".$editrow->title."' required>";
echo "</div>";
echo "<div class='form-group'>";
echo "<label>Price*</label>";
echo "<input type='text' name='price' class='form-control' value='".$editrow->price."'required>";
echo "</div>";
echo "<div class='form-group'>";
echo "<label>Category</label>";
echo "<select name='category' class='form-control'>";
echo "<option value='".$editrow->category_id."'>".$editrow->category."</option>";
$catquery = $db->query("SELECT * FROM categories");
while($row = $catquery->fetch_object()){
echo "<option value='".$row->category_id."'>".$row->category."</option>";
}
echo "</select>";
echo "</div>";
echo "<div class='form-group'>";
echo "<label>Description*</label>";
echo "<textarea type='textarea' name='description' class='form-control' required>".$editrow->description."</textarea>";
echo "</div>";
echo "<div class='form-group'>";
echo "<label>Image(s)</label>";
echo "<input type='hidden' name='size' value='1000000'>";
echo "<input multiple='multiple' name='images[]' type='file'/>";
echo "</div>";
echo "<div class='required'>";
echo "* indicates a required field";
echo "</div>";
echo "<button type='submit' name='submit' value='submit' class='btn btn-default'>EDIT POST</button>"
?>
</form>
EDIT
Whatever is happening with my code, I am unable to see any of the echoed statements after I press 'submit':
if($query){
echo "product updated";
}else{
echo "error";
}
}else{
echo "missing data";
}
Could it be possible that this is causing an issue?
if(!isset($_GET['id'])){
header('Location: modify.php');
exit();
}else{
$id = $_GET['id'];
}
Or that I need to use a hidden input along with this?
echo "<button type='submit' name='submit' value='submit' class='btn btn-default'>EDIT POST</button>"
EDIT 2
I've separated this into two files (edit.php and submitedit.php) to keep the $_GET and $_POST separated from one another. However, I am still experiencing the same issue where the database will not update.
edit.php I'm only showing the PHP and relevant HTML form
<?php
session_start();
$msg = "";
if(!isset($_GET['id'])){
header('Location: delete.php');
exit();
}else{
$id = $_GET['id'];
}
include('../includes/db_connect.php');
if (!isset($_SESSION['user_id'])) {
header('Location: login.php');
exit();
}
if(!is_numeric($id)){
header('Location: inventory.php');
}
?>
<!-- WHERE THE HTML STARTS -->
<form action="submitedit.php" method="POST" enctype="multipart/form-data">
<?php
$editsql = "SELECT * FROM post INNER JOIN categories ON categories.category_id=post.category_id WHERE post_id='$id'";
$editquery = $db->query($editsql);
if($editquery->num_rows !=1){
header('Location: inventory.php');
exit();
}
$editrow = $editquery->fetch_object();
echo "<div class='form-group'>";
echo "<label>Title*</label>";
echo "<input type='text' name='title' class='form-control' value='".$editrow->title."' required>";
echo "</div>";
echo "<div class='form-group'>";
echo "<label>Price*</label>";
echo "<input type='text' name='price' class='form-control' value='".$editrow->price."'required>";
echo "</div>";
echo "<div class='form-group'>";
echo "<label>Category</label>";
echo "<select name='category' class='form-control'>";
echo "<option value='".$editrow->category_id."'>".$editrow->category."</option>";
$catquery = $db->query("SELECT * FROM categories");
while($row = $catquery->fetch_object()){
echo "<option value='".$row->category_id."'>".$row->category."</option>";
}
echo "</select>";
echo "</div>";
echo "<div class='form-group'>";
echo "<label>Description*</label>";
echo "<textarea type='textarea' name='description' class='form-control' required>".$editrow->description."</textarea>";
echo "</div>";
echo "<div class='form-group'>";
echo "<label>Image(s)</label>";
echo "<input type='hidden' name='size' value='1000000'>";
echo "<input multiple='multiple' name='images[]' type='file'/>";
echo "</div>";
echo "<div class='required'>";
echo "* indicates a required field";
echo "</div>";
echo "<button type='submit' name='submit' value='submit' class='btn btn-default'>EDIT POST</button>"
?>
</form>
submitedit.php
<?php
if(!isset($_POST['id'])){
header('Location: delete.php');
exit();
}else{
$id = $_POST['id'];
include('../includes/db_connect.php');
if(isset($_POST['submit'])){
$title = $_POST['title'];
$price = $_POST['price'];
$description = $_POST['description'];
$category = $_POST['category'];
$title = $db->real_escape_string($title);
$price = $db->real_escape_string($price);
$description = $db->real_escape_string($description);
if($title && $price && $description && $category){
$editquery = "UPDATE post SET title='$title', price='$price', description='$description', category='$category' WHERE post_id='$id'";
$edquery = $db->prepare($editquery);
$edquery->bind_result("ssss", $title, $price, $description, $category);
$edquery->execute();
if($edquery){
echo "Updated!";
}else{
echo "error";
}
}else{
echo "missing data";
}
$postid = $db->insert_id;
for($i=0; $i<count($_FILES["images"]["name"]); $i++)
{
$filetmp = $_FILES["images"]["tmp_name"][$i];
$filename = $_FILES["images"]["name"][$i];
$filetype = $_FILES["images"]["type"][$i];
$filepath = "images/".$filename;
move_uploaded_file($filetmp, $filepath);
$sql = "INSERT INTO images (img_name, img_path, img_type, post_id) VALUES ('$filename', '$filepath', '$filetype', '$postid')";
$result = mysqli_query($db, $sql);
}
}
?>
You send your form with POST method while you try to read id from GET array. Change it to $_POST['id'], and you're all set

How do I create an edit-option for each row in a table?

I am using the following code to display certain rows from my database table:
<?php
$searchtype=$_POST['searchtype'];
$searchterm=$_POST['searchterm'];
$searchterm= trim($searchterm);
if (!$searchtype || !$searchterm)
{
echo 'Error';
exit;
}
if (!get_magic_quotes_gpc())
{
$searchtype = addslashes($searchtype);
$searchterm = addslashes($searchterm);
}
$db = include "connect2db.php";
$query = "select * from notes where ".$searchtype." like '%".$searchterm."%'";
$result = $db->query($query);
$num_results = $result->num_rows;
echo '<p>Number of rows found: '.$num_results.'</p>';
for ($i=0; $i <$num_results; $i++)
{
$row = $result->fetch_assoc();
echo '<i>';
echo stripslashes($row['date']);
echo '</i><br /> ';
echo '<b>';
echo stripslashes($row['notetitle']);
echo '</b><br /> ';
echo stripslashes($row['note']);
echo '<br /><br /> ';
echo '</p>';
}
$result->free();
$db->close();
?>
Now I would like to display an edit-link for each row displayed, that can open a new page in which it is possible to edit a specific row. I already have the code that lets you edit the row:
<?php
if ($_REQUEST['save']=="Save") { // is data submitted?
// create variables
$noteid = $_REQUEST['noteid'];
$coursename = $_REQUEST['coursename'];
$notetitle = $_REQUEST['notetitle'];
$note = $_REQUEST['note'];
$query = "UPDATE notes SET ";
$query .= "coursename='$coursename', ";
$query .= "notetitle='$notetitle', ";
$query .= "note='$note' ";
$query .= "WHERE noteid='$noteid'";
$result = $db->query($query);
} elseif ($_REQUEST['delete']=="Delete") { // is data to be removed?
$noteid = $_REQUEST['noteid'];
$query="DELETE FROM notes WHERE noteid='$noteid'";
$result = $db->query($query);
}
?>
<div class="formular">
<div class="row1">
<p>Id</p>
<p>Notetitle</p>
<p>Note</p>
</div>
<?php
$query = "SELECT * FROM notes ORDER BY noteid DESC";
$result = $db->query($query);
while ($row = mysqli_fetch_array($result)) {
echo "<form ".$_SERVER['PHP_SELF']." name='edit-form' method='post' class='row1'>\n";
echo "<p class='align_top padding_top'>".$row['noteid']."<input type='hidden' name='noteid' value='".$row['noteid']."' /></p>\n";
echo "<p class='align_top'><input type='text' name='notetitle' value='".$row['notetitle']."' /></p>\n";
echo "<p><textarea name='note' rows='10' cols='50'>".$row['note']."</textarea></p>\n";
echo "<p><input type='submit' name='save' value='Save' /></p>";
echo "<p><input type='submit' name='delete' value='Delete' /></p>";
echo "</form>\n";
}
echo '</div>';
$result->free();
$db->close();
?>
What I am struggling with is how to display an edit-link for each row that lets you open a page where you can edit/delete the content of only that row.
I hope someone can help, I am very new at this.
Thank you!
Add a button next to each row that opens an edit page (or modal) with the id inside, example: <button onclick="edit('randomId')">Edit RandomId </button>
You could implement something different that accepts the unique id of that specific row and open a new page or modal with it.

php multiple search textbox with one submit button

i would like to know how can i make a multiple search criteria with 2 or more textboxes and only one submit button.
my script is:
$sql = "select * from wp_studenti ";
if (isset($_POST['search'])) {
$search_term = mysql_real_escape_string($_POST['search_box']);
$sql .= " WHERE nume= '{$search_term}' ";
}
$query = mysql_query($sql) or die (mysql_error());
echo "<form name ='search_form' method='POST' action='search.php'>";
echo "<center><h3>Cauta:</h3> <input type='text' name='search_box' />";
echo "<input type='submit' name='search' value='Cauta' /></center>";
echo "</form>";
and my results page that shows after search page:
$sql = "select * from wp_studenti ";
if (isset($_POST['search'])) {
$search_term = mysql_real_escape_string($_POST['search_box']);
$sql .= "WHERE nume= '{$search_term}'";
}
echo "<center>\n";
echo "<table border='1'>";
echo "<thead>";
echo "<tr><th>Id</th>";
echo "<th>Nume</th>";
echo "<th>Localitate</th>";
echo "<th>Judet</th>";
echo "<th>Sector Financiar</th>";
echo "<th>Link</th></tr>";
echo "</thead>";
$rst = mysql_query($sql);
while($a_row = mysql_fetch_assoc($rst)) {
echo "<tr>";
echo "<td>"; echo $a_row['id']; echo "</td>";
echo "<td>"; echo $a_row['nume']; echo "</td>";
echo "<td>"; echo $a_row['localitate']; echo "</td>";
echo "<td>"; echo $a_row['judet']; echo "</td>";
echo "<td>"; echo $a_row['sector_financiar']; echo "</td>";
echo "<td>"; echo "<a href='results.php?id={$a_row['id']}'>{$a_row['link']}</a>" ; echo "</td>";echo "</tr>";
echo "</table>";
$sql = "select * from wp_studenti ";
if (isset($_POST['search'])) {
$search_term_by_Cauta = mysql_real_escape_string($_POST['search_box_1']);
$search_term_by_localitate = mysql_real_escape_string($_POST['search_box_2']);
//If you want both search mandatory, use "AND" Operator otherwise use "OR". If you want approximate search use "LIKE" Operator in bellow SQL
$sql .= " WHERE nume= '{$search_term_by_Cauta }' OR localitate = '{$search_term_by_localitate }' ";
}
$query = mysql_query($sql) or die (mysql_error());
echo "<form name ='search_form' method='POST' action='search.php'>";
echo "<center><h3>Cauta:</h3> <input type='text' name='search_box_1' />";
echo "<h3>localitate:</h3> <input type='text' name='search_box_2' />";
echo "<input type='submit' name='search' value='Cauta' /></center>";
echo "</form>";
Well you need another search box:
echo "<center><h3>Cauta:</h3> <input type='text' name='search_box1' /><input type='text' name='search_box2' />";
And you need to use that value in your SQL:
if (isset($_POST['search'])) {
$search_term1 = mysql_real_escape_string($_POST['search_box1']);
$search_term2 = mysql_real_escape_string($_POST['search_box2']);
$sql .= " WHERE nume= '{$search_term1}' OR nume= '{$search_term2}'";
}
But you will have to do some thinking about how the search should work, is it supposed to match exactly one OR the other? If you want the text to contain instead of exactly match, you can use the syntax nume LIKE '%searchword%'
Use mysqli instead of mysql, which is depreciated. By PHP, something like this;
<form method='post'>
<input type='hidden' name='srch' val='1'>
Search Type1: <input type='text' name='s1'>
<br>
Search Type2: <input type='text' name='s2'>
<button>Submit</button>
</form>
<?php
if(isset($_POST['srch']))
{
if(!empty($_POST['s1']))$search = $_POST['s1'];
else if(!empty($_POST['s2']))$search = $_POST['s2'];
else die ('No criteria entered');
rest of your code...
}
?>
Also see functions like mysqli_real_escape for security reasons.

PHP - Button to delete Item from MySQL

I am coding some video upload script and I am with the admin panel right now.
There I have a List with all Videos. And each video has one delete button on the right side.
When I click the button then this video should be deleted from database but its not working after I click the button nothing happens.
<?php
$query = mysql_query("SELECT * FROM `videos`");
while($row = mysql_fetch_assoc($query))
{
$id = $row['id'];
$name = $row['name'];
echo "<a href='watch.php?id=$id'>$name</a><br />
<input type='submit' name='remove' value='Delete'<br />";
}
if (isset($_POST['remove']))
{
foreach ($_POST['id'] as $the_id)
{
if (!mysql_query("DELETE FROM videos WHERE id = '$the_id'"))
{
echo mysql_error();
}
}
}
?>
Of course on the header I have the mysql connect query. This is just the php code for listing all videos and try to delete.
Here is an example of doing this with MySQLi, including binding parameters to avoid SQL injection -
if (isset($_POST['remove'])) {
$remove = $mysqli->prepare("DELETE FROM `videos` WHERE `id` = ?");
$vid_id = $_POST['vid_id'];
$remove->bind_param('s', $vid_id);
if(!$remove->execute() === true) {
echo $mysqli->error;
}
}
$query = "SELECT * FROM `videos`";
if ($result = $mysqli->query($query)) {
while($row = $result->fetch_object()){
$id = $row->id;
$name = $row->name;
echo "<a href='watch.php?id=$id'>$name</a><br />";
echo "<form name='delete_vid' method='post'>";
echo "<input type='hidden' name='vid_id' value='$id'>";
echo "<input type='submit' name='remove' value='Delete'<br />";
echo "</form>";
}
} else {
echo mysqli_error($connection);
}
$result->close();
Of course you will have to provide a $connection` to the database, but thsi should get you started not only with MySQLi but with adding a form for each video.
More on SQL Injection
Maybe the problem is in the html, each delete button must be in and independent form, with a hidden input with the id too.
echo "<a href='watch.php?id=$id'>$name</a><br />
<form method='post'><input type='hidden' value='$id'><input type='submit' name='remove' value='Delete'<br /></form>";
<form method="post" >
<?php
$query = mysql_query("SELECT * FROM `videos`");
while($row = mysql_fetch_assoc($query))
{
$id = $row['id'];
$name = $row['name'];
echo "<a href='watch.php?id=$id'>$name</a><br />
<button name='id' value='".$id."' type='submit' >Delete</button>
<br />";
}
if (!mysql_query("DELETE FROM videos WHERE id = '".$_POST['id']."'"))
{
echo mysql_error();
} else {
echo 'successfully deleted';
}
?>
</form>

Categories