This question already has answers here:
PHP form not uploading file
(2 answers)
Closed 7 years ago.
Update: I have uploaded images using PHP BLOB, but they are not showing up in mysql table. Images are being moved to the destination folder but are not showing up in table. and when I fetch the images this code nothing shows up
Code for uploading images
<?php
if (isset($_POST['add_p'])) {
#$pn = $_POST['pname'];
#$pp = $_POST['pprice'];
#$pc = $_POST['pcategory'];
#$date = date('d-m-y H:i:s');
$img = $_FILES['img']['name'];
$tmp_img = $_FILES['img']['tmp_name'];
move_uploaded_file($tmp_img, "uploads/$img");
$insert = "INSERT INTO products (`p_name`, `p_price`, `img`, `p_category`, `date_added`) VALUES ('$pn', '$pp', '$img', '$pc', '$date')";
mysqli_query($con, $insert);
}
?>
<form action="add-product.php" method="POST" class="form">
Name: <input class="inpt" type="text" name="pname">
Price: <input class="inpt" type="text" name="pprice">
Upload Image: <input class="inpt" type="file" name="img">
Select Category
<select class="inpt" name="pcategory">
<option>Men</option>
<option>Women</option>
<option>Kids</option>
</select>
<input type="submit" name="add_p" value="Add Product">
</form>
Code for fetching images
<?php
$get = "SELECT * FROM products ORDER BY p_id DESC LIMIT 0,4";
$query = mysqli_query($con, $get);
while ($row = mysqli_fetch_array($query)) {
echo $id = $row['p_id'];
echo $n = $row['p_name'];
echo $p = $row['p_price'];
echo $c = $row['p_category'];
echo $i = $row['img'];
}
?>
Add enctype='multipart/form-data' to your form to support file uploads:
<form action="add-product.php" method="POST" class="form" enctype="multipart/form-data">
See this answer for more details on encoding types for HTML forms.
Related
I am currently creating a survey where the answers are entered into a database.
I have 2 main tables:
questions, with 2 columns: questionID and questionBody
answers, with 3 columns: answerID, questionID (I want this to be tied to the column in table questions) and answerBody.
On the HTML page I am planning to create there will be multiple questions with multiple text boxes to fill in correlating to each quesiton. Is it possible that when the person submits the form, the answers are inserted into table answers with the questionID being based on what field was filled out?
So for example, If I have questionBody as "What is this Question asking?" and the questionID as 1 in table questions, when I submit the form I want table answers to also have questionID 1 in there.
At the moment this is my code:
//Check if error variables have any values assigned
if (empty($answerError))
{
//Prepare database insert
$sql = "INSERT INTO answers (questionID, answerBody) VALUES (?,?)";
//Check if the statement has the connect and sql variables
if ($statement = mysqli_prepare($connect, $sql))
{
//Add variables to the statement
mysqli_stmt_bind_param($statement, "ss", $paramQuestion, $paramAnswer);
//Set the parameter to the answer
$paramQuestion = getQuestionName($connect);
$paramAnswer = $answer;
//Execute statement with entered variable
if (mysqli_stmt_execute($statement))
{
//Redirect user to success page
header("location: thankyou.php");
}
else
{
echo "Something went wrong. Please try again later.";
}
//Close statement
mysqli_stmt_close($statement);
}
}
and for the function getQuestionName():
function getQuestionName($connect)
{
$query = "SELECT * FROM questions";
$result = mysqli_query($connect, $query);
if ($result)
{
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$questionID = $row['questionID'];
return $questionID;
}
}
}
The code I am using to output the form into a HTML page is:
function getQuestions($connect)
{
$query = "SELECT * FROM questions";
$result = mysqli_query($connect, $query);
if ($result)
{
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$body = $row['questionBody'];
echo '<div class="entry">
<div class="questionTitle"><h3>' . $body . '</h3>
<form action="survey.php" method="POST">
<input type="text" name="answer" size="50" />
<input type="submit" value="Submit" name="submit" />
</form>
</div>
</div>';
}
}
Any help on this would be greatly appreciated :)
Yes it's completely possible. Just put the question ID as a hidden field in the form, and it will be submitted along with the answer data when the form is submitted. Then you can retrieve it from the $_POST data just like the answer, and use it in your SQL query.
For example:
HTML form:
<form action="survey.php" method="POST">
<input type="hidden" name="questionID" value="<?php echo $row["questionID"]; ?>" />
<input type="text" name="answer" size="50" />
<input type="submit" value="Submit" name="submit" />
</form>
survey.php:
$paramQuestion = $_POST["questionID"];
From your question, I will suggest you make use of input with a hidden attribute.
something like this
<input type='text' name='question-id' value="<?php echo $questionId ;?>" hidden>
The user doesn't see the input it get filled from whatever you are providing into it.
Editing your code, you should do something like this.
function getQuestions($connect)
{
$query = "SELECT * FROM questions";
$result = mysqli_query($connect, $query);
if ($result)
{
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$body = $row['questionBody'];
$questionId = $row['questionId'];
echo '<div class="entry">
<div class="questionTitle"><h3>' . $body . '</h3>
<form action="survey.php" method="POST">
<input type="text" name="answer" size="50" />
<input type="number"name="question-id" value="'.$questionId.'" hidden>
<input type="submit" value="Submit" name="submit" />
</form>
</div>
</div>';
}
}
<?php
include('../connect.php');
$id=$_GET['id'];
$result = mysql_query("SELECT * FROM discharge WHERE id='$id'");
while($row = mysql_fetch_array($result))
{
echo '<img src=../'.$row['ppic'].' style="float:left; margin-right:10px;">';
echo '<img src=../'.$row['ppic1'].' style="float:left; margin-right:10px;">';
}
?>
<form action="editpicexec.php" method="post" enctype="multipart/form-data">
<br>
<input type="hidden" name="roomid" value="<?php echo $_GET['id']; ?>">
Select Image
<br>
<input type="file" name="image[]" multiple="multiple" /><br>
<input type="file" name="image1"><br>
<input type="submit" value="Upload">
</form>
discharge is my table database, I want to add picture multiple at in one input.
in this code I am opening a file one at a time, but I want to add multiple picture and then save in the field on the database
<?php
include('../connect.php');
if (!isset($_FILES['image']['tmp_name'])) {
echo "";
}else
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
$image_size= getimagesize($_FILES['image']['tmp_name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"../images/" . $_FILES["image"]["name"]);
$location="images/" . $_FILES["image"]["name"];
$roomid=$_POST['roomid'];
if(!$update=mysql_query("UPDATE discharge SET ppic = '$location' WHERE id='$roomid'"))
if (!isset($_FILES['image1']['tmp_name'])) {
echo "";
}else
$file=$_FILES['image1']['tmp_name'];
$image1= addslashes(file_get_contents($_FILES['image1']['tmp_name']));
$image1_name= addslashes($_FILES['image1']['name']);
$image1_size= getimagesize($_FILES['image1']['tmp_name']);
move_uploaded_file($_FILES["image1"]["tmp_name"],"../images/" . $_FILES["image1"]["name"]);
$location="images/" . $_FILES["image1"]["name"];
$roomid=$_POST['roomid'];
if(!$update=mysql_query("UPDATE discharge SET ppic1 = '$location' WHERE id='$roomid'"))
?>
Then this is my process I dont know how can I upload on database in single input with many pictures . ppic and ppic1 is the name of my field on my database.
if I understood your question right. You might want to use foreach to go through all file in image input like this:
foreach ($_FILES['image'] as $one_file){
$file=$one_file['tmp_name'];
// rest of code
// in the case you want to save all path in same field, change the line bellow like this
// if(!$update=mysql_query("UPDATE discharge SET ppic = concat(ppic, '$location' ) WHERE id='$roomid'"))
}
?>
Instead of concat(ppic, '$location' ) you can use CONCAT_WS(',', ppic, '$location') to separate it by comma.
By way of practicing I am building my own blog. Just to learn about PHP, MySQL and there structure. All goes well, but am running into an UPDATE problem. Let's say I have created a post with title, content and an image. Now, when I go to the page to edit my post I change my title ( not touching the content or image ). After running the update query my image that I uploaded before is gone. If I edit the post and upload a new image all is fine. I hope this makes it clear ( not so good at the jargon.. ) So, when editing, if i do not upload a new image the current image dissapears when updating the post. Here is the code:
if(isset($_FILES['post_image'])){
$errors= array();
$file_name = $_FILES['post_image']['name'];
$file_size =$_FILES['post_image']['size'];
$file_tmp =$_FILES['post_image']['tmp_name'];
$file_type=$_FILES['post_image']['type'];
$file_ext=strtolower(end(explode('.',$_FILES['post_image']['name'])));
$expensions= array("jpeg","jpg","png");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152){
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true){
move_uploaded_file($file_tmp,"post_images/".$file_name);
echo "Success";
}else{
print_r($errors);
}
}
if(isset($_POST['EditPost'])) {
$post_id=$_GET['id'];
$post_title = $_POST['post_title'];
$post_content = $_POST['post_content'];
$post_cat_id = $_POST['post_cat_id'];
$post_tags = $_POST['post_tags'];
$post_template = $_POST['post_template'];
$post_image = $_FILES['post_image']['name'];
$sql = "UPDATE posts SET post_template=?, post_title=?, post_content=?, post_tags=?, post_image=?, post_cat_id=? WHERE post_id=?";
$query = $db->prepare($sql);
$query->execute(array($post_template,$post_title,$post_content,$post_tags,$post_image,$post_cat_id,$post_id));
$succes_update = '<div class="alert alert-success" role="alert">Uw post is ge-update!</div>';;
}
$id=$_GET['id'];
$result = $db->prepare("SELECT posts.post_id, posts.post_template, posts.post_title, posts.post_content, posts.post_tags, posts.post_image, posts.post_cat_id, categories.cat_id, categories.cat_title FROM posts INNER JOIN categories ON posts.post_cat_id=categories.cat_id WHERE post_id= :userid ");
$result->bindParam(':userid', $id);
$result->execute();
$row = $result->fetch(PDO::FETCH_ASSOC);
?>
<div class="col-md-8">
<h2>Edit this Post</h2>
<?php
if(isset($succes_update)){
echo $succes_update;
}?>
<form action="" method="POST" enctype="multipart/form-data">
Post Title<br>
<input type="text" class="form-control" name="post_title" value="<?php echo $row['post_title']; ?>"><br>
Post Content<br>
<textarea style="width:100%; height:200px" class="form-control" n name="post_content"><?php echo $row['post_content']; ?></textarea><br>
Post Image<br>
<?php if(!empty($row['post_image'])) {?><img width="400px" src="post_images/<?php echo $row['post_image']; ?>"/><?php } else { echo " <em>There is no image set here</em>"; } ?><br><br>
<input type="file" name="post_image" /><br><br>
Post Template<br>
<input type="text" class="form-control" name="post_template" value="<?php echo $row['post_template']; ?>"><br>
<br>
Post Tags - (comma seperated)<br>
<input type="text" class="form-control" name="post_tags" value="<?php echo $row['post_tags']; ?>"><br>
Post Category<br>
<select name="post_cat_id">
<option selected><?php echo $row['cat_id']; ?> = <?php echo $row['cat_title']; ?></option>
<?php
$result = $db->prepare("SELECT DISTINCT cat_id, cat_title FROM categories WHERE parent_id > 0");
$result->execute();
for($i=0; $row = $result->fetch(); $i++){
echo "<option>". $row['cat_id'] . " = " . $row['cat_title'] . "</option>";
}
?>
</select><br><br>
<input type="submit" class="btn btn-primary" value="Edit this Post" name="EditPost" />
</form>
The reason for this is that in the EditPost section you simply take whatever is in the post_image file upload control. If you did not select a new file for the post, then this control will not have any content, thus it will override the existing post_image value with an empty string.
If a post must have an image, then check in the EditPost section if post_image has content at all and if not, then leave it out from the update statement.
If you do not require a post to have an image, then have a separate checkbox that says "delete exsisting image"? If the user checks it, then set the post_image to an empty string and remove the image file as well. If this checkbox is unchecked, but the post_image control was left empty, then do not set post_image field in the db to empty string.
Thanks to #shadow I figured it out. I changed the condition for the update query. This is my solution:
if($post_image!= null AND isset($_FILES['post_image'])){
$sql = "UPDATE posts SET post_template=?, post_title=?, post_content=?, post_tags=?, post_image=?, post_cat_id=?, post_video_url=? WHERE post_id=?";
$query = $db->prepare($sql);
$query->execute(array($post_template,$post_title,$post_content,$post_tags,$post_image,$post_cat_id,$post_video_url,$post_id));
}
else {
$sql = "UPDATE posts SET post_template=?, post_title=?, post_content=?, post_tags=?, post_cat_id=?, post_video_url=? WHERE post_id=?";
$query = $db->prepare($sql);
$query->execute(array($post_template,$post_title,$post_content,$post_tags,$post_cat_id,$post_video_url,$post_id));
}
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.
This question already has answers here:
display only 3 foreach result per row
(2 answers)
Closed 1 year ago.
I am currently working on a loop to display items from a mysql table. Is there a simple way to display 3 items per row. So far I managed to display all the items in a single row inside an html table . I would appreciate any help;
code (without html table tags) below:
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<?php
$database_name = "vog";
$conn = mysql_connect("localhost","root","toor");
mysql_select_db($database_name);
$sql = "select * from client1";
$result = mysql_query($sql) or die(mysql_error());
$num = mysql_num_rows($result); //Ελεγχος αν υπάρχουν εγγραφές!
?>
<?php
if($num){
while ($row = mysql_fetch_array($result))
{
echo $img_id = $row['img_id'];
?>
<form name="add2cart" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php echo $row['img_name'];?>
<?php echo "<img src=".$row['img_path'].">";?>
<select name="color">
<option>bnw</option>
<option>sepia</option>
</select>
<input type="hidden" name="img_name" value="<?php echo $row['img_name']; ?>">
<input type="submit" name="add2cart" value="Add to cart"></input>
<br />
</form>
<?php
}
}
else{
echo "Δεν υπάρχουν εγγραφές με τα κριτήρια που επιλέξατε";
}
//add2cart section
if(isset($_POST['add2cart'])){
$img_name = $_POST['img_name'];
$color = $_POST['color'];
$sql_order ="insert into orders(item_id, img_name, color)
values(' ', '$img_name', '$color')";
$result = mysql_query($sql_order);
}
?>
Declare a variable before your loop like: $currentRow = 1 and then inside, and at the end, of your loop add $currentRow++
You can then check if your row is divisible by 3 if($currentRow % 3 == 0) and put a break in.