Error when editing data in database with mysql - php

This is my code which shows current events and lets the user change the date, name or venue of the event.
I keep getting a 500 error for some reason. I think it is due to the information being passed to and from the database.
database set up is :userid ,eventname, venue, date, name ,eventid... respectivley
<div class="current events">
<h1>Your Current Events:</h1>
<?php
$sql = "SELECT * FROM events WHERE userid='{$_SESSION['u_id']}';";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_assoc($result)){
echo "<b>Event name: </b>";
echo " ";
echo $row['eventname'];
echo " ";
echo "<b>Event Venue: </b>";
echo " ";
echo $row['venue'];
echo " ";
echo "<b>Event Date: </b>";
echo " ";
echo $row['date'];
echo "
<form method='POST' action='editevent.php'>
<input type='hidden' name='eventname' value='" .$row['eventname']. "'>
<input type='hidden' name='venue' value='" .$row['venue']. "'>
<input type='hidden' name='date' value='" .$row['date']. "'>
<input type='hidden' name='name' value='" .$row['name']. "'>
<button>Edit</button>
</form>
";
}
}else{
echo "No Upcoming Events";
}
?>
</div>
I then have another file in my includes directory which allows changes to the information.
<?php
session_start();
if (isset($_POST['eventsubmit'])) {
$eventname = $_POST['eventname'];
$venue = $_POST['venue'];
$date = $_POST['date'];
$name = $_POST['name'];
$eventname = mysqli_real_escape_string($conn, $_POST['eventname']);
$venue = mysqli_real_escape_string($conn, $_POST['venue']);
$date = mysqli_real_escape_string($conn, $_POST['date']);
$name = mysqli_real_escape_string($conn, $_POST['name']);
$sql = "UPDATE events SET eventname='$eventname' WHERE userid='2' ";
mysqli_query($conn, $sql);
header("Location: ../members.php?event=success");
exit();
} else {
header("Location: ../signup.php");
exit();
}
}

I check your code in second php file you put one extra this } please remove it.

please use mysqli_error instruction to get exactly which error you get
mysqli_query($conn, $sql)or die( mysqli_error($conn));
or you can use to show php error if there any error in php syntax in start of page
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

Updating database using 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

PHP : How to pass get value in url

I want to pass both stock (user input) and id in one url one I try this I get Undefined index: stock is the way I'm passing the input value wrong ?
<?php
session_start();
$sql1 = "SELECT * FROM tbl_customers WHERE customers_id='1'";
$sql = "SELECT * FROM tbl_products";
$get = mysqli_query($conn, $sql1) or die(mysqli_error($conn));
$row = mysqli_fetch_array($get);
$customerName = $row['customer_email'];
echo "Welcome $customerName";
$data= mysqli_query($conn, $sql) or die(mysqli_error($conn));
while ($row = mysqli_fetch_assoc($data)) {
$pid = $row['pid'];
echo "<form action='' method='GET'>
<input type=text name=stock value=1><br>
<a href='stock.php?id=" . $pid . "?stock=" . $_GET['stock'] . "'> Add</a>
</form>";
}
?>
thank you everyone for your help this is what I did to fix the error my get value is always empty If I don't press enter
echo "<form action='' method='GET'>
<input type=text name=stock value=1><br>
</form>";
$_GET['stock'] = 1;
if (isset($_GET["stock"])) {
$x = $_GET['stock'];
echo "<a href='stock.php?id=" . $pid . "&stock=" . $_GET['stock'] . "'> Add</a>";
}
Just change ? with & before stock.
echo "<form action='' method='GET'><input type=text name=stock value=1><br>
<a href='stock.php?id=" . $pid . "&stock=" . $_GET['stock'] . "'> Add</a> </form>";
<a href="/php/event-detail.php?event_id=$event_id">
this how you use to pass values to another page. you can refer this http://w3schools.invisionzone.com/index.php?showtopic=48611

INSERT INTO statement doesn't post data to table [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I am trying to post data to a table in my database, but there is no error messages as to why the data is not posted. I have inserted data into the table in phpmyadmin and this data is printed with the result while loop, but data will not post to the table.
<!-- form to take input-->
<form name='form1' method='post'>
Name:
<input type='text' name='Name' id='name' /> <br />
Comment:
<input type='text' name='Comment' id='comment' /> <br />
<input type="submit" name='submit' value="Submit" id='submit'>
</form>
<!-- start php-->
<?php
if(isset($_POST['submit']))
{
$name = $_POST['Name'];
$comment = $_POST['Comment'];
}
$con = mysqli_connect("localhost", "kodie", "hill1124", "comments");
if(mysqli_connect_errno())
{
echo "Failed to connect to MySql: ". mysqli_connect_error();
}
mysqli_query($con, "INSERT INTO commenttable VALUES ('$name','$comment',NOW()");
$query = "SELECT * FROM commenttable";
$result = mysqli_query($con, $query);
$hash = $result;
echo "<table>";
if($hash = NULL)
{
echo "null";
}
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" . $row['Name'] . "</td><td>" . $row['comment'] . "</td><td>" . $row['timestamp'] . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>";
mysqli_close($con);
?>
I am unsure why it won't post, I don't think it is permissions but I am new to using mysql and don't understand why the statement compiles without errors but doesn't actually put the data on the table.
Any help is appreciated.
In order to INSERT data in your database you need to adjust the insert query.
What you have now:
mysqli_query($con, "INSERT INTO commenttable VALUES ('$name','$comment',NOW()");
Should be
mysqli_query($con, "INSERT INTO commenttable VALUES ('$name', '$comment', NOW())");
You should also consider using mysqli_real_escape_string to prevent SQL-injection
So:
$name = $_POST['Name'];
$comment = $_POST['Comment'];
Becomes:
$name = mysqli_real_escape_string($con, $_POST['Name']);
$comment = mysqli_real_escape_string($con, $_POST['Comment']);
You can also take a look at the following:
http://php.net/manual/en/mysqli.real-escape-string.php;
http://nl3.php.net/manual/en/function.trim.php (removes left over spaces);
http://nl3.php.net/manual/en/function.strip-tags.php (Optional removes html tags from string)
UPDATE
<!-- form to take input-->
<form action="" name="form1" method="post">
Name:
<input type="text" name="Name" id="name"> <br>
Comment:
<input type="text" name="Comment" id="comment"> <br>
<input type="submit" name='submit' value="Submit" id="submit">
</form>
<!-- start php-->
<?php
if($_POST) {
$con = mysqli_connect("localhost", "kodie", "hill1124", "comments");
$name = mysqli_real_escape_string($con, trim($_POST['Name']));
$comment = mysqli_real_escape_string($con, trim($_POST['Comment']));
if (mysqli_connect_errno()) {
echo "Failed to connect to MySql: " . mysqli_connect_error();
}
if (!empty($name) && !empty($comment)) {
$query = mysqli_query($con, "INSERT INTO commenttable VALUES ('$name','$comment',NOW())");
// Check if the query succeeded
if (mysqli_affected_rows($con)) {
$query = "SELECT * FROM commenttable";
$result = mysqli_query($con, $query);
$hash = $result;
echo "<table>";
}
} else {
echo 'Something went wrong: '. mysqli_error($con); // Echo the error (You could replace echo with die())
}
}
if ($hash = NULL) {
echo "null";
}
while ($row = mysqli_fetch_array($result)) {
echo "<tr><td>" . $row['Name'] . "</td><td>" . $row['comment'] . "</td><td>" . $row['timestamp'] . "</td></tr>"; //$row['index'] the index here is a field name
}
echo "</table>";
mysqli_close($con); // this is not necessary
}
?>
You are missing a closing ) at the end of your insert statement:
mysqli_query
($con,
"INSERT INTO commenttable VALUES ('$name','$comment',NOW())");
// This one ^
See the line mysqli_query($con, "INSERT INTO commenttable VALUES ('$name','$comment',NOW()");
You havnt Closed the mysqli_query().
It must be mysqli_query($con, "INSERT INTO commenttable VALUES ('$name','$comment',NOW()"));
Make sure User "kodie" have privileges to do INSERT
Missing parenthesis in
mysqli_query($con, "INSERT INTO commenttable VALUES ('$name','$comment',NOW()");
should be
mysqli_query($con, "INSERT INTO commenttable VALUES ('$name','$comment',NOW()")); // missing )

Categories