This is what it looks like.
But when i press the submit button it wont upload the image.
Is it possible to have 2 functions in one SUBMIT?
It saves the other data in my database but the image is not uploaded nor it is in my database.
<?php
$con=mysqli_connect("localhost","root","","presyohan");
// Check connection
if (mysqli_connect_error())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit']))
{
$prod_name = $_POST['prod_name'];
$prod_price = $_POST['prod_price'];
$prod_category = $_POST['prod_category'];
$sql="INSERT INTO products (prod_name, prod_price, prod_category)
VALUES('$prod_name','$prod_price','$prod_category')";
$result=mysql_query($sql);
if ($con->query($sql) === TRUE) {
session_start();
$_SESSION['users'] = $rows['prod_name'];
$_SESSION['id'] = $rows['user_id'];
header("Location: store-index.php");
die();
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
//imageupload
$filename = $_FILES['uploadfile']['name'];
$filetmpname = $_FILES['uploadfile']['tmp_name'];
$folder = 'images/products/';
move_uploaded_file($filetmpname, $folder.$filename);
$sqls = "INSERT INTO 'products' ('prod_img') VALUES ('$filename')";
$qry = mysqli_query($con, $sqls);
if ($qry) {
echo 'header("Location: store-index.php")';
}
$con->close();
}
?>
<form class="form" action="add-prod.php" method="post" enctype="multipart/form-data">
<div class="upload-btn-wrapper">
<label for="file-upload" class="custom-file-upload">
Product Image <i class="fas fa-cloud-upload-alt"></i>
</label>
<input id="file-upload" type="file" name="uploadfile" />
</div>
<div class="form__group">
<button class="btn" type="submit" name="submit">ADD</button>
</div>
</form>
enter image description here
Related
My login does not go to index.php after loging in, the page just refreshes
i am using MySqli and the database details are in the config file
This is the login.php
<form action="" method="post">
UserName: <input type="text" name="uname"><br>
Password: <input type="text" name="psw1"><br>
<button type="submit" name="submit">Login</button>
</form>
<?php
require 'config1.php';
if(isset($_POST["submit"])){
$uname = $_POST["uname"];
$psw1 = $_POST["psw1"];
$result = mysqli_query($conn, "SELECT * FROM Users WHERE Username = '$uname'");
$row = mysqli_fetch_assoc($result);
if(mysqli_num_rows($result) > 0){
if($psw1 == $row["Password"]){
$_SESSION["login"] = true;
$_SESSION["id"] = $row["id"];
header("Location: index.php");
}
else{
echo
"<script> alert('wrong password'); </script>";
}
}
else{
echo
"<script> alert('User not regitered'); </script>";
};
}
?>
This the index.php, hence the page i am supposed to go to after a successful login
`<?php
require 'config1.php';
if(!empty($_SESSION["id"])){
$id = $_SESSION["id"];
$result = mysqli_query($conn, "SELECT * FROM Users WHERE id = $id");
$row = mysqli_fetch_assoc($result);
}
else{
header("Location: login.php");
}
?>
<!DOCTYPE html>
<html>
<body>
<h1>Welcome <?php echo $row["name"]; ?></h1>
Log out
</body>
</html>`
You are emitting html before you execute the header. It does not work that way. You cannot change the page after the browser has received some html, in this case the form. So re-organise it this way.
<?php
require 'config1.php';
if(isset($_POST["submit"])){
$uname = $_POST["uname"];
$psw1 = $_POST["psw1"];
$result = mysqli_query($conn, "SELECT * FROM Users WHERE Username = '$uname'");
$row = mysqli_fetch_assoc($result);
if(mysqli_num_rows($result) > 0){
if($psw1 == $row["Password"]){
$_SESSION["login"] = true;
$_SESSION["id"] = $row["id"];
header("Location: index.php");
exit;
}
else{
echo
"<script> alert('wrong password'); </script>";
}
}
else{
echo
"<script> alert('User not regitered'); </script>";
};
}
?>
<form action="" method="post">
UserName: <input type="text" name="uname"><br>
Password: <input type="text" name="psw1"><br>
<button type="submit" name="submit">Login</button>
</form>
Note that there is an exit after the header because you dont want the rest of the file getting executed.
Note
This assumes that config1.php does not echo or emit any html
I am posting the "user" variable to another page i.e. Survey.php as follows:
index.html
<form action="Survey.php" method="post" name="frm">
<div><input type="text" name="user"></div>
<div><input type="submit" value="Start" class="btn btn-primary btn-sm"></div>
</form>
I can access the "user" variable on Survey.php page on its first load.
Now, because I have another form on this page as well, which posts data to itself.
Survey.php
$user = $_POST["user"];
echo 'this is '.$user;
$email = $_POST[email];
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$sql = "INSERT INTO `test_db` (`user`, `email`) VALUES '$user', '$email');";
echo $sql;
}
<form action="survey.php" method="post">
<div><input type="text" name="email"></div>
<div><input type="submit" value="submit" class="btn btn-primary btn-sm"></div>
</form>
I am trying to send "user" and "email" together to the database now. What happens actually is that everytime I click on submit button of the survey.php page, the "user" variable gets empty.
You have to test your posts DATA and user Sesssion.
In your PHP code, you can have something like that
<?php
session_start();
if(isset($_POST['user']))
$_SESSION['user'] = $_POST['user'];
if(isset($_POST['email']))
$_SESSION['email'] = $_POST['email'];
if(isset($_SESSION['user']) AND isset($_SESSION['email'])){
$sql = "INSERT INTO `test_db` (`user`, `email`) VALUES '$_SESSION['user']', '$_SESSION['email']');";
echo $sql;
}
If you don't want to use sessions, you can play with your form like this :
$user = $_POST["user"];
echo 'this is '.$user;
$email = $_POST[email];
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$sql = "INSERT INTO `test_db` (`user`, `email`) VALUES '$user', '$email');";
echo $sql;
}
<form action="survey.php" method="post">
<div><input type="text" name="email"></div>
<div><input type="submit" value="submit" class="btn btn-primary btn-sm"></div>
<input type="hidden" name="user" value="<?php echo $user; ?>">
</form>
You have $user and $email as variable then why are you putting them as strings? The below code should work -
$user = $_POST["user"];
echo 'this is '.$user;
$email = $_POST[email];
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$sql = "INSERT INTO `test_db` (`user`, `email`) VALUES '" . $user . "', '" . $email . "');";
echo $sql;
}
<form action="survey.php" method="post">
<div><input type="text" name="email"></div>
<div><input type="submit" value="submit" class="btn btn-primary btn-sm"></div>
</form>
How would I code into my program using PHP/JavaScript and HTML/CSS to display data from a database I made in MySQL Monitor on the blue section below:
I made buttons that use PHP to go into the database and show the data on the HTML page:
HTML:
<form action="fullridez.php" method="post">
<h4 id="Filter">GPA</h4>
<input id="FilterBox" name="gpa" type="text"/>
<h4 id="Filter">Amount</h4>
<input id="FilterBox" name="amount" type="text"/>
<h4 id="Filter">School</h4>
<input id="FilterBox" name="school" type="text"/>
<input type="submit" id="FilterBox" name="myForm" onkeypress="checkEnter()" ><img src="search.png" width=15 height=15 /></button>
</form>
<script>
</script>
PHP:
<?php
if(isset($_POST['myForm'])) {
$servername = "localhost";
$username = "root";
$password = "";
$database = "scholarshiplist";
$conn = mysqli_connect($servername, $username, $password, $database);
$gpa = $_POST['gpa'];
$amount = $_POST['amount'];
$count = "SELECT * FROM scholarships";
$result = mysqli_query($conn, $count);
if ($result->num_rows > 0) {
$sql = "SELECT * FROM scholarships WHERE GPA <= " . $gpa . " AND Amount <= "
. $amount;
if ($result = mysqli_query($conn, $sql)) {
while ($row=mysqli_fetch_row($result)) {
for($i = 0; $i < count($row); $i++) {
echo $row[$i] . '<br>';
}
}
}
} else {
echo "0 results";
}
$conn->close();
}
SQL:
USE ScholarshipList;
CREATE TABLE Scholarships
(
id int unsigned NOT NULL auto_increment,
School varchar(500) NOT NULL,
GPA decimal(10,2) NOT NULL,
Amount decimal(10,2) NOT NULL,
PRIMARY KEY (id)
);
I am using XAMPP
When I click the button on the HTML file it bring me to the PHP page and all I see is the PHP code. I don't want it to go to the page but stay on the same page showing the data below the buttons.
This is what the page looks like so far
page
What am I doing wrong?
If your HTML form is contained within the 'fullridez.php' file and you are posting the form inputs to that same file, then you need to have some PHP where you'd like to output to be checking for results and then looping through those results while echoing them out:
<table>
<tr><td>Col 1</td><td>Col 2</td><td>Col 3</td></tr>
<?php
while($row = mysql_fetch_assoc($result))
{
echo "<tr><td>"
. $row['col_1'] . "</td><td>"
. $row['col_2'] . "</td><td>"
. $row['col_3'] . "</td></tr>";
}
?>
</table>
You can build a wireframe div table with for loop:
<?php
$num_rows = mysql_num_rows($result);
for ($i=0;$i<$num_rows;$i++) {
//loop through all rows of data
$row = mysql_fetch_assoc($result); // your data is now: $row['fieldName']
?>
<div>
GPA <input name="" value="<?php echo($row['gpa'])?>;" type="text">
AMOUNT <input name="" value="<?php echo($row['amount'])?>;" type="text">
SCHOOL <input name="" value="<?php echo($row['school'])?>;" type="text">
</div>
<?php
} //end of the loop
?>
Hello monsters of programming, Good day! What i want to do is, when the user click the file button and upload the image it will update, else if the user didn't change it just echo that image. But when the user didn't change the image, im having an error **Warning**: file_get_contents(): Filename cannot be empty in C:\xampp\htdocs\studentportal\edit2.php on line 27 Can someone help me? The if(isset($_FILES['image'])) is working properly but the else statement is not. How can i just echo that image if the user didn't change it? Im new to php and starting to learn it please give me ideas.
this is cause of the error the $newsimages = $row['news_image']; in the else statement.
else{
$title = $_POST['titles'];
$date = $_POST['dates'];
$content = $_POST['contents'];
$newsimages = $row['news_image'];
$sql ="UPDATE news SET news_title ='$title', news_date ='$date', news_content = '$content', news_image ='$newsimages' WHERE news_id = '$newsid'";
mysqli_query($con, $sql);
echo "oh it worked again ";
}
this is all of the php code
<?php
include_once('connection.php');
$newsid = $_GET['news_id'];
if(isset($_POST['esubmit'])){
/* create a prepared statement */
if ($stmt = mysqli_prepare($con, "SELECT * FROM news WHERE news_id = ? LIMIT 1")) {
/* bind parameters */
mysqli_stmt_bind_param($stmt, "s", $newsid);
/* execute query */
mysqli_stmt_execute($stmt);
/* get the result set */
$result = mysqli_stmt_get_result($stmt);
/* fetch row from the result set */
$row = mysqli_fetch_array($result);
}
}
if(isset($_POST['update'])){
if(isset($_FILES['image'])){
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"img/" . $_FILES["image"]["name"]);
$newsimage="img/" . $_FILES["image"]["name"];
$title = $_POST['titles'];
$date = $_POST['dates'];
$content = $_POST['contents'];
$sql ="UPDATE news SET news_title ='$title', news_date ='$date', news_content = '$content', news_image ='$newsimage' WHERE news_id = '$newsid'";
mysqli_query($con, $sql);
echo "oh it worked ";
}
else{
$title = $_POST['titles'];
$date = $_POST['dates'];
$content = $_POST['contents'];
$newsimages = $row['news_image'];
$sql ="UPDATE news SET news_title ='$title', news_date ='$date', news_content = '$content', news_image ='$newsimages' WHERE news_id = '$newsid'";
mysqli_query($con, $sql);
echo "oh it worked again ";
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
if(isset($_POST['esubmit'])){
?>
<form method="post" action ="edit2.php?news_id=<?php echo $row['news_id']; ?>" enctype="multipart/form-data">
Title<input type ="text" name ="titles" value="<?php echo $row['news_title']; ?>"/><br>
Date<input type ="text" name="dates" value="<?php echo $row['news_date']; ?>" /><br>
Content<textarea name="contents"><?php echo $row['news_content']; ?></textarea>
<input class="form-control" id="image" name="image" type="file" accept="image/*" onchange='AlertFilesize();'/>
<img id="blah" src="<?php echo $row['news_image']; ?>" alt="your image" style="width:200px; height:140px;"/>
<input type="submit" name="update" value="Update" />
</form>
<?php
}
?>
<script src="js/jquery-1.12.4.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#image").change(function(){
readURL(this);
});
</script>
</body>
</html>
What you can do is remove <img></img> out of the first form and put it in separate <form> with separate submit button and add more php code to just update image only.You will have two forms and two updates like
$sql1 ="UPDATE news SET news_title ='$title', news_date ='$date', news_content = '$content' WHERE news_id = '$newsid'";
$sql2="update new SET new_image='$newsimages' WHERE new_id='$newsid'";
I Hope You undestand.I have done same thing for one of my websites.I think this is the best solution.Try it.For further query you can comment.
Goodmorning. My problem is after clicking the update button the edit elements are gone like the title, date, content and the image only the echo output is shown "successfully updated". What i want to do is after clicking the update button the elements will stay there and it will echo there.
Here is my edit2.php
after i click the update button only the output "Successfully update" is shown the edit elements is gone
here is the php code for edit2.php
<?php
include_once('connection.php');
$newsid = $_GET['news_id'];
if(isset($_POST['esubmit'])){
/* create a prepared statement */
if ($stmt = mysqli_prepare($con, "SELECT * FROM news WHERE news_id = ? LIMIT 1")) {
/* bind parameters */
mysqli_stmt_bind_param($stmt, "s", $newsid);
/* execute query */
mysqli_stmt_execute($stmt);
/* get the result set */
$result = mysqli_stmt_get_result($stmt);
/* fetch row from the result set */
$row = mysqli_fetch_array($result);
}
}
if(isset($_POST['update'])){
if($_FILES['image']['error'] == 0) {
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name = addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"img/" . $_FILES["image"]["name"]);
$newsimage="img/" . $_FILES["image"]["name"];
$title = $_POST['titles'];
$date = $_POST['dates'];
$content = $_POST['contents'];
$sql ="UPDATE news SET news_title ='$title', news_date ='$date', news_content = '$content', news_image ='$newsimage' WHERE news_id = '$newsid'";
mysqli_query($con, $sql);
echo "successfully updated";
}
else{
$title = $_POST['titles'];
$date = $_POST['dates'];
$content = $_POST['contents'];
$sql ="UPDATE news SET news_title ='$title', news_date ='$date', news_content = '$content' WHERE news_id = '$newsid'";
mysqli_query($con, $sql);
echo "successfully updated";
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php
if(isset($_POST['esubmit'])){
?>
<form method="post" enctype="multipart/form-data" action ="edit2.php?news_id=<?php echo $row['news_id']; ?>" >
Title<input type ="text" name ="titles" value="<?php echo $row['news_title']; ?>"/><br>
Date<input type ="text" name="dates" value="<?php echo $row['news_date']; ?>" /><br>
Content<textarea name="contents"><?php echo $row['news_content']; ?></textarea>
<input class="form-control" id="image" name="image" type="file" accept="image/*" onchange='AlertFilesize();'/>
<img id="blah" src="<?php echo $row['news_image']; ?>" alt="your image" style="width:200px; height:140px;"/>
<input type="submit" name="update" value="Update" />
</form>
<?php
}
?>
<script src="js/jquery-1.12.4.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#image").change(function(){
readURL(this);
});
</script>
</body>
</html>
The problem is because of this if block,
if(isset($_POST['esubmit'])){ ...
When you submit the form, $_POST['esubmit'] will be not get set and hence, the form won't get displayed again. So your if block should be like this:
if(isset($_POST['esubmit']) || isset($_POST['update'])){ ...
Overall, you need to change your first and third if blocks in the following way,
if(isset($_POST['esubmit'])){
/* create a prepared statement */
if ($stmt = mysqli_prepare($con, "SELECT * FROM news WHERE news_id = ? LIMIT 1")) {
/* bind parameters */
mysqli_stmt_bind_param($stmt, "s", $newsid);
/* execute query */
mysqli_stmt_execute($stmt);
/* get the result set */
$result = mysqli_stmt_get_result($stmt);
/* fetch row from the result set */
$row = mysqli_fetch_array($result);
/* get all values */
$title = $row['news_title'];
$date = $row['news_date'];;
$content = $row['news_content'];
$newsimage = $row['news_image'];
}
}
And
if(isset($_POST['esubmit']) || isset($_POST['update'])){
?>
<form method="post" enctype="multipart/form-data" action ="edit2.php?news_id=<?php echo $newsid; ?>" >
Title<input type ="text" name ="titles" value="<?php if(isset($title)){ echo $title; } ?>"/><br>
Date<input type ="text" name="dates" value="<?php if(isset($date)){ echo $date; } ?>" /><br>
Content<textarea name="contents"><?php if(isset($content)){ echo $content; } ?></textarea>
<input class="form-control" id="image" name="image" type="file" accept="image/*" onchange='AlertFilesize();'/>
<img id="blah" src="<?php if(isset($newsimage)){ echo $newsimage; } ?>" alt="your image" style="width:200px; height:140px;"/>
<input type="submit" name="update" value="Update" />
</form>
<?php
}
From the extended discussion,
Since you're making image upload optional, you need to fetch image details in the else block where you process the form in case user doesn't upload an image, like this:
if(isset($_POST['update'])){
if($_FILES['image']['error'] == 0) {
// your code
}else{
// your code
/* get the image details*/
if ($stmt = mysqli_prepare($con, "SELECT news_image FROM news WHERE news_id = ? LIMIT 1")) {
mysqli_stmt_bind_param($stmt, "s", $newsid);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_array($result);
$newsimage = $row['news_image'];
}
}
}