I'am having a button to upload a image and Every time I upload an Image the images doesn't saves on the database and there is no error given,
Here is my Code:
<td>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit" name="files" class="btn btn-primary btn-xs">
Submit
</button>
<?php
if(isset($_POST['files']))
{
$userid = $row['stall_id'];
$a = $_FILES['file']['name'];
$ab = $_FILES['file']['tmp_name'];
$location = "".$a;
move_uploaded_file($ab, "../pictures/".$location);
$sql2 = $conn->prepare("UPDATE stall SET file = ? WHERE stall_id = ?");
$sql2->execute(array($location,$userid));
if($sql){
echo '
<script>
window.location = "stalls.php"
</script>';
}
}
?>
</td>
I Figured it out my self,
<td>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" required>
<input type="hidden" name="stall_id" value="<?php echo $value['stall_id']?>">
<button type="submit" name="files" class="btn btn-primary btn-xs">
Submit
</button>
<?php
if(isset($_POST['files']))
{
$userid = $_POST['stall_id'];
$a = $_FILES['file']['name'];
$ab = $_FILES['file']['tmp_name'];
$location = "".$a;
move_uploaded_file($ab, "../pictures/".$location);
$sql2 = $conn->prepare("UPDATE stall SET file = ? WHERE stall_id = ?");
$sql2->execute(array($location,$userid));
if($sql2){
echo '
<script>
window.location = "stalls.php"
</script>';
}
}
?>
</td>
Please Bind Parameter After Prepare statement. check docs- http://php.net/manual/en/mysqli.prepare.php
in if condition put $update(return value of execution) instead of sql
close </form> tag.
check all variables having data. check with var_dump(), print_r() or echo() methods.
<td>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="file" required>
<button type="submit" name="files" class="btn btn-primary btn-xs">
Submit
</button>
</form>
</td>
<?php
if(isset($_POST['files']))
{
$userid = $row['stall_id'];
$a = $_FILES['file']['name'];
$ab = $_FILES['file']['tmp_name'];
$location = "".$a;
move_uploaded_file($ab, "../pictures/".$location);
if( $sql2 = $conn->prepare("UPDATE stall SET file = ? WHERE stall_id = ?"))
{
$sql2->bindParam(1, $location, PDO::PARAM_STR);
$sql2->bindParam(2, $userid, PDO::PARAM_INT);
$update=$sql2->execute();
if($update){
echo '
<script>
window.location = "stalls.php"
</script>';
}
}else{
echo 'sql prepare failed';
}
}
?>
change from
$sql2 = $conn->prepare("UPDATE stall SET file = ? WHERE stall_id = ?");
$sql2->execute(array($location,$userid));
to
$sql2 = $conn->prepare("UPDATE stall SET file = ? WHERE stall_id = ?");
$sql2->bindParam(1, $location, PDO::PARAM_STR);
$sql2->bindParam(2, $userid, PDO::PARAM_INT);
$sql2->execute();
Related
I am very new to PHP and was trying to do the file uploading. When I try to submit a form without having any files selected, the database will still insert a value to the attachments column.
My table picture:
Is there any way that I can set the attachments column as empty if there is not file selected for submission. Below is my code:
view_group.php
<form class="forms-sample" enctype='multipart/form-data' method="post">
<div class="modal-body">
<div class="form-group">
<textarea id="status_content" name="status_content" rows="30"></textarea>
</div>
<div class="form-group">
<label for="section_label">Add Attachments</label><br>
<input type="text" class="form-control" id="file" disabled placeholder="Select a file"><br>
<button type="button" class="file-upload-browse btn btn-primary" name="button" onclick="document.getElementById('fileName').click()">Select a file</button>
<input type="file" name="attachmentfile" id="fileName" style="display:none">
</div>
</div>
<div class="modal-footer">
<button class="btn btn-outline-secondary btn-fw">Cancel</button>
<input type="submit" class="btn btn-primary" name="postStatus" value="Post" />
</div>
</form>
GroupsController.php
function postStatus($std_id, $group_id){
$status = new ManageGroupsModel();
$status->std_id = $std_id;
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
$status->attachments = time() . $_FILES['attachmentfile']['name'];
$status->target_dir = "../../attachments/groupfiles/";
//target file to save in directory
$status->target_file = $status->target_dir . basename($_FILES["attachmentfile"]["name"]);
// select file type
$status->imageFileType = strtolower(pathinfo($status->target_file,PATHINFO_EXTENSION));
// valid file extensions
$status->extensions_arr = array("jpg","jpeg","png","gif","pdf", "doc", "pdf");
if($status->postStatus() > 0) {
$message = "Status posted!";
echo "<script type='text/javascript'>alert('$message');
window.location = '../ManageGroupsView/view_group.php?group_id=".$group_id."'</script>";
}
}
GroupsModel.php
function postStatus() {
$sql = "insert into status(std_id, group_id, status_content, attachments) values(:std_id, :group_id, :status_content, :attachments)";
$args = [':std_id'=> $this->std_id, ':group_id'=> $this->group_id, ':status_content'=> $this->status_content, 'attachments'=> $this->attachments];
move_uploaded_file($_FILES['attachmentfile']['tmp_name'],$this->target_dir.$this->attachments); $stmt = DB::run($sql, $args);
$count = $stmt->rowCount(); return $count; }
I'm sorry if the question sounded dumb. It would be really great if someone can help. Thank you!
UPDATE!
Thanks to the people in my comment section, I finally get to do it. Here are the code needed to add :
function postStatus($std_id, $group_id){
$status = new ManageGroupsModel();
$status->std_id = $std_id;
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($_FILES['attachmentfile']['name']) {
$status->attachments = time() . $_FILES['attachmentfile']['name'];
$status->target_dir = "../../attachments/groupfiles/";
//target file to save in directory
$status->target_file = $status->target_dir . basename($_FILES["attachmentfile"]["name"]);
// select file type
$status->imageFileType = strtolower(pathinfo($status->target_file,PATHINFO_EXTENSION));
// valid file extensions
$status->extensions_arr = array("jpg","jpeg","png","gif","pdf", "doc", "pdf");
} else {
$status->attachments = '';
}
if($status->postStatus() > 0) {
$message = "Status posted!";
echo "<script type='text/javascript'>alert('$message');
window.location = '../ManageGroupsView/view_group.php?group_id=".$group_id."'</script>";
}
}
I am having a trouble to saving data into the database. My connection details and sql insert query everything is correct and image is also uploading to folder but I do not know why data along with image is not saving into an database when i hit upload button.Can anyone help me please?
My php code
<?php
include('server.php');
$userID = 1;
if(isset($_SESSION['username']))
{
$userName = $_SESSION['username'];
$queryID = "SELECT id from users WHERE username = '$userName'";
$resultID = $db->query($queryID);
$row=$resultID->fetch_assoc();
$userID = $row['id'];
}
if(isset($_POST['submit']))
{
$image = $_FILES['image']['name'];
$target = "images/".basename($image);
$eventName = $_POST['eventName'];
$eventDetail = $_POST['eventDetail'];
$eventDate = $_POST['eventDate'];
$eventTime = $_POST['eventTime'];
$queryImage = "INSERT INTO event_detail(eventName,eventDetails,eventDate,eventTime,imagePath,userID) VALUES('$eventName','$eventDetail','$eventDate','$eventTime','$image','$userID')";
mysqli_query($db,$queryImage);
if(move_uploaded_file($_FILES['image']['tmp_name'],$target))
{
$msg = "Image uploaded successfully";
}
else
{
$msg = "There is problem";
}
}
?>
html
<form method="post" enctype="multipart/form-data">
<label for="eventName">Event Name:<label>
<input type="text" id="eventName" name="eventName" ><br><br>
<label for="eventDetail">Event Detail:<label>
<textarea id="eventDetail" name="eventDetail" ></textarea><br><br>
<label for="eventDate">Event Date:<label>
<input type="text" id="eventDate" name="eventDate" ><br><br>
<label for="eventTime">Event Time:<label>
<input type="text" id="eventTime" name="eventTime" ><br><br>
<input type="file" id="image" name="image"><br><br>
<button type="submit" id="submit" name="submit" >Submit</button>
</form>
Change this
$queryImage = "INSERT INTO event_detail(eventName,eventDetails,eventDate,eventTime,imagePath,userID) VALUES ('$eventName','$eventDetail','$eventDate','$eventTime','$image','$userID')";
to
$queryImage = "INSERT INTO event_detail(eventName,eventDetails,eventDate,eventTime,imagePath,userID) VALUES ($eventName,$eventDetail,$eventDate,$eventTime,$image,$userID)";
I have passed a variable using GET to a new page and will like to insert the value into a table in my database but it is saying undefined variable $exex. I tried to echo it inside the 'submit' if statement but it is not seen there either. It only echo the variable inside the isset GET if statement.
Below is the code:
<?php
session_start();
include "includes/connec.inc.php";
if (isset($_GET['exid'])){
$exex=$_GET['exid'];
}
$sql = "SELECT id FROM eaouser WHERE email = '" . $_SESSION['email'] . "'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result);
$eaofid=$row['id'];
if (isset($_POST['submit'])){
if (isset($_POST['feedbacks'])){
$feedback = $_POST['feedbacks'];
if (!empty($feedback)){
$INSERT = "INSERT Into feedback (exfid,eaofid,comment) values(?,?,?)";
$stmt = $conn->prepare($INSERT);
$stmt->bind_param("iis", $exex, $eaofid, $feedback);
$stmt->execute();
if ($stmt==TRUE){
echo "<script> alert('Feedback sent!');
window.location='feedback.php'
</script>";
}else{
echo "<script> alert('Error sending feedback!');
window.location='feedback.php'
</script>";
}
}else{
echo "<script> alert('Feedback form is empty!');
window.location='feedback.php'
</script>";
}
}
}
HTML:
<div class="panel-body">
<form method="POST" action="feedback.php">
<div class="form-group">
<label for="message-text" class="col-form-label">Comment on the experiment:</label>
<textarea class="form-control" name="feedbacks" cols="142" rows="5" placeholder="Type here..."></textarea>
<br>
<button type="submit" name="submit" class="btn" style="background-color: purple;color: white">Send feedback</button>
</div>
</form>
</div>
Hi i'm having a hard time in saving a text with an input tag and an image using one button.
here is my form:
<form method = "POST" action = "image_upload_featured.php" enctype = "multipart/form-data">
<label>Drag or click for image</label>
<div id="uploader" onclick="$('#photo').click()">
<img src=""/>
</div>
<input type="file" name="image" id="photo"/>
<div id = "file_name"></div>
<button class = "btn btn-primary" name = "save"><span class = "glyphicon glyphicon-download"></span> Save Image</button>
<input class = "w3-input w3-border" type = "text" name= "fullname" placeholder = "Fullname" style="margin-bottom: 15px;" required>
<input class = "w3-input w3-border" type = "text" name= "lname" placeholder = "Lastname" style="margin-bottom: 15px;" required>
</form>
I have a php file where it can saved the image
<?php
include('db/database_configuration.php');
if(ISSET($_POST['save'])){
if($_FILES['image']['name'] == ""){
echo '<script>alert("Please Select an Image")</script>';
echo '<script>window.location = "add_featured_alumni.php"</script>';
}else{
$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"], "featured_image/". $_FILES["image"]["name"]);
$location = $_FILES["image"]["name"];
$stmt = $conn->prepare("INSERT INTO `tblfeatured` (image1) VALUES(?)") or die(mysqli_error());
$stmt->bind_param("s", $location);
if($stmt->execute()){
$stmt->close();
$conn->close();
echo '<script>alert("Successfully Upload Image")</script>';
echo '<script>window.location = "add_featured_alumni.php"</script>';
}else{
echo '<script>alert("Error")</script>';
}
}
}
?>
But this is only for the image, I know also how to save a text using input tag but without image.
I would like to combine both. Can anyone please help me?
I assume that you have fullname and lname fields (columns) are in your Database table along with image1.
Your Html
<form method = "POST" action = "image_upload_featured.php" enctype = "multipart/form-data">
<label>Drag or click for image</label>
<div id="uploader" onclick="$('#photo').click()">
<img src=""/>
</div>
<input type="file" name="image" id="photo"/>
<div id = "file_name"></div>
<input class = "w3-input w3-border" type = "text" name= "fullname" placeholder = "Fullname" style="margin-bottom: 15px;" required >
<input class = "w3-input w3-border" type = "text" name= "lname" placeholder = "Lastname" style="margin-bottom: 15px;" required >
<button type="submit" class = "btn btn-primary" name = "save"><span class = "glyphicon glyphicon-download"></span> Save Image</button>
</form>
PHP
<?php
include('db/database_configuration.php');
if(ISSET($_POST['save'])){
if($_FILES['image']['name'] == ""){
echo '<script>alert("Please Select an Image")</script>';
echo '<script>window.location = "add_featured_alumni.php"</script>';
}else{
$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"], "featured_image/". $_FILES["image"]["name"]);
$location = $_FILES["image"]["name"];
//edit.....get input values
$fullname = $_POST['fullname'];
$lname = $_POST['lname'];
$stmt = $conn->prepare("INSERT INTO `tblfeatured` (image1,fullname,lname) VALUES(?,?,?)") or die(mysqli_error($conn));
$stmt->bind_param("sss", $location,$fullname,$lname); //bind to param
//........................................
if($stmt->execute()){
$stmt->close();
$conn->close();
echo '<script>alert("Successfully Upload Image")</script>';
echo '<script>window.location = "add_featured_alumni.php"</script>';
}else{
echo '<script>alert("Error")</script>';
}
}
}
?>
NOTE: This must work except exceptional syntax error. (If your code was previously working then this must also work)
Your DB Table must be something like this
| id | image1 | fullname | lname |
i have a code for updating data to myql. It looks doesn't have a problem but it ain't changed
my update code :
//previous data//
....
if (isset($_POST['update'])) {
$nim = mysqli_real_escape_string($connection, ($_POST['nim']));
$name = mysqli_real_escape_string($connection, ($_POST['name']));
$class1 = mysqli_real_escape_string($connection, ($_POST['class2']));
$class2 = mysqli_real_escape_string($connection, ($_POST['class1']));
if (!preg_match("/^[1-9][0-9]*$/",$nim)) {
$error = true;
$nim_error = "NIM only contain numbers";
}
if (!preg_match("/[^a-zA-Z]/",$name)) {
$error = true;
$name_error = "NIM only contain numbers";
}
if (!preg_match("/^[1-9][0-9]*$/",$class1)) {
$error = true;
$class1_error = "Class only contain numbers";
}
if (!preg_match("/^[1-9][0-9]*$/",$class1)) {
$error = true;
$class2_error = "Class only contain numbers";
}
$result = "UPDATE users SET nim='$nim', name='$name', class1='$class1', class1='$class1' WHERE id='$id'";
mysqli_query($connection, $result);
}
?>
and this is my html code :
<div id="popup2" class="overlay">
<div class="popup">
<h2 class="range2">Edit</h2>
<a class="close" href="#">×</a>
<div class="content">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input class="input" type="text" name="nim" placeholder="NIM" required/>
<input class="input" type="text" name="name" placeholder="Name" required/>
<i>SK</i>
<input class="input1" type="text" name="class1" placeholder="00" required/>
<i>-</i>
<input class="input1" type="text" name="class2" placeholder="00" required/>
<input name="update" type="submit" class="button" id="submit" value="Submit">
</form>
</div>
</div>
</div>
is there any wrong code ? Thank you..
It is really hard to explain: Take a look.
If you want to update a single data you will need a identity(Primary
key). That mean which data you want to update.
Below Example: check index.php file
In file index.php change dbname to your database name in connection.
browse project_url/index.php?id=1 [here use any id from your database]
Then update your data.
index.php
//Show existed data againist id
if(isset($_GET['id'])){
$id = $_GET['id'];
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->execute(array('id'=>$id));
$data = $stmt->fetch();
if (empty($data)) {
echo "No data found in user table. Use proper ID.";
}
}
//Update query
$msg = array();
if (isset($_POST['id']) && $_POST['id']!='') { //operation is update, because id exist
if($_POST['nim']!=0 && is_numeric($_POST['nim'])){
$nim = $_POST['nim'];
}else{
$msg[]="Nim only can be number";
}
if($_POST['name']!=''){
$name = $_POST['name'];
}else{
$msg[]="came only can not be empty";
}
if(is_numeric($_POST['class1'])){
$class1 = $_POST['class1'];
}else{
$msg[]="Class1 only can be number";
}
if(is_numeric($_POST['class2'])){
$class2 = $_POST['class2'];
}else{
$msg[]="Class1 only can be number";
}
$id = $_POST['id'];
if(count($msg)==0){
$stmt = $pdo->prepare('UPDATE users SET nim=:nim, name=:name, class1=:class1, class2=:class2 WHERE id=:id');
$result = $stmt->execute(array(
'nim' => $nim,
'name' => $name,
'class1'=> $class1,
'class2'=> $class2,
'id' => $id,
));
if($result){
echo "successfully updated.";
}else{
echo "update failed";
}
}
}else{
//You can run here insert operation because id not exist.
echo "Id not set";
}
?>
<div id="popup2" class="overlay">
<div class="popup">
<h2 class="range2">Edit</h2>
<a class="close" href="#">×</a>
<div class="content">
<?php foreach ($msg as $value) {
echo $value."<br>";
}?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php if(isset($data)){?>
<input class="input" type="hidden" name="id" value="<?php echo $data['id']; ?>" />
<?php } ?>
<input class="input" type="text" name="nim" value="<?php echo isset($data)?$data['nim']:''?>" placeholder="NIM" required/>
<input class="input" type="text" name="name" value="<?php echo isset($data)?$data['name']:''?>" placeholder="Name" required/>
<i>SK</i>
<input class="input1" type="text" name="class1" value="<?php echo isset($data)?$data['class1']:''?>" placeholder="00" required/>
<i>-</i>
<input class="input1" type="text" name="class2" value="<?php echo isset($data)?$data['class2']:''?>" placeholder="00" required/>
<input name="update" type="submit" class="button" id="submit" value="Submit">
</form>
</div>
</div>
</div>
My friend,
only do one thing to resolve this
echo $result = "UPDATE users SET nim='$nim', name='$name', class1='$class1', class1='$class1' WHERE id='$id'";
die;
then submit your form again and you will get your static query into your page then just copy that query and try to run into phpmyadmin then you will get your actual error.