How to make PHP and CSS code work together - javascript

I'm working on a project, using PHP, HTML and CSS code. The problem is when I execute it without CSS code it works, but when I add CSS to it the message "successfully created" will be displayed on the bottom status bar of the webpage! Why does this happen and why won't it be displayed on the page?
This is my HTML code:
<div class="bg">
<p>Register | Login</p>
<h3>Registration Form</h3>
<form action="register.php" method = "POST">
Email: <input type = "text" name = "email"><br />
Username: <input type = "text" name = "user"><br />
Password: <input type = "password" name = "pass"><br />
<input type = "submit" value = "Login" name = "submit" />
</form>
</div>
This is my PHP code:
if (isset($_POST["submit"])) {
$email = $_POST['email'];
$user = $_POST['user'];
$pass = $_POST['pass'];
$connection = mysqli_connect('localhost' , 'root' , '', 'website') or die(mysqli_error());
mysqli_select_db($connection , "website") or die("can not select database");
if ($connection) {
$query = mysqli_query($connection ,"SELECT * FROM users WHERE username = '".$user."'");
$numOfRows = mysqli_num_rows($query);
if ($numOfRows == 0){
$sql = "INSERT INTO users( email ,username , password) VALUES('$email', '$user' , '$pass')";
$result = mysqli_query($connection , $sql);
if($result) {
echo "successfully Created";
} else {
echo "failure!";
}
} else {
echo "Username already exist!";
}
} else {
echo "can not connect to database";
}
}
This is my CSS code:
body, html {
height: 100%;
margin: 0;
}
.bg {
background-image: url("SARV.jpg");
height: 100%;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}

Because you echo in plain text instead of handling it into your html code. Take a look into your output html.

Related

Hide "submit" button once a form is sent successfully, then show success message

At the moment I have a working contact form. I'd like to hide the "submit" button of my form when the form is sent successfully and then display a success message.
At the moment it redirects, which I've left for the purpose of this request.
I've tried multiple solutions, tweaking of the js but js sure isn't my strong point. I've left the CSS in also for the purpose of this question as I believe that will be the route I need to go down.
<< ? php
if (empty($_POST) === false) {
session_start();
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$errors = array();
if (isset($_POST['name'], $_POST['email'], $_POST['message'])) {
$fields = array(
'name' => $_POST['name'],
'email' => $_POST['email'],
'message' => $_POST['message']
);
foreach($fields as $field => $data) {
if (empty($data)) {
//$errors[] = "The " . $field . " is required";
$errors[] = "Please fill-in the form correctly";
break 1;
}
}
if (empty($errors) === true) {
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$errors[] = "Invalid e-mail address";
}
}
if (empty($errors) === true) {
$name = test_input($_POST['name']);
$email = test_input($_POST['email']);
$message = test_input($_POST['message']);
$to = "example#example.com";
$subject = "example | You have a new message from ".$name;
$body = ......
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['message'])) {
$data = $_POST['name'].
' == Email: '.$_POST['email'].
' Message: '.$_POST['message'].
"\r\n";
$ret = file_put_contents('entries.log', $data, FILE_APPEND | LOCK_EX);
if ($ret === false) {
die('There was an error writing this file');
} else {
echo "$ret bytes written to file";
}
} else {
header('location: ../sendmail/redirect.html');
}
$headers = "MIME-Version: 1.0".
"\r
#thank-you-message {
display: none;
}
#thank-you-message.show {
display: block;
}
<form action="/sendmail.php" method="post" onsubmit="return checkform(this);">
<input type="text" name="name" id="" autocomplete="off" placeholder="Name" required><br>
<input type="email" name="email" id="" autocomplete="off" placeholder="E-mail" required><br>
<textarea name="message" id="" cols="30" rows="10" placeholder="Type Your Message" required></textarea>
<button type="submit">Send</button>
</form>
<p id="thank-you-message">Thank you for contacting us. We will be in touch with you soon.</p>
You can use JavaScript to hide this button or generate this site by using PHP.
You have two possibilities, cookies or sessions.
Check if cookie or session is set, if not display the button or form, if is set hide button or form.
This can be done within a If/Else condition and a simple „print“ function.
Like (PHP)
IF (isset xxx = true) {
// print nothing
// redirect to page xxx.html
// or print Text like Lorem Ipsum
}
else {
print '<form method=“POST“ action=“form.php“> … </form>';
}
After submit the form you have to set a session or cookie in „form.php“.
When a user come back to this site, the site will check the cookie or session and print the form or not.
You have to change the IF/Else condition to your needs.
You can also print a „Thank you page“ or something else you want, you can also redirect to a other page by the header function within php.
Quick fix, you could try structuring your code in this format if using PHP
function save() {
$('.btn-danger').hide()
var number_i = $('#number_i').text();
var date_s = $('#date_s').text();
var name_p = "<?php echo $_POST['product_name']; ?>";
if (number_i != '___') {
$.post('saveEntry.php', {number: number_i, date: date_s, name: name_p}, function() {
$('#confirmation').text('Info: the data was saved!');
$('#confirmation').attr('class', 'alert alert-success');
})
} else {
alert('Introdu Numar Bon Fiscal!');
}
};
No need for JS for this. Assuming your form is parsing properly, you can add the following styles to your stylesheet.
#thank-you-message {
display: none;
}
button:focus ~ #thank-you-message {
display: block;
}
I removed your PHP and the rest of your form so that you can see a demonstration. See below:
Edit ~ added sample JS for the button to change text upon form submission. (Doesn't affect p displaying on button click)
function form_success() {
document.getElementById("myform").submit();
document.getElementById("btn").innerHTML = "Sent!";
}
#thank-you-message {
display: none;
}
button:focus {
background-color: green;
color: white;
}
button:focus~#thank-you-message {
display: block;
}
<form action="/sendmail.php" method="post" onsubmit="return checkform(this);" id="myform">
<input type="text" name="name" id="" autocomplete="off" placeholder="Name" required><br>
<input type="email" name="email" id="" autocomplete="off" placeholder="E-mail" required><br>
<textarea name="message" id="" cols="30" rows="10" placeholder="Type Your Message" required></textarea><br>
<button type="submit" id="btn" onclick="form_success()">Send</button>
<p id="thank-you-message">Thank you for contacting us. We will be in touch with you soon.</p>
</form>

My registration form was working perfectly on localhost but now that it is on a c-panel server it doesn't work

This is my code, I really don't know whats wrong does anyone else know? Currently the error that comes up is Oops! Something went wrong. Please try again later. I know that the issue is not a connection issue and is not a permissions issue. I'm really confused about what I've done wrong and have even contacted customer support multiple times and they didn't know what the issue is.
<?php
include ('config.php');
// Define variables and initialize with empty values
$username = $password = $confirm_password = "";
$username_err = $password_err = $confirm_password_err = "";
// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
// Validate username
if(empty(trim($_POST["username"]))){
$username_err = "Please enter a username.";
} else{
// Prepare a select statement
$sql = "SELECT username FROM users WHERE username = ?";
if($stmt = mysqli_prepare($conn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "s", $param_username);
// Set parameters
$param_username = trim($_POST["username"]);
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) == 1){
$username_err = "This username is already taken.";
} else{
$username = trim($_POST["username"]);
}
} else{
echo "Oops! Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Validate password
if(empty(trim($_POST["password"]))){
$password_err = "Please enter a password.";
} elseif(strlen(trim($_POST["password"])) < 6){
$password_err = "Password must have atleast 6 characters.";
} else{
$password = trim($_POST["password"]);
}
// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
$confirm_password_err = "Please confirm password.";
} else{
$confirm_password = trim($_POST["confirm_password"]);
if(empty($password_err) && ($password != $confirm_password)){
$confirm_password_err = "Password did not match.";
}
}
// Check input errors before inserting in database
if(empty($username_err) && empty($password_err) && empty($confirm_password_err)){
// Prepare an insert statement
$sql = "INSERT INTO users (username, password) VALUES (?, ?)";
if($stmt = mysqli_prepare($conn, $sql)){
// Bind variables to the prepared statement as parameters
mysqli_stmt_bind_param($stmt, "ss", $param_username, $param_password);
// Set parameters
$param_username = $username;
$param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
// Attempt to execute the prepared statement
if(mysqli_stmt_execute($stmt)){
// Redirect to login page
header("location:Login.php");
} else{
echo "Something went wrong. Please try again later.";
}
}
// Close statement
mysqli_stmt_close($stmt);
}
// Close connection
mysqli_close($conn);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
<style type="text/css">
body{ font: 14px sans-serif; }
.wrapper{ width: 350px; padding: 20px; }
</style>
</head>
<body>
<div class="wrapper">
<h2>Sign Up</h2>
<p>Please fill this form to create an account.</p>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
<div class="form-group <?php echo (!empty($username_err)) ? 'has-error' : ''; ?>">
<label>Username</label>
<input type="text" name="username" class="form-control" value="<?php echo $username; ?>">
<span class="help-block"><?php echo $username_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($password_err)) ? 'has-error' : ''; ?>">
<label>Password</label>
<input type="password" name="password" class="form-control" value="<?php echo $password; ?>">
<span class="help-block"><?php echo $password_err; ?></span>
</div>
<div class="form-group <?php echo (!empty($confirm_password_err)) ? 'has-error' : ''; ?>">
<label>Confirm Password</label>
<input type="password" name="confirm_password" class="form-control" value="<?php echo $confirm_password; ?>">
<span class="help-block"><?php echo $confirm_password_err; ?></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="reset" class="btn btn-default" value="Reset">
</div>
<p>Already have an account? Login here.</p>
</form>
</div>
</body>
</html>

Session working accurately on localhost but not working on live server

I have a admin panel for login. I have created a login page with php,
html, java script. I used session to pass user to next page. This working perfectly on my localhost. But on live server i am getting problem, its showing me "loged in successfully" popup and redirecting back to login page. When i print session on localhost its showing me session value but on live server its empty. I have searched so many answers and tried same but still it's not working. Please help and thank you for your time and consideration.
My live server is Apache HTTP Server Version 2.2
My connection file db.php is
<?php
/*Default time zone ,to be able to send mail */
date_default_timezone_set('Asia/Kolkata');
//connect database
$con = mysqli_connect ("localhost","rootuser","password","testdbname"); //host, username, password, database name
//database connect error
if (mysqli_connect_errno())
{
echo "Failed to connect to MySql: " . mysqli_connect_errno();
}
?>
login.php file is
<?php
session_start();
include("includes/db.php");
if(isset($_SESSION['mysesiuid']))
{
header('Location: index.php?alreadyin');
//echo "<script>window.location.assign('index.php?alreadyin')</script>";
}
else
{
?>
<script src="assets/js/validate/jquery.js" type="text/javascript"></script>
<script>
//login script
$(document).ready(function() {
var mazalagna_login_email1 = 1;
var mazalagna_login_email2 = 1;
var mazalagna_login_email3 = 1;
var mazalagna_login_password = 1;
$("#main_login_submit").click(function(){
//password
if($("#mazalagna_pass").val() == ''){
$("#mazalagna_pass").css("border","1px solid red");
$("#mazalagna_password_error").show();
mazalagna_login_password = 1;
}else{
if($("#mazalagna_pass").val().length < 6){
$("#mazalagna_pass").css("border","1px solid red");
$("#mazalagna_password_length_error_longform").show();
$("#mazalagna_password_error").hide();
mazalagna_login_password = 1;
}else{
$("#mazalagna_pass").css("border","1px solid green");
$("#mazalagna_password_length_error_longform").hide();
$("#mazalagna_password_error").hide();
mazalagna_login_password = 0;
}
}
//email
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")#(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
var validateMazalagnaEmail = pattern.test($("#mazalagna_email").val());
if($("#mazalagna_email").val() == ''){
$("#mazalagna_email").css("border","1px solid red");
$("#mazalagna_email_error").show();
mazalagna_login_email1 = 1;
}else{
$("#mazalagna_email").css("border","1px solid green");
$("#mazalagna_email_error").hide();
mazalagna_login_email1 = 0;
}
if(!validateMazalagnaEmail){
$("#mazalagna_email").css("border","1px solid red");
$("#mazalagna_email_error").show();
mazalagna_login_email2 = 1;
}else{
$("#mazalagna_email").css("border","1px solid green");
$("#mazalagna_email_error").hide();
mazalagna_login_email2 = 0;
}
if(validateMazalagnaEmail){
$.ajax({
type: "POST",
cache: false,
url: "php/ajax_email_exist.php",
data: { email: $("#mazalagna_email").val()},
success: function (data)
{
if(data != 1){
$("#mazalagna_email").css("border","1px solid green");
$("#mazalagna_exist_email_error").hide();
mazalagna_login_email3 = 0;
}else{
$("#mazalagna_email").css("border","1px solid red");
$("#mazalagna_exist_email_error").show();
mazalagna_login_email3 = 1;
}
if(mazalagna_login_email1 == 0 && mazalagna_login_email2 == 0 && mazalagna_login_email3 == 0 && mazalagna_login_password == 0 ){
$.ajax({
type: "POST",
cache: false,
url: "main_login.php",
data: {
username1: $("#mazalagna_email").val(),
password1: $("#mazalagna_pass").val()
},
success: function (data)
{
alert(data);
//alert("Welcome! You have loged in successfully!");
window.location.replace("index.php");
}
});
}
}
});
}
//edit value
$(".regval").click(function(){
var id = "#"+$(this).attr("id");
var errorId = "#"+$(this).attr("id")+"_error";
$(id).css("border","1px solid #a39e9e");
$(errorId).hide();
});
});
});
</script>
<strong> Enter Details To Login </strong>
<!-- <form role="form" action="" method="post"> -->
<div class="form-group input-group">
<span class="input-group-addon"><i class="fa fa-tag" ></i></span>
<input type="text" id="mazalagna_email" name="mazalagna_email" class="form-control regval" placeholder="Your Username" required />
</div>
<div id="mazalagna_email_error" style="display:none; margin-top:-12px; margin-bottom:12px; text-align:center; color:red; font-size:12px;">Please enter valid Email</div>
<div id="mazalagna_exist_email_error" style="display:none; margin-top:-12px; margin-bottom:12px; text-align:center; color:red; font-size:12px;">Your email id is not registered.</div>
<div class="form-group input-group">
<span class="input-group-addon"><i class="fa fa-lock" ></i></span>
<input type="password" id="mazalagna_pass" name="mazalagna_pass" class="form-control regval" placeholder="Your Password" required />
</div>
<div id="mazalagna_password_error" style="display:none; margin-top:-12px; margin-bottom:12px; text-align:center; color:red; font-size:12px;">Please enter your password</div>
<div id="mazalagna_password_length_error_longform" style="display:none; margin-top:-12px; margin-bottom:12px; text-align:center; color:red; font-size:12px;">Enter min 6 character password</div>
<button type="submit" id="main_login_submit" name="main_login_submit" class="btn btn-primary ">Login Now</button>
<hr />
<!-- </form> -->
<?php } // top else close here ?>
My main_login.php file is
<?php
//connect database
session_start();
require_once 'includes/db.php';
global $con;
$user_email = trim($_POST['username1']);
$user_password = trim($_POST['password1']);
$password = mysqli_real_escape_string($con, md5($user_password));
$res = $con->query("SELECT * FROM useradmins WHERE email='$user_email' AND password='$password'");
$row = $res->fetch_assoc();
$uid = $row['admin_id'];
$name = $row['name'];
$useremail = $row['email'];
$pass = $row['password'];
if($useremail==$user_email && $pass==$password){
$_SESSION['mysesi']=$name;
$_SESSION['mysesiuid']=$useremail;
echo "Loged in successfully.";
//update status and login time
date_default_timezone_set('Asia/Kolkata');
$date_email = date('F j, Y h:i A');
$date = date('Y-m-d H:i:s');
$user = $_SESSION['mysesiuid'];
$ip = $_SERVER['REMOTE_ADDR'];
$httpref = $_SERVER['HTTP_REFERER'];
$httpagent = $_SERVER['HTTP_USER_AGENT'];
$update_last_login="UPDATE useradmins SET admin_status='ONLINE',active_ip_address='$ip',admin_last_login='$date' WHERE admin_id='$user'";
$update_last_login = mysqli_query($con, $update_last_login);
}
else{
echo "Unable to login.";
}
?>
index.php file is
<?php
session_start();
require_once 'includes/db.php';
if(!isset($_SESSION['mysesiuid']))
{
header('Location: login.php');
exit;
}
else
{
?>
<h1>hi success</h1>
<?php } ?> <!-- top else statement close here -->

Error trying to insert data into a mySql database

In these days I tried to write a sort of registration-login system with php and mySql and somehow I managed to do it; now I want to put all the things in a new page with a pop up window: you press the button "register" or "login" and on the screen appears a window with all the stuff and things, that's what I did:
<!DOCTYPE html>
<html>
<head>
<title>FindMyChamp</title>
</head>
<body>
<style type="text/css">
.popUpBox{
display: none;
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
background-color: rgba(0,0,0,0.4);
}
.popUpBoxBody{
margin: 15% auto;
padding: 15px;
background-color: #fefefe;
width: 30%;
}
.closeBtn{
float: right;
font-size: 28px;
}
.container{
width: 300px;
clear: both;
display: block;
margin-left: auto;
margin-right: auto;
text-align: center;
}
.container input{
width: 100%;
clear: both;
}
#send{
width: 50%;
}
</style>
<h1>Test</h1>
<p id="popUpTrigger">Register</p>
<p>Login</p>
<div id="divPopUp" class="popUpBox">
<div class="popUpBoxBody">
<span id="popUpCloser" class="closeBtn">×</span>
<div class="container">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Username: <input type="text" name="username">
Password: <input type="password" name="password">
Repeat Password: <input type="password" name="passwordCheck"><br><br>
<input value="Send" id="send" type="submit" name="sub">
</form>
<?php include('registration.php') ?>
</div>
</div>
</div>
<script type="text/javascript">
var btnOpen = document.getElementById("popUpTrigger");
var popUp = document.getElementById("divPopUp");
var btnClose = document.getElementById("popUpCloser")
btnOpen.onclick = function(){
popUp.style.display = "block";
}
btnClose.onclick = function(){
popUp.style.display ="none";
}
</script>
register.php:
<?php
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(isset($_POST["sub"])){
$username = $password = $passwordCheck = "";
$flag = true;
$con = mysql_connect('localhost','root','Testpass');
if($_SERVER["REQUEST_METHOD"] == "POST"){
//Controllo se i campi sono vuoti
if(empty($_POST["username"])){
echo "The field 'Username' is required<br>";
} else{
$username = test_input($_POST["username"]);
}
if(empty($_POST["password"])){
echo "The field 'Password' is required<br>";
$flag = false;
} else{
$password = test_input($_POST["password"]);
}
if(empty($_POST["passwordCheck"])){
echo "The field 'Repeat Password' is required<br>";
$flag = false;
} else{
$passwordCheck = test_input($_POST["passwordCheck"]);
}
}
if($password == $passwordCheck && $password != ""){
mysql_select_db('tutorials');
$checkUsernameDuplicate = mysql_query("SELECT * FROM registration WHERE username = '$username'");
if(mysql_num_rows($checkUsernameDuplicate) <= 0){
$cost = 10;
$salt = strtr(base64_encode(mcrypt_create_iv(16,MCRYPT_DEV_URANDOM)), '+', '.');
$salt = sprintf("$2a$%02d$", $cost). $salt;
$hash = crypt($password, $salt);
$sql = "INSERT INTO registration(username,password) VALUES('$username','$hash')";
$retvalue = mysql_query($sql,$con);
if(!$retvalue){
echo "Something went wrong";
} else{
echo "Dati inseriti";
//header("Location: http://localhost/database/login.php");
exit();
}
} else{
echo "Username aldready taken";
}
mysql_close($con);
}
elseif($flag){
echo "<p style='color: red;'>The two password must match</p>";
}
}
?>
Everything works fine, but, when I press the button 'send' the window disappears and all the datas are send to the database, that's ok but I want that the windows remains until the user decides to close it. How can I do that?
use ajax, you can execute your code in register.php without refreshing your page
http://api.jquery.com/jquery.ajax/

PHP - Edit elements is gone after updating

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'];
}
}
}

Categories