When populating the fields of an update form how can I show the path to the current image like this
so that if the user doesn't want to change the image the same image is used.
This is what the browser displays:
<input type="file" value="uploads/chaps_B.jpg" name="image_edit"></input>
I have a feeling my photopath in not in scope but unsure how to go about fixing it. All variables populate the form and it saves to the db fine just can't figure out the image path.
if(isset($_POST['update_submit']))
{
$get_products = $db->prepare("select `photopath` from `item` where
`item_id` = '$get_item' LIMIT 1");
$get_products->execute();
$path= $get_products->fetchColumn(6);
if($_FILES['image_edit']['tmp_name'] != "")
{
$edit_name = $_POST['item_name'];
$edit_description =$_POST['item_description'];
$form_id = $_POST['edit_form_id'];
$file_dir = "uploads/";
$image = $file_dir. $_FILES['image_edit']['name'];
move_uploaded_file($_FILES['image_edit']['tmp_name'], $image);
$edit_sql =$db->prepare("UPDATE item SET item_name = '$edit_name',
item_description = '$edit_description',
photopath ='$image' WHERE item_id = '$form_id'");
$edit_sql->execute();
header("Location: manage_items.php");
exit();
}
else
{
$edit_name = $_POST['item_name'];
$edit_description =$_POST['item_description'];
$form_id = $_POST['edit_form_id'];
$edit_sql =$db->prepare("UPDATE item SET item_name = '$edit_name',
item_description = '$edit_description'
WHERE item_id = '$form_id'");
$edit_sql->execute();
header("Location: manage_items.php");
exit();
}
UPDATE FORM
<form action="item_edit.php" method="post" enctype="multipart/form-data">
<input type = "text" name="item_name" value="<?php echo $item_name ?> "/>
<textarea name="item_description"><?php echo $item_description ?></textarea>
<p> <img src="<?php echo $image; ?>" width="75" height="75" /></p>
<input type="file" name="image_edit" />
<input name="edit_form_id" type="hidden" value="<?php echo $get_item ?>">
<p><input type="submit" name="update_submit" value="Update"/></p>
<p><input type="submit" name="cancel_edit" value="Cancel"/></p>
</form>
DB STRUCTURE
When retrieving a single row, you do not have to loop through as you asked in the comment in your code.
As for the database, what exactly are you storing what does your table structure look like?
You could easily save the name of the image in a field and retrieve that and not even get the fullpath ( since there could be more images there )
EDIT 1
This is one way to solving the empty string insertion issue yes, however the query will have to be different so you'll have to write one which does insert the image, and one that excludes it
EDIT 2
After you retrieve the image path all you'd have to do now is split the string by using PHP's explode, e.g. $aPath = explode('/', $yourDBfield);, this would give you an array with items split on a /, since the file will always be at the end, simply do this: $image = $aPath[(count($aPath)-1)];, this should give you the image.
EDIT 3
As requested by the OP,
The main query should include the image update, e.g. when the value set is not empty.
$edit_sql =$db->prepare("UPDATE item SET item_name = '$edit_name',
item_description = '$edit_description',
photopath ='$image' WHERE item_id = '$form_id'");
The other query should exclude photopath = '$image' e.g.
$edit_sql =$db->prepare("UPDATE item SET item_name = '$edit_name',
item_description = '$edit_description',
WHERE item_id = '$form_id'");
You could also, as mentioned in the comments, add the default path, e.g. $image (not split) to the value of the field when the page is requested, this way you'd only have to write 1 query, and the image would remain the same if untouched.
Related
This is the code where I get my input names and values from a table called optionale and doing something with these:
<form role="form" autocomplete="off" action="includes/functions/fisa-init.php" method="POST">
<?php
connectDB();
$query = mysqli_query($mysqli, "SELECT * FROM `optionale`") or die(mysqli_error($mysqli));
while($row = mysqli_fetch_array($query))
{
?>
<span><?php echo $row['denumire']; ?></span>
<input type="text" name="nrBucati">
<input type="hidden" value="<?php echo $row['cod']; ?>" name="codProdus">
<?php } ?>
</form>
The optionale table looks like this:
The HTML looks like this:
As you can see in the last picture, I have in HTML, a name for input (taken from optionale table) and the actual input in which I write a value.
fisa-init.php:
$stmt3 = $mysqli->prepare("
UPDATE
`stocuri`
SET
`cantitate` = `cantitate` - ?
WHERE `cod` = ?
");
$stmt3->bind_param("is", $bucata, $cod);
// set parameters and execute
$bucata = mysqli_real_escape_string($mysqli, $_POST['nrBucati']);
$cod = mysqli_real_escape_string($mysqli, $_POST['codProdus']);
if (!$stmt3->execute())
{
echo "Execuția a întâmpinat o eroare: (" . $stmt3->errno . ") " . $stmt3->error;
}
$stmt3->close();
$mysqli->close();
In the code above (fisa-init.php) I am trying to take all the input values from my HTML and update rows in another table called stocuri:
As you can see, only the second row from stocuri table was updated, but I wrote values in all 5 inputs. It got only the last input.
How to modify the while loop in order to take all my inputs value?
If something is not clear, I apologize a hundred times. I will explain all the informations that are needed.
P.S. cod in table optionale is the same with cod in table stocuri. In this way, I know where to update values.
Each <input> MUST have an individual name or a named array.
So give each an aditional number like name1,name2 or use an named array like name[]
Finally this name="codProdus[]" is your solution.
Read more here
HTML input arrays
Have a nice day
hii am amateur in php and making a website in which i am uploading an image,storing it in database(with an autoincrement variable) and displaying it on page in descending order so it may seem as latest at top and latter below it,,i need to add a textbox for comment and username(cuz i haven't made login page as m not gonna host it somewhere)
i knwo how to add it for upload image's section as only 1 image is gonna get uploaded
problem is how to display it, i have used
while ($image = mysqli_fetch_assoc($sql))
{
echo image code....
}
Now i in the div to display image i'll incorporate 2 textboxes and evertime after while loop ill display values from dB accordingly but when i want to edit the textbox after uploading more than 1 image,how to know which textbox is being edited as every textbox would have same textbox name
should i compare the image contents ?as the image iteself is stored in binary format? but that wud be a slow process i guess
plz suggest som idea or method to do so basically its like instagram(but very basic)....
First create images table:
images table
image_id | url
Then creare seperate table for images comments:
images_comments table
comment_id | image_id | user | text | date
Where:
comment_id: integer , Auto Increment
image_id: integer referring to id in images table
user: should be user id referring to separate users table, but because you do not have login system you can store user name here as varchar.
text: varchar
date: datetime
To show images + comments:
$sql = "SELECT * FROM images";
while ($image = mysqli_fetch_assoc($sql))
{
$imageUrl = $image["url"];
$imageID = $image["image_id"];
//Show image:
echo "<img src='$imageUrl ' />";
//Get comments:
$sql2 = "SELECT * FROM images_comments WHERE image_id=$imageID";
while ($comment = mysqli_fetch_assoc($sql2))
{
$text = $comment["text"];
$userName = $comment["user"];
$date = $comment["date"];
//show username and comment date
echo $userName . " " .$date . "<br>";
//Show comment text:
echo $text;
}
}
To add a comment to images
if you want a comment form under each image then in the While loop we used before add the following code:
while ($image = mysqli_fetch_assoc($sql))
{
.......... previous code goes here .........
//in the form we store imageID in hidden input field
//so that we can know to which image the form belongs
echo "<form method='post' action='page.php'>
<input type='text' name='username'/>
<textarea name='commentText'></textarea>
<input type='hidden' name='imageID' value='$imageID'/>
<input type='submit' name='submitComment' value='Submit'>
</form>";
}
then in page.php
if(isset($_POST["submitComment"]))
{
$username = $_POST["username"];
$text = $_POST["commentText"];
$imageID = $_POST["imageID"];
$date = date("Y-m-d H:i:s");
$sql = "INSERT INTO images_comments (image_id,user,text,date) VALUES
($imageID,$username,$text,$date)";
mysqli_query($con,$sql);
}
I currently have a form that creates an item in a database then in the next step it allows the user to upload multiple images for that listing both sections work on their own but i need to be able to insert the $id from the first page into the query for the image upload to identify which listing it corresponds to
Here is the page to allow the user to upload multiple images
<input name="name" type="text" id="name" size="40" placeholder="Homestay's Name"/>
<input name="type" type="text" id="type" size="40" placeholder="Homestay's Type"/>
<input name="category" type="text" id="category" size="40" placeholder="Homestay's Category"/>
<input class='file' multiple="multiple" type="file" class="form-control" name="userfile[]" placeholder="Please choose your image">
here is the function
$path = pathinfo($_SERVER['PHP_SELF']);
for ($i = 0; $i < count ($_FILES['userfile']['name']); $i++)
{
$tmp_file = $_FILES['userfile']['tmp_name'][$i];
$filetype = $_FILES['userfile']['type'][$i];
$filesize = $_FILES['userfile']['size'][$i];
$filename = $_FILES['userfile']['name'][$i];
$destination = $path['dirname'] . '../data/' . $filename;
if (move_uploaded_file($tmp_file, $_SERVER['DOCUMENT_ROOT'] . $destination))
{
$name = $_POST['name'];
$type = $_POST['type'];
$category = $_POST['category'];
$sql="INSERT INTO homestay (name, type,category,)
VALUES
('$name', '$type','$category')";
$result = mysql_query ("insert into img_homestay (id, location,filetype, filename, filesize)
values ('".$id."', '" . $destination . "','" . $filetype ."','" . $filename . "'," . $filesize . ") ");
}
}
If I understood your question:
In the previous page you have the id from the list.
At the second page, put it into a hidden field like:
<input type="hidde" name="theId" value="<?php echo $_POST["idFromPrevPage"]; ?>" />
And then you can access it from $_POST["theId"]
EDIT:
Based on your comment, I think, you want to do something like this:
$sql = "INSERT INTO homestay (name, type,category) VALUES ('".mysql_real_escape_string($name) ."', "
. "'".mysql_real_escape_string($type)."','".mysql_real_escape_string($category)."')";
$res = mysql_query($sql);
$id = mysql_insert_id(); //This where you can get the last insert id.
NOTES
Anyway, you have several problems in your original code:
In your first insert query have an unwanted , character at the field list.
Do not use mysql_* functions, they are deprecated. Use mysqli_* functions or PDO!
Escape your data to avoid sql vulnerables or use prepared statements.
I think your best bet would be :
create the form to insert the db item
get the ID of the inserted item, and add it as a hidden element on the second step
once the second form gets back, you can easily see the ID you need.
Do note that this approach will send DB id's client side, but is the simplest option.
A second approach is to utilize session variables - simply store the item ID to the user session, and retrieve it on the second step. This is safer, but not a good approach if multiple forms can be submitted at the same time by the same account/person.
$_SESSION['the_id'] = $result->id;
and then
$id = $_SESSION['the_id'];
The best approach (in my opinion always) is to use a non-sensical token to the client side, and map it to the proper ID using some logic. A simple example is to generate a complex hash for the ID, and send that as a hidden field to the user when sending the form for step 2. Store the ID and hash in a database table.
When the user POSTs that back, use the hash to map it back to a normal ID, and destroy the entry.
I have the following code that I created to update the database with the data coming from a a php form. $_POST['variables'] are different arrays.
the issue I am having is when I echo $updater the field status and the field display values are not in the correct order. for example if I check the checkbox 3. it will return the value enabled on the first line of the results. any suggestions would help thank you
//update data
$priority = $_POST['priority']; // this will be an array
$enable = $_POST['enable'];
$height = $_POST['height'];
$position = $_POST['position'];
$widgetid = $_POST['widgetid'];
$display = $_POST['display'];
$i = -1;
foreach($priority as $priori)
{
++$i;
$row_enable = $enable[$i];
$row_height = $height[$i];
$row_prio = $priority[$i];
$positio = $position[$i];
$disp = $display[$i];
$widgeti = $widgetid[$i];
if (isset($enable[$i]))
$enables ="y";
else
$enables ="n";
if (isset($display[$i]))
$displ = "y";
else
$displ = "n";
//DO THIS FOR THE REST AND THEN YOUR UPDATE QUERY
$updater = "UPDATE hpoptions SET position='$positio', height='$row_height', status='$enables', display='$displ', priority='$row_prio' WHERE userid='$ud' and widgetid='$widgeti'";
echo $updater."<br>";
} // ends here
There is no guarantee you will get your arrays in the desired order, unless you force it in the HTML. You probably have something like this:
<input type="text" name="position[]">
<input type="text" name="height[]"> ...
<input type="hidden" name="widgetid[]" value="w1">
...
<input type="text" name="position[]">
<input type="text" name="height[]"> ...
<input type="hidden" name="widgetid[]" value="w2">
...
You need to add an extra dimension to the arrays encoded on the field name. You need an unique id for each field group, and I believe your widgetid is exactly that, right? So you can do:
<input type="text" name="data[w1][position]">
<input type="text" name="data[w1][height]"> ...
...
<input type="text" name="data[w2][position]">
<input type="text" name="data[w2][height]"> ...
...
Notice you don't even need a field called widgetid anymore, since the ids will be encoded on every field name. In PHP, you do this to loop through the results:
foreach($_POST['data'] as $widgetid => $data) {
// Make sure to check if the values won't make your SQL query vulnerable to injection!
// http://stackoverflow.com/questions/332365/xkcd-sql-injection-please-explain
$widgetid = mysql_real_escape_string($widgetid);
$position = is_numeric($data['position']) ? $data['position'] : 0;
// ...
// Build your update query here
}
I have a PHP update page in which I am showing a text field containing a value from the database. It is like this, and it is working,
<input type="text" name="title" id="title" class="text_box" value="<?php echo $row['title']?>"/>
Now I need to put this updated value back in the database! I have used the code like this, but it's not updating:
$title=$_POST['title'];
$v_id = $_GET['v_id'];
$sql = mysql_query("update vehicles set title = '$title' where v_id = '$v_id'");
In detail... an input field is there. It's showing a value contained in $title (retrieved from the database) and that value is to be edited and updated.
From my side my code is working perfectly without showing any error, but the value that I give $title is giving the same one without any change.
Is there any other way to show a value in an input field without putting in a "value" tag?
Two things wants to happen in a single input field!
You'll need to post your form HTML as well.
Unless your form looks like the following, that code won't work
<form method='post' action='page.php?v_id=1'>
<input type="text" name="title" id="title" class="text_box" value="<?php echo $row['title']?>"/>
</form>
This is because you're using $_GET to get the id field and $_POST to get the value field
EDIT
Your edit has muddied the water a bit more. I'm going to assume all you want to do is show a title and let the user update the title
<?php
if ($_POST) {
$title = mysql_escape_string($_POST['title']);
$id = intval($_GET['v_id']);
$sql = "update vehicles set title = '$title' where v_id = '$id'";
mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
}
if (isset($_GET['v_id'])) {
$id = intval($_GET['v_id']);
$sql = 'SELECT title FROM vehicles WHERE v_id = ' . $id;
$rs = mysql_query($sql) or trigger_error(mysql_error()." ".$sql);
$row = mysql_fetch_assoc($rs);
$title = htmlspecialchars($row['title']);
}
?>
<form method='post' action='?v_id=<?php echo $id?>'>
<input type="text" name="title" id="title" class="text_box" value="<?php echo $title ?>"/>
<input type='submit' value='update'>
</form>
This should work for you. I haven't error tested obviously, but the idea is sound. You should also add any other input screening you feel necessary.
You are using both $_POST and $_GET.
Depending on the method element value of <form>, you need either $_POST or $_GET.
If this is not helping, please show more code so it is possible to determine which one you need.
Also, you can try to update the database without reading the form, to check if the updating itself is working correctly.
is there any other way to showing a value in a input field without putting a "value" tag?
Nope.
That's exactly what value attribute for.
What's wrong with it?
only thing to mention, it should be not <?php echo $row['title']?> but
<?php echo htmlspecialchars($row['title'])?>