I'm trying to set a variable to a function that selects a table from a database. It has worked all the other times I have been using the function, but now I get this error message:
Notice: Undefined variable: post in C:\xampp\htdocs\blog\single.php on line 50
Now when I try to use another function that I have and set the same variable it doesn't work either. For some reason on this single.php page it will not recognize the function that I have in another file. The file where functions are lies included in posts.php, in a file called db.php, like this:
single.php :
<?php include('path.php');?>
<?php include('posts.php');
if (isset($_GET['id']))
{
$post = selectOne('posts', ['id' => $_GET['id']]);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
<!-- Custom Styles -->
<link rel="stylesheet" href="assets/css/style.css">
<title><?php echo $post['title'];?> </title>
</head>
<body>
<div id="fb-root"></div>
<!-- <script>
(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.src =
'https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v3.2&appId=285071545181837&autoLogAppEvents=1';
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
</script> -->
<!-- header -->
<?php include(ROOT_PATH . "/app/includes/header.php"); ?>
<!-- // header -->
<!-- Page wrapper -->
<div class="page-wrapper">
<!-- content -->
<div class="content clearfix">
<div class="page-content single">
<h2 style="text-align: center;"><?php echo $post['title']; ?></h2>
<br>
<?php echo html_entity_decode($post['body']); ?>
</div>
<div class="sidebar single">
<!-- fb page -->
<!-- // fb page -->
<!-- Popular Posts -->
<div class="section popular">
<h2>Popular</h2>
<div class="post clearfix">
<img src="images/image_1.png">
How to act inspite of your emotions
</div>
<div class="post clearfix">
<img src="images/image_2.png">
How to act inspite of your emotions
</div>
<div class="post clearfix">
<img src="images/image_3.png">
How to act inspite of your emotions
</div>
<div class="post clearfix">
<img src="images/image_4.png">
How to act inspite of your emotions
</div>
<div class="post clearfix">
<img src="images/image_5.png">
How to act inspite of your emotions
</div>
</div>
<!-- // Popular Posts -->
<!-- topics -->
<div class="section topics">
<h2>Topics</h2>
<ul>
<a href="#">
<li>Poems</li>
</a>
<a href="#">
<li>Quotes</li>
</a>
<a href="#">
<li>Fiction</li>
</a>
<a href="#">
<li>Biography</li>
</a>
<a href="#">
<li>Motivation</li>
</a>
<a href="#">
<li>Inspiration</li>
</a>
<a href="#">
<li>Life Lessons</li>
</a>
<a href="#">
<li>Self Development</li>
</a>
</ul>
</div>
<!-- // topics -->
</div>
</div>
<!-- // content -->
</div>
<!-- // page wrapper -->
<!-- FOOTER -->
<?php include(ROOT_PATH . "/app/includes/footer.php"); ?>
<!-- // FOOTER -->
<!-- JQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Slick JS -->
<script type="text/javascript" src="//cdn.jsdelivr.net/npm/slick-carousel#1.8.1/slick/slick.min.js"></script>
<script src="assets/js/script.js"></script>
</body>
</html>
posts.php:
<?php
include("app/database/db.php");
include("app/helpers/validatePost.php");
$table = 'posts';
$topics = selectAll('topics');
$posts = selectAll($table);
$errors = array();
$title = "";
$id = "";
$body = "";
$topic_id = "";
$published ="";
if (isset($_GET['id'])){
$post = selectOne($table, ['id' => $_GET['id']]);
$id = $post['id'];
$title = $post['title'];
$body = $post['body'];
$topic_id = $post['topic_id'];
$published = $post['published'];
}
if (isset($_GET['delete_id'])){
$count = delete($table, $_GET['delete_id']);
$_SESSION['message'] = "Post deleted succefully";
$_SESSION['type'] = "success";
header("location: " . BASE_URL . "/admin/posts/index.php");
exit();
}
if(isset($_GET['published']) && isset($_GET['p_id'])){
$published = $_GET['published'];
$p_id = $_GET['p_id'];
$count = update($table, $p_id, ['published' => $published]);
$_SESSION['message'] = "Post published state changed";
$_SESSION['type'] = "success";
header("location: " . BASE_URL . "/admin/posts/index.php");
exit();
}
if (isset($_POST['add-post'])){
$errors = validatePost($_POST);
if(!empty($_FILES['image']['name'])){
$image_name = time() . ' _ ' . $_FILES['image']['name'];
$destination = ROOT_PATH . "/assets/images/" . $image_name;
$result = move_uploaded_file($_FILES['image']['tmp_name'], $destination);
if ($result) {
$_POST ['image'] = $image_name;
} else{
array_push($errors, 'failed to upload image');
}
} else{
array_push($errors, "Post image required");
}
if(count($errors) == 0) {
unset($_POST['add-post']);
$_POST['user_id'] = $_SESSION['id'];
$_POST['published'] = isset($_POST['published']) ? 1 : 0;
$_POST['body'] = htmlentities($_POST['body']);
$post_id = create($table, $_POST);
$_SESSION['message'] = "Post created succefully";
$_SESSION['type'] = "success";
header("location: " . BASE_URL . "/admin/posts/index.php");
exit();
} else {
$title = $_POST['title'];
$body = $_POST['body'];
$topic_id = $_POST['topic_id'];
$published = isset($_POST['published']) ? 1 : 0;
}
}
if(isset($_POST['update-post'])){
$errors = validatePost($_POST);
if(!empty($_FILES['image']['name'])){
$image_name = time() . ' _ ' . $_FILES['image']['name'];
$destination = ROOT_PATH . "/assets/images/" . $image_name;
$result = move_uploaded_file($_FILES['image']['tmp_name'], $destination);
if ($result) {
$_POST ['image'] = $image_name;
} else{
array_push($errors, 'failed to upload image');
}
} else{
array_push($errors, "Post image required");
}
if(count($errors) == 0) {
$id = $_POST['id'];
unset($_POST['update-post'], $_POST['id']);
$_POST['user_id'] = $_SESSION['id'];
$_POST['published'] = isset($_POST['published']) ? 1 : 0;
$_POST['body'] = htmlentities($_POST['body']);
$post_id = update($table, $id, $_POST);
$_SESSION['message'] = "Post updated succefully";
$_SESSION['type'] = "success";
header("location: " . BASE_URL . "/admin/posts/index.php");
} else {
$title = $_POST['title'];
$body = $_POST['body'];
$topic_id = $_POST['topic_id'];
$published = isset($_POST['published']) ? 1 : 0;
}
}
db.php: (There are more functions, but i only included the two I tried to use with the variable $post.
function selectOne($table, $conditions)
{
global $conn;
$sql = "SELECT * FROM $table";
//return srecords that match conditions
$i = 0;
foreach($conditions as $key => $value) {
if ($i === 0){
$sql = $sql . " WHERE $key=?";
} else{
$sql = $sql . " AND $key=?";
}
$i++;
}
$sql = $sql . " LIMIT 1";
$stmt = executeQuery($sql, $conditions);
$records = $stmt->get_result()->fetch_assoc();
return $records;
}
function dd($value){
echo "<pre>", print_r($value, true), "</pre>";
die();
}
Related
What I am trying to do is setup a upvote/downvote system on my website using cookies (to try and allow anonymous users to participate). The issue I am running into is I have to set my cookies before my headers, and for some reason, whenever I click the upvote or downvote button, my navbar dissapears and then reappears. The index file is here:
<?php
include 'dbconnect.php';
include 'postbuttons.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>Announcments</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="stylesheet.php">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<?php include '../header.html'; ?>
</head>
<body>
<?php
include 'pagination.php';
include 'content.php';
?>
</body>
</html>
my dbconnect file is:
<?php
$db_host = 'localhost';
$db_name = 'databasename';
$db_user = 'databaseuser';
$db_pass = 'databasepassword';
$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_SESSION['user'])) {
$res = $conn->query("SELECT * FROM users WHERE id=" . $_SESSION['user']);
if ($res != false) {
$userRow = mysqli_fetch_array($res, MYSQLI_ASSOC);
}
}
?>
my post buttons page, which is where i think the problem is:
<?php
$posts = $conn->query("SELECT * FROM blog");
//$posts = mysqli_fetch_array($postsraw, MYSQLI_ASSOC);
foreach ($posts as $ind) {
setcookie('test'.$ind['id'], 'heck you');
$id = $ind['id'];
$postraw = $conn->query("SELECT * FROM blog WHERE id=$id");
$post = mysqli_fetch_array($postraw, MYSQLI_ASSOC);
if (isset($_POST['vote'.$id])) {
$postcookie = 'vote' . $id;
if (isset($_COOKIE[$postcookie])) {
$data = json_decode($_COOKIE[$postcookie]);
} else {
$data = ['neither', '#aaa'];
}
if ($_POST['votetype'.$id] == 'up') {
if (!isset($_COOKIE[$postcookie]) || $data[0] == 'neither' ||
$data[0] == 'down') {
if ($data[0] == 'down') {
$change = $post['upvote'] + 1;
$sql = "UPDATE blog SET upvote=$change WHERE id=$id";
$query = $conn->query($sql);
$changedown = $post['downvote'] - 1;
$othersql = "UPDATE blog SET downvote=$changedown WHERE id=$id";
$newquery = $conn->query($othersql);
} else {
$change = $post['upvote'] + 1;
$sql = "UPDATE blog SET upvote=$change WHERE id=$id";
$query = $conn->query($sql);
}
$cookievalue = ['up', 'green'];
setcookie($postcookie, json_encode($cookievalue));
} else {
$change = $post['upvote'] - 1;
$sql = "UPDATE blog SET upvote=$change WHERE id=$id";
$query = $conn->query($sql);
$cookievalue = ['neither', '#aaa'];
setcookie($postcookie, json_encode($cookievalue));
}
}
if ($_POST['votetype'.$id] == 'down') {
if (!isset($_COOKIE[$postcookie]) || $data[0] == 'neither' ||
$data[0] == 'up') {
if ($data[0] == 'up') {
$change = $post['downvote'] + 1;
$sql = "UPDATE blog SET downvote=$change WHERE id=$id";
$query = $conn->query($sql);
$changedown = $post['upvote'] - 1;
$othersql = "UPDATE blog SET upvote=$changedown WHERE
id=$id";
$newquery = $conn->query($othersql);
} else {
$change = $post['downvote'] + 1;
$sql = "UPDATE blog SET downvote=$change WHERE id=$id";
$query = $conn->query($sql);
}
$cookievalue = ['down', 'red'];
setcookie($postcookie, json_encode($cookievalue));
} else {
$change = $post['downvote'] - 1;
$sql = "UPDATE blog SET downvote=$change WHERE id=$id";
$query = $conn->query($sql);
$cookievalue = ['neither', '#aaa'];
setcookie($postcookie, json_encode($cookievalue));
}
}
echo '<meta http-equiv="Refresh" content="0; url=#'.$id.'">';
}
if(isset($_POST['report'.$id])) {
if(isset($_COOKIE['report'.$id])) {
$cdata = json_decode($_COOKIE['report'.$id]);
} else {
$cdata = ['notset', 'black'];
}
if ($cdata[0] == 'notset') {
$reportval = ['reported', 'red'];
setcookie('report'.$id, json_encode($reportval));
$change = $post['reports'] + 1;
$sql = $conn->query("UPDATE blog SET reports=$change WHERE id=$id");
} else {
$reportval = ['notset', 'black'];
setcookie('report'.$id, json_encode($reportval));
$change = $post['reports'] - 1;
$sql = $conn->query("UPDATE blog SET reports=$change WHERE id=$id");
}
echo '<meta http-equiv="Refresh" content="0; url=#'.$id.'">';
}
}
?>
and if it helps, this is my content.php page:
<div class="container-fluid text-center">
<button type="button" class="btn btn-primary float-right" data-
toggle="modal"
data-target="#announcmentm">
Add
</button><h1>Announcments:</h1>
</div>
<div class="modal fade" id="announcmentm" tabindex="-1" role="dialog" aria-
hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Add Announcment</h5>
<button type="button" class="close" data-dismiss="modal" aria-
label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<?php include 'create.php' ?>
</div>
</div>
</div>
</div>
<?php
$sql = $conn->query("SELECT id FROM blog");
$pager = new Paginater();
$pager->paginate('blog', 5, $id);
?>
and finally my header.html page:
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="#">STUCO</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="/">Home</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/suggestions.html">Suggestions</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/tasks">Tasks</a>
</li>
<li class="nav-item">
<a class="nav-link" href="/blog">Blog</a>
</li>
</ul>
</div>
you can see the problem I am describing here: https://stuco.baccaw.host/blog
just try and upvote one of the articles and you will see the navbar dissapear for a bit, then come back.
Why my $_SESSION["products"] has been destroy after logged in, How do I keep my $_SESSION["products"] after I logged in?
Add product to cart before logged in.
After logged in my cart is empty.
CODE
login.php
<?php
ob_start();
session_start();
include 'init.php';
require_once 'config.php';
//initalize user class
$user_obj = new Cl_User();
if(!empty( $_POST )){
try {
$user_obj = new Cl_User();
$data = $user_obj->login( $_POST );
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']){
header('Location: home.php');
}
} catch (Exception $e) {
$error = $e->getMessage();
}
}
if(isset($_SESSION['logged_in']) && $_SESSION['logged_in']){
header('Location: home.php');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Smart Login Page</title>
<link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="css/login.css" rel="stylesheet">
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<?php require_once 'templates/ads.php';?>
<div class="login-form">
<?php require_once 'templates/message.php';?>
<h1 class="text-center">Login</h1>
<div class="form-header">
<i class="fa fa-user"></i>
</div>
<form id="login-form" method="post" class="form-signin" role="form" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input name="email" id="email" type="email" class="form-control" placeholder="Email" autofocus>
<input name="password" id="password" type="password" class="form-control" placeholder="Password">
<button class="btn btn-block bt-login" type="submit" id="submit_btn" data-loading-text="loging in....">Login</button>
<br>
</form>
<div class="form-footer">
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<i class="fa fa-lock"></i>
Forgot Password?
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<i class="fa fa-check"></i>
Sign up
</div>
</div>
</div>
</div>
</div>
<!-- /container -->
<script src="js/jquery.validate.min.js"></script>
<script src="js/login.js"></script>
</body>
</html>
<?php ob_end_flush(); ?>
login function in User.php
public function login( array $data )
{
$_SESSION['logged_in'] = false;
if( !empty( $data ) ){
// Trim all the incoming data:
$trimmed_data = array_map('trim', $data);
// escape variables for security
$email = mysqli_real_escape_string( $this->_con, $trimmed_data['email'] );
$password = mysqli_real_escape_string( $this->_con, $trimmed_data['password'] );
if((!$email) || (!$password) ) {
throw new Exception( LOGIN_FIELDS_MISSING );
}
$password = md5( $password );
$query = "SELECT member_id, member_display_name, member_email, member_status, roles_id FROM fm_member where member_email = '$email' and member_pwd = '$password' ";
//$query = "SELECT user_id, name, email, created, roles_id, id FROM users where email = '$email' and password = '$password'"
$result = mysqli_query($this->_con, $query);
$data = mysqli_fetch_assoc($result);
$count = mysqli_num_rows($result);
mysqli_close($this->_con);
if( $count == 1){
$_SESSION = $data;
if($_SESSION['member_status'] == 'Activated') {
$_SESSION['logged_in'] = true;
return true;
} else {
throw new Exception( 'Your account is Deactiavted! <br> Please contact to Adminnistrator for more information.' );
$_SESSION['logged_in'] = false;
}
}else{
throw new Exception( LOGIN_FAIL );
}
} else{
throw new Exception( LOGIN_FIELDS_MISSING );
}
}
cart_process.php
session_start(); //start session
include_once("config.inc.php"); //include config file
setlocale(LC_MONETARY,"en_US"); // US national format (see : http://php.net/money_format)
############# add products to session #########################
if(isset($_POST["product_code"]))
{
foreach($_POST as $key => $value){
$new_product[$key] = filter_var($value, FILTER_SANITIZE_STRING); //create a new product array
}
//we need to get product name and price from database.
$statement = $mysqli_conn->prepare("SELECT fm_product.p_name, fm_product.p_price, fm_product.p_member_id, fm_product.p_discount, fm_member.member_display_name, fm_member.member_payment, fm_product_image.img_1, shipping_cost.shipping_register,
shipping_cost.shipping_normal, shipping_cost.shipping_ems FROM fm_product LEFT JOIN fm_member ON fm_member.member_id = fm_product.p_member_id LEFT JOIN fm_product_image ON fm_product_image.p_id_img = fm_product.p_id LEFT JOIN shipping_cost ON shipping_cost.shipping_vendor = fm_member.member_id WHERE p_id=?");
$statement->bind_param('s', $new_product['product_code']);
$statement->execute();
$statement->bind_result($product_name, $product_price, $p_member_id, $p_discount, $member_display_name, $member_payment, $img_1, $shipping_register, $shipping_normal,$shipping_ems);
while($statement->fetch()){
$new_product["p_name"] = $product_name; //fetch product name from database
$new_product["p_price"] = $product_price;
$new_product["p_member_id"] = $p_member_id;
$new_product["p_discount"] = $p_discount;
$new_product["member_display_name"] = $member_display_name;
$new_product["member_payment"] = $member_payment;
$new_product["img_1"] = $img_1;
$new_product["shipping_register"] = $shipping_register;
$new_product["shipping_normal"] = $shipping_normal;
$new_product["shipping_ems"] = $shipping_ems;
//fetch product price from database
if(isset($_SESSION["products"])){ //if session var already exist
if(isset($_SESSION["products"][$new_product['product_code']])) //check item exist in products array
{
unset($_SESSION["products"][$new_product['product_code']]); //unset old item
}
}
$_SESSION["products"][$new_product['product_code']] = $new_product; //update products with new item array
}
$total_items = count($_SESSION["products"]); //count total items
die(json_encode(array('items'=>$total_items))); //output json
}
################## list products in cart ###################
if(isset($_POST["load_cart"]) && $_POST["load_cart"]==1)
{
if(isset($_SESSION["products"]) && count($_SESSION["products"])>0){ //if we have session variable
$cart_box = '<ul class="cart-products-loaded">';
$total = 0;
foreach($_SESSION["products"] as $product){ //loop though items and prepare html content
//set variables to use them in HTML content below
$product_name = $product["p_name"];
if(!empty($product["p_discount"]))
{
$product_price = $product["p_discount"];
} else if(empty($product["p_discount"])) {
$product_price = $product["p_price"];
}
$product_code = $product["product_code"];
$p_member_id = $product["p_member_id"];
$member_display_name = $product["member_display_name"];
$member_payment = $product["member_payment"];
$product["product_qty"] = 1;
$product_qty = $product["product_qty"];
$cart_box .= "<li>$product_name — Price ".$product_price." x ".$product_qty." = ".sprintf($product_qty * $product_price)."×</li>";
$subtotal = ($product_price * $product_qty);
$total = ($total + $subtotal);
}
$cart_box .= "</ul>";
$cart_box .= '<div class="cart-products-total" style="border-top: 1px solid #C0C0C0;">'.$quantity.'Total : '.sprintf($total).'<u>Check Out</u></div>';
die($cart_box); //exit and output content
}else{
die("Empty Cart!"); //we have empty cart
}
}
EDIT
home.php added
<?php
session_start();
include('connect.php');
$ID = $_SESSION['member_id'];
if(!isset($_SESSION['logged_in'])){
header('Location: index.php');
}
?>
<?php require_once 'templates/header.php';?>
<?php if($_SESSION['roles_id']=='1') { ?>
<div class="content">
<div class="container">
<div class="col-md-8 col-sm-8 col-xs-12">
<br>
<h1 class="text-center"> Admin Page </h1>
<br>
</div>
<?php require_once 'templates/sidebar.php';?>
</div>
</div> <!-- /container -->
<?php } else if($_SESSION['roles_id']=='2') { ?>
<div class="content">
<div class="container">
<div class="col-md-8 col-sm-8 col-xs-12">
<br>
<h1 class="text-center"> User Page </h1>
<br>
</div>
<?php require_once 'templates/sidebar.php';?>
</div>
</div> <!-- /container -->
<?php } ?>
looks like $_SESSION = $data; may be your culprit, you're resetting the entire session variable with data.
EDIT
Where $_SESSION = $data is change it to this;
$data["products"] = $_SESSION["products"];
$_SESSION = $data;
I am making a medical related site in php. When a patient logged in and he did not post any thing but he refreshes the page the query retrieve the old records again which is already inserted kindly help
This is my code for
Patient_dashboard.php
<?php
session_start();
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$ufn = "";
$uln = "";
$q2 = "";
$post="";
$query;
$query2="";
$connection = mysqli_connect($dbhost, $dbuser, $dbpass);
if(! $connection )
{
die('Could not connect: ' . mysql_error());
}
$database = mysqli_select_db($connection,"medical_network");
if (!$database) {
die("Database selection failed: " . mysql_error());
}
if(!isset($_SESSION['username'])) {
header('Location: index.php');
}
require_once("Functions/functions.php");
$posts = get_user_posts($_SESSION['id']);
$uploadDir = 'Reports Images/'; //Image Upload Folder
if(isset($_POST['submit'])&& !empty($_POST['submit'])){
$fileName = $_FILES['image']['name'];
$tmpName = $_FILES['image']['tmp_name'];
$fileSize = $_FILES['image']['size'];
$fileType = $_FILES['image']['type'];
$filePath = $uploadDir . $fileName;
$filename = $fileName;
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$date = date_create();
$fileName= date_timestamp_get($date).".".$ext;
$filePath = $uploadDir . $fileName;
$result = move_uploaded_file($tmpName, $filePath);
if(!get_magic_quotes_gpc())
{
$fileName = addslashes($fileName);
$filePath = addslashes($filePath);
}
$post = mysqli_real_escape_string($connection,($_POST['np_text']));
//$date = date("Y/m/d");
date_default_timezone_set('Asia/Karachi');
$date = date('Y-m-d H:i:s');
//echo $date;
$query = "INSERT INTO post ";
$query .= "(p_pic,p_content,p_date,u_id) VALUES (";
$query .= "'{$filePath}','{$post}','{$date}','{$_SESSION['id']}');";
//echo $query . " " .$date;
$result_set = mysqli_query($connection,$query);
if (!$result_set) {
die("Database query failed: " . mysqli_error($connection));
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Medical Network</title>
<link href="css/custom.css" rel="stylesheet" />
<script>
function performClick(node) {
var evt = document.createEvent("MouseEvents");
evt.initEvent("click", true, false);
node.dispatchEvent(evt);
}
</script>
</head>
<body>
<div class="topmenu">
<div class="search">
<form>
<input type="text" placeholder="Search" value="">
</form>
</div>
<div id='cssmenu'>
<ul>
<li><a href='#'><span>Home</span></a></li>
<li><a href='#'><span>Profile</span></a></li>
<li><a href='logout.php'><span>Logout</span></a></li>
</ul>
</div>
</div>
<div class="main">
<div class="left-colum">
<div class="profileinfo">
<div class="profilepic">
<?php echo "<img class='getPic' src='{$_SESSION['pic']}' />" ?>
</div>
<div class="personal-info">
<ul>
<li><a href='#'><span><?php echo $_SESSION['fname']." ".$_SESSION['lname']; ?></span></a></li>
<li><a href='#'><span>Edit Profile</span></a></li>
</ul>
</div>
</div>
<div class="importantlinks">
<h4>Important Links</h4>
<ul>
<li><a href='#'><span>Make Appointment</span></a></li>
<li><a href='#'><span>Search Doctor</span></a></li>
<li><a href='logout.php'><span>Logout</span></a></li>
</ul>
</div>
<div class="pages">
<h4>Pages</h4>
</div>
</div>
<div class="middle-colum">
<div id="feeds">
<div class="new-post">
<ul>
<form method="post" action="patient-dashboard.php" enctype="multipart/form-data">
<li><label for="newpostfield"><img src="images/status.png" width="14" height="14"> Update Status</label></li>
<li> <img src="images/photo.png" width="14" height="14"> Add Photo
</li>
<input type="file" id="myFile" name="image" size="4
000000" accept="image/gif, image/jpeg, image/x-ms-bmp, image/x-png" />
</ul>
<br />
<textarea rows="1" cols="40" id="newpostfield" name="np_text" placeholder="Whats on your mind ?" required="required" ></textarea>
<input type="submit" value="Post" name="submit" id="postbtn"/>
</form>
</div><!--End of feed-item -->
<br />
<div class="posts-feed">
<h3 id="postsheading" class="post-heading">Posts</h3>
<?php while($post = mysqli_fetch_array($posts)){
$counter = 0;
?>
<div class="post">
<div class="poster-pic">
<?php echo "<img src='{$_SESSION['pic']}' height='60' width='60' />" ?>
</div><!--End of poster-pic -->
<div class="post-content">
<div id="poster-name"><?php echo $_SESSION['fname']." ".$_SESSION['lname']; ?><span></span></div>
<div id="content">
<p id="post-text">
<?php
echo $post['p_content']."<br/>";
$img = $post['p_pic'];
echo "<a href='#'> <img src='{$post['p_pic']}' height='300' width='300' >"
?>
</p>
</div><br />
<div id="post-responses" class="top-border">
Comment
</div>
</div><!--End of post-content -->
</div><!--End of post -->
<?php $counter++;
} ?>
</div><!--End of feeds -->
</div>
<div class="right-colum">
<div class="heading">
<h4>Recommended Pages</h4>
</div>
</div>
</body>
</html>
This is function.php where i am retrieving the records.
<?php
function get_user_posts($id) {
global $connection;
$query2 = "SELECT p_pic, p_content,u_id ";
$query2 .= "FROM post ";
$query2 .= "WHERE u_id= " . $id ." ";
$query2 .= "ORDER BY p_id DESC ";
$query2 .= "LIMIT 5";
$result_set1 = mysqli_query( $connection,$query2);
if (!$result_set1) {
die("Database query failed: " . mysqli_error($connection));
}
// REMEMBER:
// if no rows are returned, fetch_array will return false
if ($result_set1) {
return $result_set1;
} else {
return NULL;
die("query faild..... in get post");
}
}
?>
You are calling $posts = get_user_posts($_SESSION['id']); outside the if statement so it is showing the records as on every reload it is fetching the data. if you want to display the records only if it is posted then put it inside the if statement
if(isset($_POST['submit'])&& !empty($_POST['submit'])){
//your code
$posts = get_user_posts($_SESSION['id']);
}
and please do check the if the variables are available or not.
Please change input name attribute
it should be:
use any name Except submit
also change
if(isset($_POST['submit'])&& !empty($_POST['submit'])){
i'm getting the following error.
i cant figure it out what is wrong with this code.
there is something that i missed or forget.
can anybody please help me? i'm stuck at the moment.
he keeps saying there something with the array.
Notice: Undefined property: Cms::$contant_types in C:\xampp\htdocs\PassieCMS\app\cms\models\m_cms.php on line 34
Warning: in_array() expects parameter 2 to be array, null given in C:\xampp\htdocs\PassieCMS\app\cms\models\m_cms.php on line 34
<?php
/*
CMS Class
Handle CMS task, allowing admins to view/edit content
*/
class Cms
{
private $content_types = array('wysiwyg', 'textarea', 'oneline');
private $FP;
function __construct()
{
global $FP;
$this->FP = &$FP;
}
function clean_block_id($id)
{
$id = str_replace(' ', '_', $id);
$id = str_replace('-', '_', $id);
$id = preg_replace("/[^a-zA-Z0-9_]/", '',$id);
return strtolower($id);
}
function display_block($id, $type = 'wysiwyg')
{
// clean id
$id = $this->clean_block_id($id);
// check for valid type
$type = strtolower(htmlentities($type, ENT_QUOTES));
if (in_array($type, $this->contant_types) == FALSE)
{
echo "<script>alert('Please enter a valid block type for \'" . $id . "\'');</script>";
return;
}
// get content
$content = "content here...";
// check login status
if ($this->FP->Auth-checkLoginStatus())
{
if($type == 'wysiwyg') { $type2 = 'WYSIWYG';}
if($type == 'textarea') { $type2 = 'Textarea';}
if($type == 'oneline') { $type2 = 'One Line';}
$edit_start = '<div class=""fp_edit>';
$edit_type = '<a class="fp_edit_type" href="' . SITE_PATH .'app/cms/edit.php?id' . $id . '&type='. $type . '">' . $type2 . '</a>';
$edit_link = '<a class="fp_edit_link" href="' . SITE_PATH .'app/cms/edit.php?id' . $id . '&type='. $type . '">Bewerken</a>';
$edit_end = '</div>';
echo $edit_start . $edit_type;
echo $edit_link . $content . $edit_end;
}
else
{
echo $content;
}
}
}
and the index file is
<?php include ("app/init.php");?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>PassieCMS</title>
<link href="resources/css/style.css" rel="stylesheet" type="text/css">
<?php $FP->head(); ?>
</head>
<body class="home <?php $FP->body_class(); ?>">
<?php $FP->toolbar(); ?>
<div id="wrapper">
<h1>Website</h1>
<div id="banner">
<img src="resources/images/banner.jpg" alt="banner" width="900" height="140">
</div>
<ul id="nav">
<li>Home</li>
<li>Test link</li>
<li>Longer Text Link</li>
<li>Contact us</li>
</ul>
<div id="content">
<div class="left">
<h2><?php $FP->Cms->display_block('content-header','oneline'); ?></h2>
<?php $FP->Cms->display_block('content-maincontent'); ?>
</div>
<div class="right">
<?php $FP->Cms->display_block('content-quote'); ?>
<?php $FP->Cms->display_block('content-attribution'); ?>
</div>
</div>
<div id="footer">
Copyright 2014 PassieCMS | <?php $FP->login_link();?> Login optie 2
</div>
</div>
</body>
</html>
Thank you all for your time
if (in_array($type, $this->contant_types) == FALSE)
You have a typo, you have declared it as content_types above. This should work:
if (in_array($type, $this->content_types) == FALSE)
I am continuosly getting this error:
Commands out of sync; you can't run this command now
I don't know why is this happening and none of the preivous questions are helping.
This is my code:
User.php
public static function GetUserFullName($username){
if(Utilities::IsValid($username)){
$username = Utilities::SafeString($username);
Database::OpenConnection();
$query = Database::$databaseConnection->prepare("SELECT Name FROM user WHERE Username = ?") or die(Database::$databaseConnection->error);
$query->bind_param("s", $username);
$result = $query->execute();
Database::CloseConnection();
if($result){
$query->bind_result($name);
$query->fetch();
$query->close();
return $name;
}
}else return -1;
}
Skill.php
public static function UpdateSkills($id, $skill, $action){
if(Utilities::IsValid($id) && Utilities::IsValid($skill) && Utilities::IsValid($action)){
$id = Utilities::SafeString($id);
$skill = Utilities::SafeString($skill);
$action = Utilities::SafeString($action);
Database::OpenConnection();
if($action == 'i'){
$skill = str_replace(" ", "", $skill);
$db = Database::$databaseConnection;
$skills = explode(",", $skill);
$query = "";
foreach ($skills as $s){
$query .= "INSERT INTO skill (User_ID,Skill) VALUES({$id},'{$s}');";
}
$result = $db->multi_query($query);
echo $db->error;
Database::CloseConnection();
if($result) return 1;
else return -1;
}else if($action == 'd'){
$query = Database::$databaseConnection->prepare("DELETE FROM Skill WHERE Skill = ? AND User_ID = ?");
$query->bind_param("si", $skill,$id);
$result = $query->execute();
Database::CloseConnection();
if($result && $query->num_rows >0) return 1;
else return -1;
}
}
return -1;
}
header.php
<?php
require_once 'Classes/UserLogin.php';
require_once 'Classes/User.php';
$user_fullname = User::GetUserFullName($_SESSION["username"]);
?>
<header>
<div class="welcome_area">
<p>
Welcome, <b><?php echo $user_fullname; ?> </b>
</p>
</div>
<div class="menu">
<nav>
<ul>
<li>My Profile
<ul>
<li><div>My Questions</div>
</li>
<li><div>Settings</div>
</li>
<li style="margin-bottom: 5px;"><div>Logout</div>
</li>
</ul>
</li>
<li>Inbox
</li>
<li>Notifications
</li>
</ul>
</nav>
</div>
</header>
<section id="container">
<br />
<div id="logo"></div>
<div id="content">
profile.php
<?php
require_once "Classes/User.php";
require_once "Classes/Skill.php";
require_once "Classes/UserLogin.php";
if(!UserLogin::IsLoggedIn("username")) header("location: login.php");
$user_details = User::GetUserDetails($_SESSION["username"]);
echo Skill::UpdateSkills(11, "programmer,designer", "i");
?>
<!DOCTYPE html>
<html>
<head>
<title>Help Exchange</title>
<link rel="stylesheet" href="css/base.css" />
<link rel="stylesheet" href="css/profile.css" />
<link rel="stylesheet" href="css/user.css" />
<link rel="stylesheet" href="css/widgets.css" />
<script src="js/jquery.min.js"></script>
<script src="js/profile.js"></script>
</head>
<body>
<script>
var user_details = eval(<?php echo $user_details; ?>);
var about = user_details.About;
</script>
<?php require_once 'admin/header.php';?>
Please help me :'(