Displaying posts by specific user? this i saw is for ruby on rails and it couldn't help me..
I have two tables, users and posts.
If a user posts anything, it displays on his dashboard which works fine for now. But what i need is for the user to view only his posts.
Please help...
Below is my code:
server.php
<?php
// connect to database
require_once 'database.php';
// initialize variables
$note = "";
$id = 0;
$edit_state = false;
// if save button is clicked
if (isset($_POST['save'])) {
$note = addslashes($_POST['note']);
$created_at = date("Y-m-d H:i:s");
// basic first name validation
if (empty($note)) {
$error = true;
$noteError = "Field cannot be empty.";
}else {
// insert records if no error
$query = "INSERT INTO posts (note, created_at, updated_at) VALUES ('$note', '$created_at', NOW())";
mysqli_query($dbconn, $query);
$_SESSION['msg'] = "Saved";
header('location: ../home.php'); // redirect to home page after inserting
}
}
?>
and this is home.php where results are displayed
<?php
ob_start();
session_start();
error_reporting(E_ALL);
require_once 'config/database.php';
include 'config/server.php';
// if session is not set this will redirect to login page
if( !isset($_SESSION['user']) ) {
header("Location: index.php");
exit;
}
// select loggedin users detail
$res=mysqli_query($dbconn, "SELECT * FROM users WHERE Id=".$_SESSION['user']);
$userRow=mysqli_fetch_array($res);
?>
<div class="container" style="margin-top: 100px;">
<div class="row">
<div class="col-sm-6">
<div class="wrap-status100">
<form method="post" class="login100-form validate-form" action="config/server.php" autocomplete="off">
<span class="login100-form-title p-b-26">
<?php if (isset($_SESSION['msg'])): ?>
<div class="form-group">
<div class="alert alert-<?php echo $_SESSION['msg']; unset($_SESSION['msg']); ?>">
<span class="glyphicon glypicon-info-sign"></span>
</div>
</div>
<?php endif ?>
What's up <?php echo $userRow['fname']; ?>?
</span>
<div class="wrap-input100 validate-input">
<textarea name="note" class="input100" value="<?php echo $note; ?>"></textarea>
<span class="focus-input100" data-placeholder="Write note here."></span>
</div>
<div class="container-login100-form-btn">
<div class="wrap-login100-form-btn">
<div class="login100-form-bgbtn"></div>
<?php if ($edit_state == false): ?>
<button name="save" class="login100-form-btn">
Save
</button>
<?php else: ?>
<button name="update" class="login100-form-btn">
Update
</button>
<?php endif ?>
</div>
</div>
</div>
</form>
</div>
<div class="col-sm-6">
<?php if (isset($_SESSION['msg'])): ?>
<div class="msg">
<?php
echo $_SESSION['msg'];
unset($_SESSION['msg']);
?>
</div>
<?php endif ?>
<table>
<thead>
<tr>
<th>Note</th>
<th>created</th>
<th>Updated</th>
<th colspan="2">Action</th>
</tr>
</thead>
<tbody>
<?php while ($row = mysqli_fetch_array($results)) { ?>
<tr>
<td><?php echo $row['note']; ?></td>
<td><?php echo $row['created_at']; ?></td>
<td><?php echo $row['updated_at']; ?></td>
<td><a class="edit_btn" href="home.php?update=<?php echo $row['id']; ?>">Update</a>
</td>
<td>
<a class="del_btn" href="config/server.php?del=<?php echo $row['id']; ?>">Delete</a>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>
You need to take one more column in posts table i.e user_id. You have to store the id of user who create the Post.
While fetching the result, you can take logged in user's id. And create a query like
"Select * from posts where user_id=".$_SESSION['user'];
by this you have get all the posts created by that particular user.
Hope this helps.
Thanks.
You need to do this in this way:
First while adding a post you have to insert the user id of the user who is posting the post. Be sure to add a field named user_id in the posts table in db. PLease try this query:
$user_id=trim($_SESSION['user']);
$query = "INSERT INTO posts (note,user_id, created_at, updated_at) VALUES ('$note', '".$user_id."' , '$created_at', NOW())";
Now in the dashboard of the user you need to fetch the posts based on the user_id and then loop the tr in the results array:
"Select * from posts where user_id=".$_SESSION['user'];
Related
I am trying to create a shopping cart with PHP, but, once the user leaves the cart area, all of the products disappear. That's what I'm trying to do:
<?php foreach($almofadas as $almofadas):?>
<form action="cart.php" method="GET">
<div class="base col-6 col-sm-4 col-md-5 col-lg-4 col-xl-4">
<div class="card">
<img src="uploads/<?php echo $almofadas['imagem']; ?>" alt="">
<div class="content-c">
<div class="row-p">
<div class="details">
<span><?php echo $almofadas['pnome'] ; ?></span>
</div>
<div class="price">R$ <?php echo $almofadas['preço'];?> </div>
</div>
<input type="hidden" name="id" value="<?php echo $almofadas['p_id']?>">
<div style="margin-top: 10px;">
<div style="margin-bottom: 5px;"><button class="buttons-1" data-toggle="modal" data-target="#myModal">Detalhes</button></div>
<div><button class="buttons-2" type="submit">Adicionar ao Carrinho</a> </button></div>
</div>
</div>
</div>
</div>
</form>
<?php endforeach; ?>
Now the cart system:
<?php
session_start();
require_once 'conn.php';
$_SESSION['id'] = $_GET['id'];
$result_pedido = "SELECT * FROM tb_produtos WHERE p_id = '{$_SESSION['id']}'";
$resultado_pedido = mysqli_query($conn, $result_pedido);
$pedidos = mysqli_fetch_all($resultado_pedido, MYSQLI_ASSOC);
?>
Here I can only add one product and, I can't save it into a $_SESSION, having said that the product disapears once iI leave the cart.
<?php foreach($pedidos as $pedidos):?>
<tr>
<td>
<div class="cart-img">
<img src="uploads/<?php echo $pedidos['imagem'];?>" width="125px">
</div>
</td>
<td>
<div class="cart-model">
<?php echo $pedidos['pnome'] ; ?>
</div>
</td>
<td>
<div class="cart-quantity">
<input class="i-quantity" type="number" value="1">
</div>
</td>
<td>
<div class="cart-price">
R$<?php echo $pedidos['preço'] ; ?>
</div>
</td>
</tr>
</tbody>
</table>
<?php endforeach; ?>
If you check this line:
$_SESSION['id'] = $_GET['id'];
This mean the "id" in your $_SESSION is always set to $_GET['id'], even if it is empty. So it is reset every time the user visit a page.
You should:
have some mechanism to store your shopping cart content. There is none in your code; and
have a way to check if the user visits a new id before storing it to shopping cart.
For example,
<?php
/**
* This only make sense if this script is called
* by some AJAX / javascript interaction to specifically
* add a new item to cart.
*/
session_start();
require_once 'conn.php';
if (isset($_GET['id']) && !empty($_GET['id'])) {
$_SESSION['id'] = $_GET['id'];
}
$result_pedido = "SELECT * FROM tb_produtos WHERE p_id = '{$_SESSION['id']}'";
$resultado_pedido = mysqli_query($conn, $result_pedido);
$pedidos = mysqli_fetch_all($resultado_pedido, MYSQLI_ASSOC);
// If the user visits a path where the $_GET['id'] have result in
// database and the user specified that he / she want to save something
// to his / her cart.
if (isset($_GET['id']) && !empty($_GET['id']) && !empty($pedidos)) {
if (!isset($_SESSION['cart'])) $_SESSION['cart'] = []; // initialize if not exists.
$_SESSION['cart'] = array_merge($_SESSION['cart'], $pedidos);
}
?>
Note: the quantity should be set to the cart somehow. You need to change the data structure to set or increment the "qty". But this is at least a start.
I have a problem which is the user when write in my comments form is insert successfully but when I refresh the page it will insert the last comments again , I read the solution in this link how to stop data automatically insert into database in php
but does not work for me
this is my codes I would appreciate for your help :)
file viewhospital.php contain include comments.php file
--look at the bottom of the codes--
<?php
include ('header.php');
if(!isset($_GET['hospital_id'])){
echo '<div class="alert alert-danger" role="alert"><b>You should choose hospital before opening this page!</b></div>';
include ('footer.php');
die();
}
include ('setting.php');
$sql = 'select * from hospital where hid = '. $_GET['hospital_id'];
$result = $conn->query($sql) or die(mysql_error($conn));
$hospital = null;
if ($result->num_rows > 0) {
$hospital = $result->fetch_assoc();
} else {
die('Could not find hospital!');
}
$sql = 'select * from doctor where hospital_id = '. $_GET['hospital_id'];
$doctor_result = $conn->query($sql) or die(mysql_error($conn));
$conn->close();
?>
<div class="row">
<div class="col-md-6">
<p class="text-center">
<img src="<?php echo $hospital['image']; ?>" class="img-thumbnail" style="height: 400px;">
</p>
</div>
<div class="col-md-6">
<p class="text-center">
<img class="img-thumbnail" src="https://maps.googleapis.com/maps/api/staticmap?center=<?php echo $hospital['location']; ?>&zoom=13&size=400x400&maptype=roadmap&markers=color:blue%7Clabel:S%7C<?php echo $hospital['location']; ?>&key=AIzaSyD59nHXpZgqZwjJvsAcPe2CYcIEWoaQ9yY" style="height: 400px;">
</p>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h1 class="page-header">
<?php echo $hospital['name']; ?>
</h1>
<p>
<?php echo $hospital['description']; ?>
</p>
<p>
Address: <?php echo $hospital['address']; ?>
</p>
<p>
Phone: <?php echo $hospital['phone']; ?>
</p>
<p>
Go To Hospital
</p>
<p>
Online Appointment
</p>
</div>
</div>
<!--<div class="row">
<div class="col-md-12 text-center">
<div class="btn-group" role="group" aria-label="...">
<a type="button" class="btn btn-info">Edit</a>
<a type="button" class="btn btn-danger">Remove</a>
<a type="button" class="btn btn-primary" href="doctor_form.php?hospital_id=<?php echo $hospital['hid']; ?>">Add Doctor</a>
</div>
</div>
</div>-->
<div class="row">
<div class="col-md-12">
<table class="table table-striped">
<caption>Doctors:</caption>
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Field</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
if ($doctor_result->num_rows > 0) {
while($row = $doctor_result->fetch_assoc()) {
?>
<tr>
<th scope="row">
<?php echo $row['did'];?>
</th>
<td>
<?php echo $row['name'];?>
</td>
<td>
<?php echo $row['field'];?>
</td>
<td>View</td>
</tr>
<?php
}
}else{
?>
<tr>
<th scope="row"></th>
<td>No doctors found</td>
<td></td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
<?php
include ('comments.php');
include ('footer.php');
?>
the comments.php file
<?PHP
# comments PHP code
date_default_timezone_set('Asia/Riyadh');
function setComments (){
if (isset($_POST['submitComments'])){
include('setting.php');
//$uid = $_POST['uid'];
$date = $_POST['date'];
$message = $_POST['message'];
$sql = "INSERT INTO comments ( date, message) VALUE ( '$date', '$message')";
$result = mysqli_query($conn,$sql);
}
}
function getComments (){
if (isset($_POST['submitComments'])){
include('setting.php');
$sql = "SELECT * FROM comments";
$result = mysqli_query($conn,$sql);
while ($row = $result->fetch_assoc()){
echo "<div class='comments-box'>";
echo $row['date']."<br>";
echo nl2br($row['message'])."<br><br>";
echo "</div>";
}
}
}
echo "
<form action='".setComments ()."' method='POST'>
<input type='hidden' name='uid' value=''>
<input type='hidden' name='date' value='".date('Y-m-d H:i:s')."'>
<textarea name='message' class='form-control' rows='3'></textarea>
<br>
<button type='submit' name='submitComments' class='btn btn-primary'>Comments</button>
</form>
<br><br>
";
getComments ();
?>
When you refresh in the browser, you send the last request again. That request was the POST of the form. So the user (browser) is telling the code to insert another comment.
Generally this is handled by redirecting after posting a form, rather than re-displaying the form again. Move all of your logic for (and only for) inserting the new content to its own PHP file (something like addComment.php) and have the form post to that file. Then in that file ensure that there is no actual output except perhaps to display an error message if something goes wrong?) and just a redirect back to the page:
header("Location: viewhospital.php");
This will instruct the browser in the response to make a new GET request for viewhospital.php. So if the user reloads the browser, all they're doing is repeating that GET request.
I am trying to generate Tabs from 1st while loop and within that table from second while loop.
I will fetch the records date wise from my 1st table ie, treatment from that i am generating Tab, In another table called treatment_litems i have stored all the line items for treatment table records. So for 1st date (Tab) from treatment table, i want to display all the related records from treatment_litems in table format.
I am getting records but Tabs are not getting added, but everytime new Tabs are generating.
here is my code
<ul class="nav nav-tabs">
<?php $i=1; while($tt2 = mysqli_fetch_array($tt1)) { ?>
<li>
<?php echo $tt2['date']; ?>
</li>
</ul>
<div class="tab-content">
<div class="tab-pane fade active in" id="tab_1_<?php echo $i; ?>">
<?php $l1 = mysqli_query($con, "SELECT * FROM treatment_litems WHERE tid=".$tt2['tid'].""); ?>
<table class="table">
<thead><tr><th>Drugs</th><th>Route</th><th>Dosage</th></tr></thead>
<tbody>
<?php
while($l2 = mysqli_fetch_array($l1)) { ?>
<tr><td><?php echo $l2['drugs']; ?></td>
<td><?php echo $l2['route']; ?></td>
<td><?php echo $l2['dosage']; ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
<?php $i++ ; } ?>
</div>
Here is the image
**** EDITED ******
<ul class="nav nav-tabs">
<?php
while($tt2 = mysqli_fetch_array($tt1)) { ?>
<li>
<?php echo $tt2['date']; ?>
</li>
</ul>
<?php } ?>
<div class="tab-content">
<div class="tab-pane fade active in" id="tab_1_<?php echo $tt2['tid']; ?>">
This is my working code, you can get hints by this:
<div id="tabs" style="float:left">
<ul>
<?php $getlang=mysql_query("select * from language where Mid='$mid' and status='1' order by LanguageName asc");
if(mysql_num_rows($getlang)>0){
while($arr=mysql_fetch_array($getlang)){?>
<li><?php echo $arr['LanguageName']; ?></li>
<?php }}?>
</ul>
<?php $getlang=mysql_query("select * from language where Mid='$mid' and status='1' order by LanguageName asc");
if(mysql_num_rows($getlang)>0){
while($arr=mysql_fetch_array($getlang)){?>
<div id="tabs-<?php echo $arr['LanguageID'] ?>">
<input type="hidden" name="LanguageId[]" class="langID" value="<?php echo $arr['LanguageID']; ?>">
<input type="hidden" name="mid" value="<?php echo $mid; ?>">
<div class="rows">
<label>Notification Text</label><br/>
<textarea rows="3" cols="10" name="description[]" id="" maxlength="1000" style="width:700px; height:100px;" required="required"></textarea>
</div>
</div>
<?php } }
Check and do let me know.
I have a form that's supposed to enter a reply to a forum topic into the database and redirect the user back to the same topic. After much trial and error I have finally got the form to work, only it is putting two identical entries into the db every time. I cannot figure out why. I have looked up this same problem and most of the other people were not redirecting after the form submission or they were using AJAX or jquery or something. Here is my page info:
<?php
session_start();
include_once('includes/config.php');
include_once('classes/topic.php');
include_once('classes/post.php');
include('includes/header.php');
?>
<link rel="stylesheet" href="css/dd.css">
<?php
$topic = new Topic;
if (isset($_GET['id']))
{
$topic_id = $_GET['id'];
$data = $topic->fetch_data($topic_id);
if (isset($_POST['content']))
{
// someone posted a reply
$date = date('Y-m-d H:i:s');
$by = $_SESSION['user_id'];
$query = $pdo->prepare("INSERT INTO dd_posts (post_content, post_date, post_by, post_topic) VALUES (? ,? ,?, ?)");
$query->bindParam(1, $_POST['content']);
$query->bindParam(2, $date);
$query->bindParam(3, $by);
$query->bindParam(4, $_GET['id']);
$query->execute();
$result = $query->execute();
header("location:topic.php?id=".$_GET['id']);
exit;
}
?>
<div id ="wrapper">
<div class="drop-section">
<div id="menu">
<a class="item" href="drop_index.php">Dead Drop</a>
<a class="item" href="add_topic.php">New Post</a>
<a class="item" href="admin/add_cat.php">New Category</a>
<div id="userbar">
<?php
if( $user->is_logged_in() ) {
echo 'Hello ' . $_SESSION['user_name'] . '. How are you?';
} else {
echo '<a class="item" href="login.php">Sign in</a> or <a class="item" href="index.php">Create an account</a>';
}
?>
</div>
</div>
<table>
<tr class = "header-row">
<div id = "sans">
<?php echo $data['topic_subject']; ?>
- <small>started by <?php echo $data['user_name']; ?> </small><br />
<?php echo $data['topic_content']; ?>
</div>
</tr>
<?php
// retrieve all the replies to the original topic
$post = new Post;
$topic_id = $_GET['id'];
$posts = $post->fetch_all_posts_by_topic($topic_id);
?>
<tr>
<td class="first-column">
<?php foreach ($posts as $post) { ?>
<div class="drop-content-box">
<li><?php echo $post['post_content']; ?><br />
<div class = "forum-user-info">
<a href="player.php?id=<?php echo $post['user_id']; ?>">
<?php echo $post['user_name']; ?></a> - level:
<?php echo $post['user_level']; ?>
</div>
</li>
</div>
<?php } ?>
</td>
</tr>
</table>
<?php
if( $user->is_logged_in() )
{
?>
<div id = "header-section">Reply</div>
<?php if (isset($error)) { ?>
<small><?php echo $error; ?></small>
<?php } ?>
<form action="<?php echo "topic.php?id=".$_GET['id']?>" method="post" autocomplete="off">
<small><i>Do not post the actual answer to any level.</i></small><br />
<textarea rows="15" cols="50" name="content" placeholder="Give us your thoughts..."></textarea><br />
<input type="submit" value="Post" />
</form>
</div>
</div>
<?php
} else {
echo '<div id = "errors"><small>You must be signed in to reply.</div></small>';
}
}
include_once('includes/footer.php');
?>
You're executing the query twice.
$query->execute();
$result = $query->execute();
I got an error on my page that I can't identify, and when I view the site online it replaces all my site content with the value "0".
How come I can't see the forms, and is it communicating with the SQL server properly?
PS: Login works and session is created, so the connect.php does work properly.
Here is the code for members.php:
<?php
// starting session
session_start();
// check if user is logged in
if (!isset($_SESSION['username']))
{
header('Location: http://wwww.gjertgjersund.com/');
exit();
}
else
{
// database connection
require ('connect.php');
//post record count
$post_count = mysql_query("SELECT * FROM posts");
$post_count_result = mysql_num_rows($post_count);
//comment count
$comment_count = mysql_query("SELECT * FROM comments");
$comment_count_result = mysql_num_rows($comment_count);
if(isset($_POST['submit']))
{
$newcategory = $_POST['newcategory'];
if(!empty($newcategory))
{
$query = mysql_query("INSERT * INTO categories (category) VALUES ('$newcategory')";
if($query)
{
echo 'New category added';
}
}
else
{
echo 'Error';
}
}
else
{
echo 'Missing newcategory';
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title> Folder </title>
<body>
<div class="wrap">
<div id="menu">
<ul>
<li><a href='#'>Home</a></li>
<li><a href='#'>Create New Post</a></li>
<li><a href='#'>Delete Post</a></li>
<li><a href='logout.php'>Log Out</a></li>
<li><a href='#'>Blog Home Page</a></li>
</ul>
</div>
<div id="maincontent">
<table>
<tr>
<td>Total Blog Post</td>
<td><?php echo $post_count_result ?></td>
</tr>
<tr>
<td>Total Comments</td>
<td><?php echo $comment_count_result ?></td>
</tr>
</table>
<div id="categoryform">
<form action="members.php" method="post">
<label for="category">Add New Category</label>
<input type="text" name="newcategory"/>
<input type="submit" name="submit" value="Create"/>
</form>
</div>
</div>
</div>
</body>
</html>
$query = mysql_query("INSERT * INTO categories (category) VALUES ('$newcategory')";
should be
$query = mysql_query("INSERT INTO categories (category) VALUES ('$newcategory')";