Setting cookies without navbar dissapearing - php

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.

Related

php page won't recognize a function included in another file

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();
}

How to allow only session user to modify review php sql?

This is code for user review system, Everything is working fine with this code but i want to allow only those user to modify their reviews who are on session (logged in) so i just want to add if($_SESSION['id']==$row['user_id']) then open modify page or else echo"Access Denied"; i have tried this code but its not fetching session_id & also i am not sure where should i place this code because i will also block edit page please help anyone..i m stucked
edit page is that page where user can add review
modify page is that page where user can update edit already added review
reviews.php
<?php
session_start();
include('server3.php');
include('config.php');
if (isset($_GET['edit'])) {
$id = $_GET['edit'];
$record = mysqli_query($db, "SELECT * FROM info WHERE user_id=$id");
if (count($record) == 1 ) {
$nm = mysqli_fetch_array($record);
$name = $nm['name'];
$address = $nm['address'];
$yid= $nm['id'];
}
}
if (isset($_GET['modify'])) {
$update = true;
$id = $_GET['modify'];
$record2 = mysqli_query($db, "SELECT * FROM info WHERE id=$id");
if (count($record2) == 1 ) {
$n = mysqli_fetch_array($record2);
$name = $n['name'];
$address = $n['address'];
}
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" type="text/css" href="somecss.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="NAV/jquery.min.js"></script>
<script src="NAV/bootstrap.min.js"></script>
</head>
<body>
<header id="fixed-header">
<center><img id="logo" src="logo.png" height="82" width="350" style="border-radius:8px; margin-top:-100px;"/></center>
</header>
<nav class="navbar navbar-inverse" style="margin-bottom:0px;" >
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">NearestMentor.Com</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>What's This</li>
<li>How to Use</li>
<li>Contribute & Win</li>
<li>Winner Mentors Leatherboard</li>
<li>Terms</li>
<li>About Us</li>
<li>Donate Us</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<?php
$loggedin = isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true;
if($loggedin) : ?>
<li><span class="glyphicon glyphicon-pencil"> </span>My Q & A</li>
<li><span class="glyphicon glyphicon-user"> </span>Edit Profile</li>
<li><span class="glyphicon glyphicon-log-in"> </span>Logout</li>
<?php else : ?>
<li><span class="glyphicon glyphicon-user"></span> Sign Up</li>
<li><span class="glyphicon glyphicon-log-in"></span> Login</li>
<?php endif; ?>
</ul>
</div>
</div>
</nav>
<?php if (isset($_SESSION['message'])): ?>
<div class="msg">
<?php
echo $_SESSION['message'];
unset($_SESSION['message']);
?>
</div>
<?php endif ?>
<?php $results = mysqli_query($db, "SELECT * FROM info WHERE user_id=$id"); ?>
<table>
<thead>
<tr>
<th>Name</th>
<th>Review</th>
<th colspan="2">Action</th>
</tr>
</thead>
<?php while ($row = mysqli_fetch_array($results)) { ?>
<tr>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['address']; ?></td>
<td>
<?php
if($row['user_id']==$_SESSION['id'])
{
echo "<a href='review.php?modify=".$row['id'];"class='edit_btn' >Edit</a>";
}
else
{
echo "";
}
?>
</td>
<td>
Delete
</td>
</tr>
<?php } ?>
</table>
<form method="post" action="server3.php" >
<input type="hidden" name="id" value="<?php echo $id; ?>">
<div class="input-group">
<label>USERID</label>
<input type="text" name="user_id" style="width:670px; height:40px;" value=
"<?php echo $id;?>"
</div>
<div class="input-group">
<label>Name</label>
<input type="text" name="name" style="width:670px; height:40px;" value='<?php echo $_SESSION['username'] ?>' readonly="readonly">
</div>
<div class="input-group">
<label>Give Your Review</label>
<input type="text" name="address" style="width:670px;" value="<?php echo $address; ?>">
</div>
<div class="input-group">
<?php if($update=='true')
{
echo '<button class="btn" type="submit" name="update" style="background: #556B2F;" >update</button>';
}
else
{
echo '<button class="btn" type="submit" name="save" >Save</button>';
} ?>
</div>
</form>
</body>
</html>
server3.php
<?php
session_start();
$db = mysqli_connect('localhost', 'root', '', 'mydatabase');
// initialize variables
$name = "";
$address = "";
$id = 0;
$update = false;
if (isset($_POST['save'])) {
$user_id = $_POST['user_id'];
$name = $_POST['name'];
$address = $_POST['address'];
mysqli_query($db, "INSERT INTO info (user_id, name, address) VALUES ('$user_id','$name', '$address')");
$_SESSION['message'] = "Review Saved, Thankyou!";
header('location: review.php?edit='.$user_id);
}
if (isset($_POST['update'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$address = $_POST['address'];
mysqli_query($db, "UPDATE info SET name='$name', address='$address' WHERE id=$id");
$_SESSION['message'] = "Review Updated, Thankyou!";
echo("<script>alert('Review Successfully Updated!')</script>");
echo("<script>window.location = 'index.php';</script>");
}
if (isset($_GET['del'])) {
$id = $_GET['del'];
mysqli_query($db, "DELETE FROM info WHERE id=$id");
$_SESSION['message'] = "Review Deleted, Thankyou!";
echo("<script>alert('Review Successfully Deleted!')</script>");
echo("<script>window.location = 'index.php';</script>");
}
$results = mysqli_query($db, "SELECT * FROM info");
?>
Why not just use an OAuth login like google to create the user and then use that login to authenticate whether the user can edit a review? It makes it easier for users to create an account, which means you are more likely to get those reviews AND you can check if they are actual customers by implementing a system where they can order online and then do a check if they actually buy from you and verify them as a purchaser. Possibly hide reviews that are spam or non-customer reviews.
I was looking at server3.php and you need to do a lot of checks. This code is vulnerable to MySQL Injections and can easily store garbage data into your database server. I recommend using PDO and prepared queries. I also recommend you check for valid email and escape all data input from the user. Right now I hope this is not on a single live website.

After sending a search query page become blank

I am working on a little search engine in PHP & MySQL. Yesterday, I restyled (I did changes only at the HTML part, no php code was touched) the result page, after that I was unable to search for a term.
New code:
<?php
header( 'Cache-Control: no-store, no-cache, must-revalidate' );
header( 'Cache-Control: post-check=0, pre-check=0', false );
header( 'Pragma: no-cache' );
require_once("lucene.php");
?>
<?php
$row1 = [];
$row2 = [];
$search_word = false;
if(isset($_POST["submit"])) {
//edit this with your credentials
$con = mysqli_connect("localhost", "root", "pass", "db");
if(mysqli_connect_error()) echo "Connection Fail";
else {
$search_word = true;
$input = $_POST["s_input"];
// tokenize input
$tokens = tokenize($input);
//compute weight of every token
$token_weight = compute_weight($tokens, $con);
$sql1 = "SELECT *, match(description) against('". $input ."') as score FROM web where match(description) against('".$input."') order by score desc";
$sql2 = "SELECT *, match(description) against('". $input ."') as score FROM web where match(description) against('".$input."') order by score desc";
$result1 = mysqli_query($con, $sql1);
$result2 = mysqli_query($con, $sql2);
$sql3 = "SELECT * FROM web";
$numDocs = (mysqli_num_rows(mysqli_query($con, $sql3)));
$maxOverlap = sizeof($tokens);
$ctr2 = 0;
while($ctr2 != $maxOverlap){
//compute inverse_document_frequency of term
$sql3 = "SELECT *, match(description) against('".$tokens[$ctr2]."') FROM web where match(description) against('".$tokens[$ctr2]."')";
$docFreq = (mysqli_num_rows(mysqli_query($con, $sql3)));
$idf[$tokens[$ctr2]] = idf($numDocs, $docFreq);
$ctr2++;
}
$ctr = 0;
while($r1 = mysqli_fetch_array($result1)){
$row1[$ctr]['ID'] = $r1['ID'];
$row1[$ctr]['title'] = $r1['title'];
$row1[$ctr]['description'] = highlight_words($r1['description'], $tokens);
$row1[$ctr]['credit'] = $r1['credit'];
$row1[$ctr]['url'] = $r1['url'];
$document = strtolower($row1[$ctr]['description']);
$ctr2 = 0;
$summation = 0;
while ($ctr2 != sizeof($tokens)) {
//compute term_frequency(term in document)
$term_frequency = tf($tokens[$ctr2], $document);
//get idf of term
$inverse_document_frequency = $idf[$tokens[$ctr2]];
//compute norm
$norm = norm($document);
$ctr2++;
$summation += $term_frequency*$inverse_document_frequency*$inverse_document_frequency*$norm;
}
$queryNorm = queryNorm($idf, $tokens);
$coord = coord($tokens, $document, $token_weight);
$lucene_score = $summation * $coord * $queryNorm;
$row1[$ctr]['score'] = $lucene_score;
$ctr++;
}
$row1 = orderBy($row1);
/*
desc score = number of word ocurrences * weight + match_against weight
+ 2(if exact words occur)
*/
$ctr = 0;
while($r2 = mysqli_fetch_array($result2)){
$row2[$ctr]['ID'] = $r2['ID'];
$row2[$ctr]['title'] = $r2['title'];
$row2[$ctr]['description'] = highlight_words($r2['description'], $tokens);
$row2[$ctr]['credit'] = $r2['credit'];
$row2[$ctr]['url'] = $r2['url'];
$desc = strtolower($row2[$ctr]['description']);
$ctr2 = 0;
$total_weight = 0;
$flag = 0;
while ($ctr2 != sizeof($tokens)) {
$weight = substr_count($desc, $tokens[$ctr2]) * $token_weight[$tokens[$ctr2]];
if ($weight == 0)
$flag++;
$total_weight += $weight;
$ctr2++;
}
//occurence of exact word * weight * 2
$exact_word_weight = substr_count($desc, $input) * $total_weight * 5;
$total_weight += $flag;
$row2[$ctr]['score'] = $r2['score'] + $total_weight + $exact_word_weight;
$ctr++;
}
$row2 = orderBy($row2);
}
mysqli_close($con);
}
?>
<!DOCTYPE>
<html>
<head>
<TITLE>Search Engine</TITLE>
<link rel="stylesheet" type="text/css" href="css/reset.css">
<link rel="stylesheet" type="text/css" href="css/search.css">
<!-- jQuery -->
<script src="js/jquery.js"></script>
<!-- Solve Simplex JavaScript -->
<script src="js/validation.js"></script>
</head>
<body>
<div id="wrapper">
<nav>
<form name="search_form" id="search_form" validate method="post">
<div class="left">
<img src="images/logo.png" attr="google logo">
<input type="text" class="textbox" id="obj_function" name="s_input">
<button type="submit" id="search_button" name="submit">
</form>
</div>
<div class="right">
<img src="images/button.png">
Sign In
</div>
</nav>
<div class="nav2">
<ul>
<li class="active">Web</li>
<li>Images </li>
<li>Videos</li>
<li>More <span><img src="images/dropdown.png"></span></li>
<li>Search Tools</li>
</ul>
</div>
<div class="search_results">
<ol>
<li>
<?php
$ctr = 0;
while ($ctr != count($row2)){
echo "<h1><a href=''#'> ".$row2[$ctr]['title']."</a></h1>";
echo "<div class='grey_green_links'>";
echo "<p class='green'>".$row2[$ctr]['url']."<span><img src='images/search_result_link_dropdown.png'></span></p>";
echo "<tr class = 'active'><td>"."<b>Description: </b>".($row2[$ctr]['description']."</td><td></td></tr>");
echo "<tr><td><br></br></td><td></td></tr>";
$ctr++;
}
?>
</li>
</ol>
<div class="page_nav">
<img src="images/pagination_logo.png" alt="pagination page logo">
<ol>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li id="next">10</li>
<li>Next</li>
</ol>
</div>
<footer>
<div class="top">
<p>
<img src="images/your_location_dot.png">
<span class="light_grey">Mars, TX - From your Internet address -</span> Use precise lcoation - Learn more
</p>
</div>
<div class="bottom">
<ul>
<li>Help</li>
<li>Send feedback</li>
<li>Privacy</li>
<li>Terms</li>
</ul>
</div>
</footer>
</div>
</body>
</html>
I personally thinks that bug is somewhere in this section of code, but I can't figure out where it should be. Can someone look at it, and maybe lend me a hand ?
<form name="search_form" id="search_form" validate method="post">
<div class="left">
<img src="images/logo.png" attr="google logo">
<input type="text" class="textbox" id="obj_function" name="s_input">
<button type="submit" id="search_button" name="submit">
</form>
I rewrited it a little bit and it's working, thanks to everyone for help.

how do we get the username of current logged in user in php?

i want to display username of user who is logged in on dropdown which contains option of settings, profile and logout.
here is login.php
<?php
session_start(); // Starting Session
$error[] = ''; // Variable To Store Error Message
require 'function/general.php';
require 'function/users.php';
include 'includes/db_connect.php';
if(empty($_POST)=== false){
$username = $_POST['username'];
$password = $_POST['password'];
if(empty($username) === true || empty($password) === true){
$error[] = "you need to enter username and password";
}
else if(user_exists($username)=== false){
$error[] = "cant find username . have you registerd";
}
else if (user_active($username)=== false) {
$error[] = "havent activated account";
}else{
$login = login($username,$password);
if($login === false){
$error[] = "invalide login credentials";
}
else{
$_SESSION['id'] = $login;
header("Location: index.php");
exit();
}
}
}
?>
here is users.php containing all the functions
<?php
function logged_in(){
return(isset($_SESSION['id'])) ? true : false;
}
function user_exists($username) {
$username = sanitize($username);
return (mysql_result( mysql_query("SELECT COUNT(`id`) FROM `login` WHERE `username` ='$username' "), 0) == 1) ? true : false;
}
function user_active($username) {
$username = sanitize($username);
return (mysql_result( mysql_query("SELECT COUNT(`id`) FROM `login` WHERE `username` ='$username' AND `active` = 1 "), 0) == 1) ? true : false;
}
function user_id_from_username($username){
$username = sanitize ($username);
return mysql_result(mysql_query("SELECT `id` FROM `login` WHERE `username` = '$username'"),0, 'id');
}
function login($username , $password){
$id = user_id_from_username($username);
$username = sanitize($username);
$password = md5($password);
return (mysql_result(mysql_query("SELECT COUNT(`id`) FROM `login` WHERE `username` ='$username' AND `password` = '$password'") , 0) == 1) ? $id : false;
}
here is where i want to show the name of logged in user
<?php
session_start();
include 'includes/bootstrap.html';
require 'function/general.php';
require 'function/users.php';
require 'includes/bootstrap.html';
?>
<script>
$('.dropdown-toggle').dropdown();
</script>
<!---------navbar --->
<nav class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.php"><h3>Utile</h3></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li>Home <span class="sr-only">(current)</span></li>
<li>Browse Photos</li>
</ul>
<?php if (logged_in() === true) {
?>
<!-- <ul class="nav navbar-nav navbar-right">
<li>LogoutProfileSettings</li>
-->
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
**here i want username** <span class="caret"></span>
<ul class="dropdown-menu" role="menu">
<li>Logout</li>
<li>Profile</li>
<li>Setting</li>
<li class="divider"></li>
<li>Separated link</li>
<li class="divider"></li>
<li>One more separated link</li>
</ul>
</li>
<?php
} else {
?>
<ul class="nav navbar-nav navbar-right">
<li>Login</li>
<li>Sign Up</li>
<?php } ?>
<li><button type="button" class="btn btn-primary">Become Professional</button></li>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
If you have followed phpacademy's login system Then you must have the below functions
function user_data($user_id) {
$data = array();
$user_id = (int)$user_id;
$func_num_args = func_num_args();
$func_get_args = func_get_args();
if ($func_num_args > 1) {
unset($func_get_args[0]);
$fields = '`' .implode('`, `', $func_get_args) . '`';
$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM `users` WHERE `user_id` = $user_id"));
return $data;
}
}
function user_id_from_username($username) {
$username = sanitize($username);
return mysql_result(mysql_query("SELECT `user_id` FROM `users` WHERE `username` = '$username'"), 0, 'user_id');
}
Then you can get the username from
$username= $user_data['username'];

mysqli - Commands out of sync; you can't run this command now

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 :'(

Categories