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.
Related
I'm writing a program to create an online forum and I am relatively new to php.
I have used a while loop to display all topics created for discussion in a table. This reads my sql database and echoes out just fine:
if ( mysqli_num_rows( $r ) >0 ) {
while ( $row = mysqli_fetch_array( $r, MYSQLI_ASSOC ) )
{
echo "<tr><th><p align = 'left'>"."Posted By ".$row['first_name']." " .$row['last_name']. " on ". $row['post_date']."<br/>";
echo "<p style = 'color:#2208A1', align='left'>"."Subject:". $row['subject']."<br/><br/>";
echo "Message: ". $row['message']."<br/>";
echo "ID Number = ". $row['post_id']."<br/>";
echo "<p style='color:red;' align = 'right'>"."<a href='http://localhost/FirstCswkAttempts/2017%20Web%20Scenario_A2/cwk_addreply.php?post_id =" .$row['post_id']." '>Reply to Post."."</a></p>";
"</tr></th>";
}
}
However,you can see that in the last line of code I try to concatenate the post_id number to the URL in the hope that I can use this information in another php file:
The code below shows my attempt to do just this. I use the GET method to capture post_id and insert it into another table in my database. If I use var_dump($_GET); I get an empty array. Where am I going wrong??
$q = "INSERT INTO responses(reply_owner, reply_text,reply_create_time,post_id)
VALUES (' ".$_POST['email']." ', ' ".$_POST["message"]."', now(),'".$_GET['post_id']."')";
$r = mysqli_query ( $dbc, $q
) ;
In response to comments, please find the form used to add posts to the topic:
<h1>Reply to Thread</h1>
<!--Display form-->
<form action="cwk_reply_action.php" method="post" accept-charset="utf-8">
<p><strong>Your email:<br><input name="email" type="text" size="55px" maxlength="100"></p>
<p>Message:<br><textarea name="message" rows="5" cols="50px"></textarea></strong></p>
<input type = "hidden" name = "post_id" value = "$_GET['post_id'] ">
<p><input name="submit" type="submit" value="Submit"></p></form>
This is a pretty common type of thing for a PHP application to do. The general pattern is:
Pull a list of items from a database and display them with links to interact with specific items.
When a link is clicked, display a form with the information of the selected item.
When the form is submitted, save the user input to the selected item.
The minimum you need to implement this pattern is the following:
Step 1 (display the items):
<?php
// using mysqli for example here, but the same general idea for pdo or any other
$result = mysqli_query('SELECT id, some_text, other_columns FROM your_table WHERE criteria');
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$id = htmlspecialchars($row['id']);
$text = htmlspecialchars($row['some_text']);
echo '' . $text . '<br>';
}
?>
Clicking a link (<a>) sends an HTTP GET request to the URL in its href parameter.
Step 2 (display the form):
When PHP handles the request, anything you have included in the query string of the URL (the ?id=x portion) will be availabe in the $_GET array.
There are two ways you can handle this piece of data so that it can be passed on to step 3. One way is to include it in the URL in the action parameter of your form:
<form action="url/to/submission_handler.php?id=<?php echo $_GET['id']; ?>" method="post">
Another way is to include a hidden form element that contains the ID.
<form action="url/to/submission_handler.php" method="post">
<input type="hidden" name="id" value="<?php echo $_GET['id']; ?>">
Step 3 (handle the form submission):
In this step, if you have passed the ID via the action parameter, it will be available in the $_GET array ($_GET['id']), and if you have passed it via an input on the form, it will be available in the $_POST array. ($_POST['id']).
Either way, you should be able to access it for use in your query.
<?php
$id = $_GET['id']; // or $_POST['id'], depending on which way you handled it on your form
// Using a prepared statement here for example rather than concatenating values into the
// SQL string, in order to reduce risk of SQL injection
// (Assuming $mysli is a connected mysqli object)
$stmt = $mysqli->prepare('UPDATE your_table SET ... WHERE id=?');
$stmt->bind_param("i", $id);
$stmt->execute();
?>
Either method of passing the id from your form to the script that handles its submission is perfectly valid, functional and commonly used. As far as I know, which way you should do it is really just determined by your own personal preference.
But you should note that passing parameters in the query string of the action paramater will only work for forms with method="post". If you ever need to use method="get" instead, only the values in the form fields will be available in $_GET; parameters in the query string will be ignored.
(For forms that will make changes on your server, (INSERT, UPDATE, or DELETE queries, writing to files, etc.) you should always be using method="post" anyway, but just FYI.)
If you want to print a variable you need it
<input type = "hidden" name = "post_id" value = "<?php echo $_GET['post_id']; ?> ">
And you will see the value of post_id
I believe you should be more specific however your code seems pretty rusty you need someone to tell you how its done what its your current uri on this script?
its it anything like that:http://localhost/forum.php?post_id=foobar
Are you send a POST or a GET request? what its your enctype?
if it is you can use the $_GET super global just fine just be careful inserting it on your querys, SQL injection still a big problem on this day.
<?php
if ( mysqli_num_rows( $response ) >0 ) {
while ( $row = mysqli_fetch_array( $response, MYSQLI_ASSOC ) )
{
echo "<tr>
<th>
<p align = 'left'> Posted By {$row['first_name']} {$row['last_name']} on {$row['post_date']} <br/>
<p style = 'color:#2208A1', align='left'>
Subject: {$row['subject']} <br/><br/> Message: {$row['message']} <br/>
ID Number = {$row['post_id'] }<br/>
<p style='color:red;' align = 'right'>
<a href='http://localhost/FirstCswkAttempts/2017%20Web%20Scenario_A2/cwk_addreply.php?post_id ={$row['post_id']}'>Reply to Post.</a>
</p>
</tr>
</th>";
}
//This is not recomenended anymore
//But since you are not using PDO and prepared statments its not that bad
$email = mysql_real_escape_string($_POST['email']);
$message = mysql_real_escape_string($_POST["message"]);
$postId = mysql_real_escape_string($_GET['post_id']);
//never name your variables less then 4 chars $q = $query, $r = $response , $dbc = $databaseConnection
$query = "INSERT INTO responses( reply_owner, reply_text, reply_create_time, post_id ) VALUES ('$email', '$message', now(),'$postId')";
$response = mysqli_query ( $databaseConnection, $query );
My users have profile photos with captions. Each photo is stored under an auto incremented ID in a database table, so in order to display all relevant photos for an individual user I while look content relevant to their user number.
Because of the differing photo quantities between users, I am unsure of how to process the submitted form.
Is it possible to while loop content back into the database in order to update the table?
Code that produces form details:
while($row = mysql_fetch_array($result))
{
echo '<div style="width:180px; height:210px; float:left;"><img src="../assets/uploads/thumbnail_' . $row['photoLINK'] . '" alt="" class="profileImgsStretch"/>';
echo '<input type="text" name="caption' . $row['photoID'] . '" value="' . $row['photoCAPTION'] . '"></div>';
echo '<input type="hidden" name="picture" value="' . $row['photoID'] . '"></div>';
}
First you need to look at the structure of the database. if 1 user has many pictures you need to make a separate database table consisting of the user id and the photo id
your database structure should be like this
myDB
table 1 -Users
table 2 -user_and_picture
-user_id
-picture_id
table 3 -Pictures
You insert the new picture into the pictures table
Then retrieve that picture id
get the user id and the picture id and store it in the new table user_and_picture
When you want to retrieve the pictures that belong to lets say user 1 you run a query on table user_and_pictures
an example would be
SELECT user_id, user_picture_id
FROM user_and_picture
WHERE user_id = 1
The result of this query will give you all the pictures associated with user #1
after that make a query that gets the filenames of those pictures
In your html use:
<input type="text" name="caption[' . $row['photoID'] . ']" value="' . $row['photoCAPTION'] . '">
You may remove the hidden input field.
So that in your PHP file you may use:
$captions = $_GET['caption'];
foreach ($captions as $picture_id => $caption){
/*
VERY IMPORT TIP ABOUT HACKING: For each caption, check if the picture_id belongs to the user BEFORE making the update. Otherwise a hacker can just change the picture id's and add malicious captions for other users!
If the picture belongs to the uploading user, then continue.
*/
echo 'caption for picture_id: '.$picture_id.' = '.$caption.'<br />'
}
This is how form with data works:
your input field have element named name. its the variable name for your input which you receive in you back-end i.e PHP page.
the form variable name could be literal variable or could be an array.
so for example:
login:
<input type="text" name="username" />
<input type="text" name="password" />
to get it in PHP
$user = $_POST["username"];
$pass = $_POST["password"];
OR in array
<input type="text" name="loginData[username]" />
<input type="text" name="loginData[password]" />
to get it in PHP
$userData = $_POST["loginData"]; // $userData = Array(username, password)
OR
$user = $_POST["loginData[username]"];
$pass = $_POST["loginData[password]"];
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.
I am very new to PHP;
ADD.PHP - I have a form that collects the following information 1. name 2. email 3. phone and picture
pictures are stored on a directory folder on my server and then the filename of that photo is stored on my sql table.
VIEW.PHP - all the data in mysql is being displayed in this page including the photo in tabular format including the id of every record. The id being display is a hyperlink in which when clicked you will be directed to a page wherein you can edit the record contents:
below is the code for my EDIT.PHP
<?php
// Connects to your Database
mysql_connect("localhost", "user1", "12345") or die(mysql_error()) ;
mysql_select_db("test") or die(mysql_error()) ;
// Check whether the value for jobnumber is transmitted
if (isset($_GET['id'])) {
// Put the value in a separate variable
$id = $_GET['id'];
// Query the database for the details of the chosen jobnumber
$result = mysql_query("select id, name, email,
phone, picture from employees where id = $id");
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = "Invalid query: " . mysql_error() . "\n";
$message .= "Whole query: " . $query;
die($message);
}
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(),etc.
while ($row = mysql_fetch_array($result)) {
$name = $row['name'];
echo $name. "\n";
echo $row['email'] . "\n";
echo $row['phone'] . "\n";
echo "<img width=500px height=500px src=pics/" . $row['picture'].">" . "\n";
// form tag
echo '<form action="add2.php" method="POST">';
//display name
echo 'Name: <input type="text" name="name" value="';
echo $row['name'];
echo '"><br>';
//display email
echo 'email: <input type="text" name="email" value="';
echo $row['email'];
echo '"><br>';
//display phone
echo 'Phone: <input type="text" name="phone" value="';
echo $row['phone'];
echo '"><br>';
//display photo
echo 'Photo: <input type="text" name="photo" value="';
echo $row['picture'];
echo '"><br>';
echo '<input type="submit" value="Add">';
echo '</form>';
}
} else {
die("No valid data specified!");
}
?>
using this code, the test fields went well but the input box for the photo is blank and when i click the button the photo field in my database will be blank unless i uploaded a new photo?
how can the user change the existing photo? or retain the old photo if not being changed?
Assuming your employees.picture column stores the path to the image.
To upload a new photo, you're going to need to change a couple of things...
Your form needs to use the correct encoding type, ie
<form action="add2.php" method="post" enctype="multipart/form-data">
You also need to provide a "file" input element to accept the new photo, eg
<input type="file" name="photo">
To see if a new photo has been supplied, simply check (after detecting a valid POST request)
if ($_FILES['photo']['error'] == UPLOAD_ERR_OK) {
// file uploaded
}
see this link :http://www.w3schools.com/PHP/php_file_upload.asp
As to changing the existing photo, u should also save the name of the photo name in your db fom within the page add2.php
when any users wants to upload the photo for the second time, then a check should be made in add2.php to find whether a photo was previously uploaded. Then U can take a decision from the user from 2 yes, no buttons. If yes then UPDATE( not insert) the corresponding column in db table.
U can use jquery to take the decision and work accordingly. Any help needed with jquery?
IF it is for the first time that the uploading is gonna take place, then u can bypass the check process.
Clear?
I have two fields
<form action="insert.php" method="post">
Firstname: <input type="text" name="firstname" />
Lastname: <input type="text" name="lastname" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
how to post name and lastname in one variable meaning in one field of database
is it
<?php
$name=$_post['firstname']['lastname'];
?>
Actually you have three fields. Use string concatenation (or implode):
$name = $_POST['firstname'] . ' ' . $_POST['lastname'];
And don't forget to use mysql_real_escape_string (or what #ThiefMaster says) if you store the values in a database. Never trust user input.
Just concatenate the two values e.g.
<?php
$name = $_POST['firstname'] . $_POST['lastname'];
?>
keep an array, and serialize it to store it.
$name['firstname']=$_post['firstname'];
$name['lastname']=$_post['lastname'];
//storage and retrieval methods
$stored_name = serialize($name);
$name = unserialize($stored_name);
This way you don't lose the functionality of having the variables separate in an array, and you can always concatenate them later for display if you need to.
You can give the text inputs the same name with []
Firstname: <input type="text" name="name[]" />
Lastname: <input type="text" name="name[]" />
then you can
$name = $_POST['name'][0].$_POST['name'][1];
but i would prefer
$name=$_post['firstname'] . ' ' . $_post['lastname'];
This One will help You...! I also implemented this and it works...!
Firstname: <input type="text" name="firstName" />
Lastname: <input type="text" name="lastName" />
$fullname = $_post['firstName']. ' ' .$_post['lastName'];
$name = $firstname . " " . $lastname;
Then post $name in whatever field you want.
I had this same problem, i have a form with the name of the person reporting the issue and it takes the first name and the last name from my database of users and adds them together, but then when it came time to post both names to the database it would only post the first name.
my solution was to first of all call the first name and last name from the database of users, then i called just the first name and last name and concat them together to produce reportername.
so this is the first part of the code calling for the user details i require for the form:
// Select the member from the users table
$sql = "SELECT * FROM users WHERE username='$log_username' AND activated='1' LIMIT 1";
$user_query = mysqli_query($db_conx, $sql);
// Now make sure that user exists in the table
$numrows = mysqli_num_rows($user_query);
if($numrows < 1){
echo "That user does not exist or is not yet activated, press back";
// exit();
}
// Fetch the user row from the query above
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$profile_id = $row["id"];
$first_name = $row["First_Name"];
$last_name = $row["Last_Name"];
$userlevel = $row["userlevel"];
}
Next i Concat the first name and last name:
$reporter_sql = "SELECT CONCAT (First_name,' ', Last_name) AS reportername FROM users WHERE username='$log_username' AND activated='1' LIMIT 1";
$reporter_results = mysqli_query($db_conx, $reporter_sql);
while ($row = mysqli_fetch_array($reporter_results, MYSQLI_ASSOC)){
$reportername = $row['reportername'];
}
then you can post it to your database:
$reportername = mysqli_real_escape_string($db_conx, $reportername);
$sql = "INSERT INTO yourform (`reportedby`) Value ('$reportername')";
I have striped my code down so it gives you an idea and I'm sure coders with more experience could tell you a simpler way to do this i just know it worked for me.
A shortcut way to concatenate variables is this:
$name = "$_POST[first_name] $_POST[last_name]"
General comment. A good proportion of the world don't have first and last names.
Better practice is just to ask for "Name", and stick it in one field.
If you must split 'em, then "given name" and "family name" are better labels.