$_GET in uploading image - javascript

my code is working if I use $_SESSION but I need to name the file what is in the URL.
this is the sample URL: localhost/boldr/updateimage.php?EMPLOYEE_ID=180627-027
I want to rename the uploaded image like profile180627-027 but it's not working in $_GET.
<?php
$id = $_GET['EMPLOYEE_ID'];
if (isset($_POST['submit'])){
$file = $_FILES['file'];
$fileName = $_FILES['file']['name'];
$fileTmpName = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileError = $_FILES['file']['error'];
$fileType = $_FILES['file']['type'];
$fileExt = explode('.',$fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('jpg', 'jpeg', 'png');
if(in_array($fileActualExt, $allowed)){
if($fileError == 0){
if($fileSize < 1000000){
$fileNameNew = "profile".$id.".".$fileActualExt;
$fileDestination = 'img/'.$fileNameNew;
move_uploaded_file($fileTmpName, $fileDestination);
$sql = "UPDATE employees SET image=0 WHERE EMPLOYEE_ID='$id'";
$result = mysqli_query($conn, $sql);
header("Location: updateimage.php?EMPLOYEE_ID=$id");
}else{
echo "Your file is to big";
}
}else{
echo "There was an error!";
}
}else{
echo "You cannot upload files of this file";
}
}
echo "<form action='updateimage.php' method='POST' enctype='multipart/form-
data'>
<input type='file' name='file'>
<button type='submit' name='submit'>Upload</button>
</form>";
?>

How about trying this in your form part:
action='updateimage.php?EMPLOYEE_ID=$id'

Related

Having trouble with datatable invalid JSON response

I keep having this error. I manage to track down the response by inspecting the dataTable which lead me to believe that this is the source of the problem. Please bear with me for I'm still a beginner in javascript and PHP.
image link to error:
source of error
here are my codes:
config.php
<?php
class dbConfig {
protected $serverName;
protected $userName;
protected $password;
protected $dbName;
function dbConfig() {
$this -> serverName = 'localhost';
$this -> userName = 'root';
$this -> password = '';
$this -> dbName = 'database';
}
}
?>
user.php
<?php
require('config.php');
class User extends dbconfig {
protected $hostName;
protected $userName;
protected $password;
protected $dbName;
private $userTable = 'user';
private $dbConnect = false;
public function __construct(){
if(!$this->dbConnect){
$database = new dbConfig();
$this -> hostName = $database -> serverName;
$this -> userName = $database -> userName;
$this -> password = $database -> password;
$this -> dbName = $database -> dbName;
$conn = new mysqli($this->hostName, $this->userName, $this->password, $this->dbName);
if($conn->connect_error){
die("Error failed to connect to MySQL: " . $conn->connect_error);
} else{
$this->dbConnect = $conn;
}
}
}
private function getData($query) {
$result = mysqli_query($this->dbConnect, $query);
if(!$result){
die('Error in query: '. mysqli_error());
}
$data= array();
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$data[]=$row;
}
return $data;
}
private function getNumRows($query) {
$result = mysqli_query($this->dbConnect, $query);
if(!$result){
die('Error in query: '. mysqli_error());
}
$numRows = mysqli_num_rows($result);
return $numRows;
}
public function userList(){
$query = "SELECT * FROM ".$this->userTable." ";
if(!empty($_POST["search"]["value"])){
$query .= 'where(user_id LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_fname LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_mname LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_lname LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_address LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_contactnumber LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_birthdate LIKE "%'.$_POST["search"]["value"].'%") ';
}
if(!empty($_POST["order"])){
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
} else {
$query .= 'ORDER BY id DESC ';
}
if($_POST["length"] != -1){
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$result = mysqli_query($this->dbConnect, $query);
$numRows = mysqli_num_rows($result);
$userData = array();
while ($user = mysqli_fetch_assoc($result)) {
$userRows = array();
$userRows[] = $user['user_id'];
$userRows[] = ucfirst($user['user_fname']);
$userRows[] = $user['user_mname'];
$userRows[] = $user['user_lname'];
$userRows[] = $user['user_address'];
$userRows[] = $user['user_contactnumber'];
$userRows[] = $user['user_birthdate'];
$userRows[] = '>button type="button" name="update" id="'.$user['user_id'].'"class="btn btn-warning btn-xs update"<Update>/button<';
$userRows[] = '>button type="button" name="delete" id="'.$user['user_id'].'"class="btn btn-danger btn-xs update"<Delete>/button<';
$userData[] = $userRows;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $numRows,
"recordsFiltered" => $numRows,
"data" => $userData
);
echo json_encode($output);
}
}
?>
ajax.js
$(document).ready(function(){
var userRecords = $('#userList').DataTable({
"lengthChange": false,
"processing": true,
"serverSide": true,
"order":[],
"ajax":{
url:"process.php",
type: "POST",
data: {action: 'listUser'},
dataType: "json"
},
"columnDefs":[
{
"targets": [0, 6, 7],
"orderable": false,
},
],
"pageLength": 10
});
});
process.php
<?php
include('user.php');
$user = new User();
if (!empty($_POST['action']) && $_POST['action'] == 'listUser') {
$user -> userList();
}
?>

Javascript code stops working after page Load More .load()

When data is fetched on auto Load More, another JavaScript (which is given below) stops working.
Even when it shows the 1st page default it works there but after scrolling down it does not work.
Updated with more explaination with index and getdata file. I'm fetching data like mentioned in the below codes.
index.php
<div>
<?php include('getdata.php'); ?>
</div>
<script>
$(document).ready(function(){
var is_ajaxed = false;
function getresult(url) {
$.ajax({
url: url,
type: "GET",
data: {rowcount:$("#rowcount").val()+1},
beforeSend: function(){
$('#loader-icon').show();
},
complete: function(){
$('#loader-icon').hide();
},
success: function(data){
$("#faq-result").append(data);
},
error: function(){}
});
}
$(window).scroll(function(){
if ($(window).scrollTop() >= ($(document).height() - $(window).height()-900) && is_ajaxed == false){
if($(".pagenum").val() <= $(".total-page").val()) {
var pagenum = parseInt($(".pagenum").val()) + 1;
var pname = "<?php echo $pgianame; ?>";
var sname = "<?php echo $stianame; ?>";
getresult('sellers_forum_page_posts_getresult.php?page='+pagenum+'&pname='+pname+'&sname='+sname);
is_ajaxed = true
}
}
});
});
</script>
getdata.php
<?php
include ('db.php');
$perPage = 10;
$sql = "select * from posts where status = 1";
$faq3x = $dba3->query($sql);
$allrowscount = mysqli_num_rows($faq3x);
$pages = ceil($allrowscount/$perPage);
$page = 1;
if(!empty($_GET["page"])) {
$page = $_GET["page"];
}
$start = ($page-1)*$perPage;
if($start <= 0) $start = 0;
$sqlsC = "select * from posts where status = 1 ";
$query = $sql . " limit " . $start . "," . $perPage;
$faq3xsC = $dba3->query($query);
echo '<input type="text" class="pagenum" value="'.$page.'" />';
echo '<input type="text" class="total-page" value="'.$pages.'" />';
while ($faqC = $faq3xsC->fetch_assoc()) {
$id = $faqC['id'];
$ext = ".doc";
$name = $id.$ext;
$filepath = "blog/posts/";
$filename = $filepath.$name;
if(file_exists($filename)) {
if(($fhP = fopen($filename, 'r')) !== false ) {
$headersxP = fread($fhP, 999000);
$commentsPP = nl2br($headersxP);
$countxP = 0;
$fhxP = fopen($filename, 'r');
while(!feof($fhxP)){
$frxP = fread($fhxP, 999999);
$countxP += strlen($frxP);
}
fclose($fhxP);
?>
<?php echo substr($commentsPP, 0, 511); ?>
<span id="dots_<?php echo $idPost; ?>">...</span>
<span id="more_<?php echo $idPost; ?>" style="">
<?php echo substr($commentsPP, 512, 999999); ?>
</span>
<a onclick="myFunctionx_<?php echo $id; ?>()"
id="myBtn_<?php echo $id; ?>"> See More <i class="fa fa-long-arrow-right"></i></a>
<script>
function myFunctionx_<?php echo $id; ?>() {
var dots_<?php echo $id; ?> = document.getElementById("dots_<?php echo $id; ?>");
var moreText_<?php echo $id; ?> = document.getElementById("more_<?php echo $id; ?>");
var btnText_<?php echo $id; ?> = document.getElementById("myBtn_<?php echo $id; ?>");
if (dots_<?php echo $id; ?>.style.display === "none") {
dots_<?php echo $id; ?>.style.display = "inline";
btnText_<?php echo $id; ?>.innerHTML = " See more <i class='fa fa-long-arrow-right'></i>";
moreText_<?php echo $id; ?>.style.display = "none";
} else {
dots_<?php echo $id; ?>.style.display = "none";
btnText_<?php echo $id; ?>.innerHTML = " <i class='fa fa-long-arrow-left'></i> See less";
moreText_<?php echo $id; ?>.style.display = "inline";
}
}
</script>
<?php } ?>

What should I put in my updating.php when I need to update users status if online or offline every 5 seconds?

Hi I've made a messaging feature,it displays the receivers of the message in an account, beside the receiver's name is a green or red dot, for online or offline, it is successful when I log in 2 accounts and messaged each other, when I open the first account, the other account is offline, when I open the second account, the other is online, what my problem is I want to update their status in every five seconds so that their dot will be accurate whenever they log out or log in. I have made a javascript and ajax below this page left-col.php and I've tried copying the whole code, putting it to updating.php but it did not work, what should be the appropriate data inorder to update user receiver status in every 5 seconds inside the updating.php? and also, does my the javascript and ajax needs a library to be included that's why it didn't work? Please help.
<?php
require('connection.php');
$user_name=$_SESSION['username'];
$user_id=$_SESSION['user_id'];
if(!isset($_SESSION['user_id'])){
header("LOCATION: index.php");
}else{
$advance_time=time()+15;
$query=mysqli_query($con,"SELECT * FROM status WHERE user_id='$user_id'");
if(mysqli_num_rows($query)>0){
mysqli_query($con,"UPDATE status SET status='$advance_time' WHERE user_id='$user_id'");
}else{
mysqli_query($con,"INSERT INTO status(user_id,status) VALUES ('$user_id','$advance_time')");
}
}
?>
<div id="left-col-container">
<div style="cursor:pointer" onclick="document.getElementById('new-message').style.display='block'" class="white-back">
<p align="center">New Message </p>
</div>
<?php
$q='SELECT DISTINCT `receiver_name`,`sender_name`,`date_time`
FROM `messages` WHERE
`sender_name`="'.$_SESSION['username'].'" OR
`receiver_name`="'.$_SESSION['username'].'"
ORDER BY `date_time` DESC';
$e='SELECT * from messages';
$r=mysqli_query($con,$q);
if($r){
if(mysqli_num_rows($r)>0){
$counter=0;
$added_user=array();
while($row=mysqli_fetch_assoc($r)){
$sender_name=$row['sender_name'];
$receiver_name=$row['receiver_name'];
$timestamp=$row['date_time'];
if($_SESSION['username']==$sender_name){
//add the receiver_name but only once
//so to do that check the user in array
if(in_array($receiver_name,$added_user)){
//dont add receiver_name because
//he is already added
}else{
//add the receiver_name
?>
<div class="grey-back">
<img src="images/s.jpg" class="image"/>
<?php
echo ''.$receiver_name.'';
$fetch_content=mysqli_query($con,"SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id`");
while($row_fetch=mysqli_fetch_array($fetch_content)){
$time=$row_fetch[5];
if($time<= time()){
$status = "<img src='images/r.png' height='10' width='10' style='float:right'>";
}else{
$status= "<img src='images/a.png' height='10' width='10' style='float:right'>";
}
}
echo $status;
?>
</div>
<?php
//as receiver_name added so
///add it to the array as well
$added_user=array($counter=>$receiver_name);
//increment the counter
$counter++;
}
}elseif($_SESSION['username']==$receiver_name){
//add the sender_name but only once
//so to do that check the user in array
if(in_array($sender_name,$added_user)){
//dont add sender_name because
//he is already added
}else{
//add the sender_name
?>
<div class="grey-back">
<img src="images/s.jpg" class="image"/>
<?php echo ''.$sender_name.'';
$fetch_content=mysqli_query($con,"SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id`");
while($row_fetch=mysqli_fetch_array($fetch_content)){
$time=$row_fetch[5];
if($time<= time()){
$status = "<img src='images/r.png' height='10' width='10' style='float:right'>";
}else{
$status= "<img src='images/a.png' height='10' width='10' style='float:right'>";
}
}
echo $status;
?>
</div>
<?php
//as sender_name added so
///add it to the array as well
$added_user=array($counter=>$sender_name);
//increment the counter
$counter++;
}
}
}
}
else{
//no message sent
echo 'no user';
}
}else{
//query problem
echo $q;
}
?>
<!-- end of left-col-container -->
</div>
<input type="hidden" value="<?php echo $user_id; ?>" id="from_user_id">
<script type="text/javascript">
setInterval(function(){updating_status()},5000);
function updating_status(){
let this_user = $('#from_user_id').val();
$.ajax({
method: "POST",
url: "updating.php",
data: {from_user:this_user},
success: function(response){
$('#content').html(response);
}
});
}
</script>
You need to handle the $_SESSION in all pages
Updating.php code:
<?php
require('connection.php');
session_start();
$user_name = $_SESSION['username'];
$user_id = $_SESSION['user_id'];
if(isset($_REQUEST['from_user'])){
$advance_time=time()+15;
$user_id = $_REQUEST['from_user'];
$query=mysqli_query($con,"SELECT * FROM status WHERE user_id='$user_id'");
if(mysqli_num_rows($query)>0){
mysqli_query($con,"UPDATE status SET status='$advance_time' WHERE user_id='$user_id'");
}
}else{
mysqli_query($con,"INSERT INTO status(user_id,status) VALUES ('$user_id','$advance_time')");
}
$html_left_div = '';
$html_left_div .='<div id="left-col-container">
<div style="cursor:pointer" onclick="document.getElementById(\'new-message\').style.display=\'block\'" class="white-back">
<p align="center">New Message </p>
</div>';
$q = 'SELECT DISTINCT `receiver_name`,`sender_name`,`date_time`
FROM `messages` WHERE
`sender_name`="' . $_SESSION['username'] . '" OR
`receiver_name`="' . $_SESSION['username'] . '"
ORDER BY `date_time` DESC';
$e = 'SELECT * from messages';
$r = mysqli_query($con, $q);
// echo $q;
if ($r) {
if (mysqli_num_rows($r) > 0) {
$counter = 0;
$added_user = array();
while ($row = mysqli_fetch_assoc($r)) {
$sender_name = $row['sender_name'];
$receiver_name = $row['receiver_name'];
$timestamp = $row['date_time'];
if ($_SESSION['username'] == $sender_name) {
//add the receiver_name but only once
//so to do that check the user in array
if (in_array($receiver_name, $added_user)) {
//dont add receiver_name because
//he is already added
} else {
//add the receiver_name
$html_left_div .='<div class="grey-back first">
<img src="s.jpg" class="image"/>
' . $receiver_name . '';
$fetch_content = mysqli_query($con, "SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id` WHERE user_name = '$receiver_name'");
while ($row_fetch = mysqli_fetch_array($fetch_content)) {
$time = $row_fetch[5];
if ($time <= time()) {
$status ='<img src=\'r.png\' height=\'10\' width=\'10\' style=\'float:right\'>';
} else {
$status ='<img src=\'a.png\' height=\'10\' width=\'10\' style=\'float:right\'>';
}
}
$html_left_div .= $status.'</div>';
//as receiver_name added so
///add it to the array as well
$added_user = array($counter => $receiver_name);
//increment the counter
$counter++;
}
} elseif ($_SESSION['username'] == $receiver_name) {
//add the sender_name but only once
//so to do that check the user in array
if (in_array($sender_name, $added_user)) {
//dont add sender_name because
//he is already added
} else {
//add the sender_name
$html_left_div .='<div class="grey-back second">
<img src="s.jpg" class="image"/>
' . $sender_name . '';
$fetch_content = mysqli_query($con, "SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id` WHERE user_name = '$sender_name'");
while ($row_fetch = mysqli_fetch_array($fetch_content)) {
$time = $row_fetch[5];
if ($time <= time()) {
$status ='<img src=\'r.png\' height=\'10\' width=\'10\' style=\'float:right\'>';
} else {
$status ='<img src=\'a.png\' height=\'10\' width=\'10\' style=\'float:right\'>';
}
}
$html_left_div .= $status.'</div>';
//as sender_name added so
///add it to the array as well
$added_user = array($counter => $sender_name);
//increment the counter
$counter++;
}
}
}
} else {
//no message sent
echo 'no user';
}
} else {
//query problem
echo $q;
}
$html_left_div .='</div>';
echo $html_left_div;
Left-col.php code:
<?php
require 'connection.php';
session_start();
$user_name = $_SESSION['username'];
$user_id = $_SESSION['user_id'];
if (!isset($_SESSION['user_id'])) {
header("LOCATION: index.php");
} else {
$advance_time = time() + 15;
$query = mysqli_query($con, "SELECT * FROM status WHERE user_id='$user_id'");
if (mysqli_num_rows($query) > 0) {
mysqli_query($con, "UPDATE status SET status='$advance_time' WHERE user_id='$user_id'");
} else {
mysqli_query($con, "INSERT INTO status(user_id,status) VALUES ('$user_id','$advance_time')");
}
}
?>
<div id="left-col-container">
<div style="cursor:pointer" onclick="document.getElementById('new-message').style.display='block'" class="white-back">
<p align="center">New Message </p>
</div>
<?php
$q = 'SELECT DISTINCT `receiver_name`,`sender_name`,`date_time`
FROM `messages` WHERE
`sender_name`="' . $_SESSION['username'] . '" OR
`receiver_name`="' . $_SESSION['username'] . '"
ORDER BY `date_time` DESC';
$e = 'SELECT * from messages';
$r = mysqli_query($con, $q);
if ($r) {
if (mysqli_num_rows($r) > 0) {
$counter = 0;
$added_user = array();
while ($row = mysqli_fetch_assoc($r)) {
$sender_name = $row['sender_name'];
$receiver_name = $row['receiver_name'];
$timestamp = $row['date_time'];
if ($_SESSION['username'] == $sender_name) {
//add the receiver_name but only once
//so to do that check the user in array
if (in_array($receiver_name, $added_user)) {
//dont add receiver_name because
//he is already added
} else {
//add the receiver_name
?>
<div class="grey-back">
<img src="images/s.jpg" class="image"/>
<?php
echo '' . $receiver_name . '';
$fetch_content = mysqli_query($con, "SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id`");
while ($row_fetch = mysqli_fetch_array($fetch_content)) {
$time = $row_fetch[5];
if ($time <= time()) {
$status = "<img src='images/r.png' height='10' width='10' style='float:right'>";
} else {
$status = "<img src='images/a.png' height='10' width='10' style='float:right'>";
}
}
echo $status;
?>
</div>
<?php
//as receiver_name added so
///add it to the array as well
$added_user = array($counter => $receiver_name);
//increment the counter
$counter++;
}
} elseif ($_SESSION['username'] == $receiver_name) {
//add the sender_name but only once
//so to do that check the user in array
if (in_array($sender_name, $added_user)) {
//dont add sender_name because
//he is already added
} else {
//add the sender_name
?>
<div class="grey-back">
<img src="images/s.jpg" class="image"/>
<?php echo '' . $sender_name . '';
$fetch_content = mysqli_query($con, "SELECT * FROM users JOIN status ON `users`.`id`=`status`.`user_id`");
while ($row_fetch = mysqli_fetch_array($fetch_content)) {
$time = $row_fetch[5];
if ($time <= time()) {
$status = "<img src='images/r.png' height='10' width='10' style='float:right'>";
} else {
$status = "<img src='images/a.png' height='10' width='10' style='float:right'>";
}
}
echo $status;
?>
</div>
<?php
//as sender_name added so
///add it to the array as well
$added_user = array($counter => $sender_name);
//increment the counter
$counter++;
}
}
}
} else {
//no message sent
echo 'no user';
}
} else {
//query problem
echo $q;
}
?>
<!-- end of left-col-container -->
</div>
<script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<input type="hidden" value="<?php echo $user_id; ?>" id="from_user_id">
<script type="text/javascript">
setInterval(function(){updating_status()},5000);
function updating_status(){
let this_user = $('#from_user_id').val();
$.ajax({
method: "POST",
url: "updating.php",
data: {from_user:this_user},
success: function(response){
$('#left-col-container').html(response);
}
});
}
</script>

Change input background-image onclick

I have one page (resto presentation), and one blue img (like icon).
When I click like_icon, if the user never vote for this resto, I want:
- to increase the vote (saving into mysql database as integer);
- show the new value in the page (without refresh page);
- change the like icon (red icon, always clickable);
If the user already voted, on click icon:
- descrease the vote (update the resto table);
- show the new value in the page (without refresh page);
- change the like icon to blue img (always clickable).
This is what I have tried, but not works properly. What is wrong? And how can I do this?
Thank you.
HTML:
...
...
<?php include 'test.php'; ?>
<div id="idlike"><?php echo $idlike[0]; ?></div>
<label for="like">
<img id="likeimg" src="/img/like.png" style="cursor: pointer;" />
<script>
var x = document.getElementById("idlike").value;
if (x > 0) {
$("#likeimg").attr('src', '/img/dislike.png');
//document.getElementById("likeimg").innerHTML = <img scr="/img/dislike.png">;
}
else {
$("#likeimg").attr('src', '/img/like.png');
//document.getElementById("likeimg").innerHTML = <img scr="/img/like.png">;
}
</script>
</label>
<div id="likeimg"></div>
<form method="POST" action="resto-test.php?id=1">
<input type="submit" id="vote" name="vote" value="" style="display: none;" />
</form>
<script>
$("#likeimg").click(function(){
$("#vote").click();
});
</script>
...
...
test.php:
<?php
//date_default_timezone_set("Europe/Bucharest");
require('login/dbconfig.php');
session_start();
$login_session = $_SESSION['login_user'];
$idresto = 1;
$query = "SELECT id FROM users WHERE username = '$login_session'";
$result = mysqli_query($dbconfig, $query);
$iduser = mysqli_fetch_array($result);
//$query = "SELECT id FROM likes WHERE id_user = (SELECT id FROM users WHERE username = '$login_session')";
$query = "SELECT id FROM likes WHERE id_user = $iduser[0]";
$result = mysqli_query($dbconfig, $query);
$idlike = mysqli_fetch_array($result);
//echo "<div id='idlike'>";
//if ($idlike[0]) {
//echo $idlike[0];
//}
//else {
//echo "0";
//}
//echo "</div>";
$query = "SELECT COUNT(id_resto) FROM likes WHERE id_resto = $idresto";
$result = mysqli_query($dbconfig, $query);
$nrl = mysqli_fetch_array($result);
if (isset($_POST['vote'])) {
if (!$idlike[0]) {
//echo "<div id='likes'><img id='likeimg' src='/img/like.png'>";
//echo "<div id='likes'><img id='likeimg' src='/img/like.png'>";
$query = "INSERT INTO likes (id, id_user, id_resto, id_fel, id_gr) VALUES (default, $iduser[0], $idresto, 0, 0)";
$result = mysqli_query($dbconfig, $query);
$query = "UPDATE restos SET likes = ($nrl[0]+1) WHERE id = $idresto";
$result = mysqli_query($dbconfig, $query);
//echo "<span id='likenr'> " . ($nrl[0] + 1). "</span></div>";
echo "<span id='likenr'> " . ($nrl[0] + 1). "</span>";
$img = '/img/like.png';
}
else {
//echo "<div id='likes'><img id='likeimg' src='/img/dislike.png'>";
$query = "DELETE FROM likes WHERE id = $idlike[0]";
$result = mysqli_query($dbconfig, $query);
$query = "UPDATE restos SET likes = ($nrl[0]-1) WHERE id = $idresto";
$result = mysqli_query($dbconfig, $query);
//echo "<span id='likenr'> " . ($nrl[0] - 1). "</span></div>";
echo "<span id='likenr'> " . ($nrl[0] - 1). "</span>";
$img = '/img/dislike.png';
}
}
?>

php .session_start show errors on contact.php from submit.php

I need the errors on a form to show up from the submit.php onto the form page at contact.php
I have tried with Session_Start, but it is not working. This is what I have so far.
Contact.php
<?php
ob_start();
session_start();
if ($_SESSION["error"] != "") {
echo $_SESSION["error"];
$_SESSION["error"] = "";
}
?>
<?php echo $error; ?>
Submit.php
<?php
ob_start();
session_start();
?>
<?php
//fields
$link_address = 'contact'; // page to redirect to
$honeypot = '';
$error = '';
$name = 'Name';
$email = 'Email';
$comments = 'Message';
if(isset($_POST['contactus'])) {
$honeypot = $_POST['email_confirm'];
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
// honeypot
if($honeypot)
exit(1);
<?php
//error messages
if(trim($name) == 'Name') {
$error = '<div class="error_message">Need your Name</div>';
} else if(trim($name) == '') {
$error = '<div class="error_message">Need your Name</div>';
} else if(trim($email) == 'Email') {
$error = '<div class="error_message">Need your Email</div>';
} else if(trim($email) == '') {
$error = '<div class="error_message">Need your Email</div>';
} else if(!isEmail($email)) {
$error = '<div class="error_message">Need a valid email</div>';
} else if(trim($comments) == 'Message') {
$error = '<div class="error_message">A Message is required</div>';
} else if(trim($comments) == '') {
$error = '<div class="error_message">A Message is required</div>';
}
if($error == '') {
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
//email address
$address = "mail#example.com";
//email message
$e_subject = 'Web Message from: ' . $name . '.';
$e_body = "From: $name\nEmail: $email \r\n\nMessage:\n$comments\n\n\n";
$msg = $e_body . $e_content . $e_reply;
if(mail($address, $e_subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n"))
{
//success html page response
echo "<div id='succsess_page'>";
echo "<h1>Email Sent Successfully.</h1>";
echo "<p>Thank you. The following was sent to us. <br/><br/>$name<br/><br/>$email<br/><br/>$comments</p>";
echo "<a href='$link_address'>CLOSE THIS MESSAGE</a>";
echo "</div>";
} else echo "Error. Mail not sent";
}
}
if(!isset($_POST['contactus']) || $error != '') // Do not edit.
{
?>
<?php }
function isEmail($email) { // Email address verification, do not edit.
return(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,12})$/",$email));
}
?>
As you can see, the $error from the inputs required should show up when the user does not enter in their $name, etc on the contact.php page where it says:
<?php echo $error; ?>
How can I have the $error(s) from the submit.php code show up on the contact.php page if a user does not fill in the required input fields?
Try this as your Submit.php added $_SESSION['error'] = $error; //if $error is not empty. Also removed extra php tag
<?php
ob_start();
session_start();
//fields
$link_address = 'contact'; // page to redirect to
$honeypot = '';
$error = '';
$name = 'Name';
$email = 'Email';
$comments = 'Message';
if(isset($_POST['contactus'])) {
$honeypot = $_POST['email_confirm'];
$name = $_POST['name'];
$email = $_POST['email'];
$comments = $_POST['comments'];
// honeypot
if($honeypot)
exit(1);
//error messages
if(trim($name) == 'Name') {
$error = '<div class="error_message">Need your Name</div>';
} else if(trim($name) == '') {
$error = '<div class="error_message">Need your Name</div>';
} else if(trim($email) == 'Email') {
$error = '<div class="error_message">Need your Email</div>';
} else if(trim($email) == '') {
$error = '<div class="error_message">Need your Email</div>';
} else if(!isEmail($email)) {
$error = '<div class="error_message">Need a valid email</div>';
} else if(trim($comments) == 'Message') {
$error = '<div class="error_message">A Message is required</div>';
} else if(trim($comments) == '') {
$error = '<div class="error_message">A Message is required</div>';
}
if (isset($error) && !empty($error)){
$_SESSION['error'] = $error; //SET errors for contact.php page to display
echo $error;
}else {
$_SESSION['error'] = '';
if(get_magic_quotes_gpc()) {
$comments = stripslashes($comments);
}
//email address
$address = "mail#example.com";
//email message
$e_subject = 'Web Message from: ' . $name . '.';
$e_body = "From: $name\nEmail: $email \r\n\nMessage:\n$comments\n\n\n";
$msg = $e_body . $e_content . $e_reply;
if(mail($address, $e_subject, $msg, "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n"))
{
//success html page response
echo "<div id='succsess_page'>";
echo "<h1>Email Sent Successfully.</h1>";
echo "<p>Thank you. The following was sent to us. <br/><br/>$name<br/><br/>$email<br/><br/>$comments</p>";
echo "<a href='$link_address'>CLOSE THIS MESSAGE</a>";
echo "</div>";
} else echo "Error. Mail not sent";
}
}
if(!isset($_POST['contactus']) || $error != '') // Do not edit.
{
?>
<?php
}
function isEmail($email) { // Email address verification, do not edit.
return(preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,12})$/",$email));
}
?>

Categories