I have looked far and wide through the lands of Stack Overflow, but have found no success in finding a solution to my extremely basic question.
I have a messaging system within my website and when a user posts a message, I would like their name to feature at the top of the article eg. "Posted by (name)".
At the moment, it displays the name of the logged in user, however this name changes depending on whoever is logged in at the time.
So, if I posted something under the name "Jim", and then logged in under the name "Bob", it would display the poster name as "Bob".
I am aware that my problem lies within $username = $_SESSION['username'];. I'm just not sure what to do about it.
<?php
require_once("nbbc/nbbc.php");
$bbcode = new BBCode;
$sql = "SELECT * FROM comment ORDER BY id DESC";
$res = mysqli_query($dbCon, $sql) or die(mysqli_error($dbCon));
$comment = "";
$username = $_SESSION['username'];
if(mysqli_num_rows($res) > 0) {
while($row = mysqli_fetch_assoc($res)) {
$id = $row['id'];
$date = $row['date'];
$content = $row['content'];
$bbcode->Parse($content);
$comment .= "
<div id='a_comment'>
<h1>Posted by $username on $date</h1>
<p>$content</p>
</div>
";
}
echo $comment;
} else {
echo "<div id='no_comments'>There are no comments to be displayed.</div>";
}
?>
Here's the rest of the code:
<?php
session_start();
include_once("inc/connection.php");
error_reporting(E_ALL); ini_set('display_errors', 1);
if(!isset($_SESSION['username'])) {
header("Location: login.php");
return;
}
if(isset($_POST['post'])) {
$content = strip_tags($_POST['content']);
$content = mysqli_real_escape_string($dbCon, $content);
date_default_timezone_set("Australia/Victoria");
$date = date('d-m-y h:i:sa');
$sql = "INSERT INTO comment (date, content) VALUES ('$date', '$content')";
mysqli_query($dbCon, $sql);
header("Location: members.php");
}
?>
Ideally you would store the user ID in the comment table, and then use the user table for a lookup when pulling the comment out. However, since I know nothing about your table structure, I'm going to give you instructions for storing the username in the comment table instead, and you can adjust for your needs.
Step 1: Alter your comment table to store the username
ALTER TABLE comment
ADD username VARCHAR(100) AFTER content;
Step 2: Store the username when storing the post
$sql = "INSERT INTO comment (date, content, username) VALUES ('$date', '$content', '{$_SESSION['username']}')";
Step 3: Assign the correct username when retrieving the data
$username = $row['username'];
Related
I want to query my SQL database for a name. Let's say a certain table contains the column "names" and has two inputs "John Silva" and "Dave Silva". I want to make a query where I get all inputs with the name "Silva" and store them in a way that I can later echo out the result onto my HTML code. Here's what I got so far (keep in mind that it is not working, that's why i came here to ask :) ):
$query = "SELECT ID, email, fullname, permission FROM users WHERE name LIKE '$data'";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$userName = $row['fullname'];
$userHashedPermission = $row['permission'];
$ID = $row['ID'];
$userEmail = $row['email'];
}
if(password_verify('sim', $userHashedPermission)){
$userPermission='sim';
}else{
$userPermission='nao';
}
$callbackObj->name = $userName;
$callbackObj->permission = $userPermission;
$callbackObj->Id = $ID;
$callbackObj->email = $userEmail;
$callbackJson = json_encode($callbackObj);
echo $callbackJson;
}else{
echo "something went wrong"
}
The functionality you want is like. More importantly: learn to use parameters.
$query = "SELECT ID, email, fullname, permission FROM users WHERE name LIKE CONCAT('%', ?)";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, "s", $data)
$result = mysqli_stmt_execute($conn, $query);
I think your sample code and the introduction are totally explaining different thing.
From your introduction, I think you are trying to get all search results with the same surname and then save them in another different way.
If that is your point, we will have better way to sort it out.
You need to make some changes in your query as
$query = "SELECT ID, email, fullname, permission FROM users WHERE name LIKE '%".$data."%'";
As per the comments
Do not use while loop keep your code as
if(mysqli_num_rows($result) > 0){
$row = mysqli_fetch_assoc($result));
$callbackJson = json_encode($row);
echo $callbackJson;
}
i am retrieving posts from a table called post . I wanted to add a commenting feature to this code, The problem is that the latest posts variables are dominant over others in that if you comment on an older post, the variables of the "latest post(which appears first because of the ORDER BY ID DECS criteria"
Someone help me make this posts independent on their own...Thanks
<?php
$sqlhash="SELECT * FROM posts ORDER BY id DESC ";
$result_hash = mysqli_query($conn,$sqlhash);
while($rowhash = mysqli_fetch_assoc( $result_hash))
{
$user = $rowhash['user'];
$message = $rowhash['post'];
$time = $rowhash['time'];
$id= $rowhash['id'];
$tt = date('m/d/Y H:i:s',$time);
$my_id = $_SESSION['user_id'];
$sql="SELECT * FROM users WHERE Full_name='$user' ";
$result_set = mysqli_query($conn,$sql);
while($row = mysqli_fetch_assoc( $result_set))
{
$select_username = $row['Full_name'];
$profp = $row['pic'];
$my_id = $_SESSION['user_id'];
?>
<center><div class='post' style='width:48%; height:40%; align:middle; text-align:left; margin:30px 0'>
<img width="70" height="70" src='uploads/<?php echo $profp; ?>'><br><p style='color:#0c88b5'><b> <?php echo $id ;?><br><?php echo $user ;?>On:<?php echo $tt ; ?><h4><b><?php echo $message
;?></h4></p><hr>
<?php
$sqlcom="SELECT * FROM comment WHERE hash='$id' ";
$result_com = mysqli_query($conn,$sqlcom);
while($rowcom = mysqli_fetch_assoc( $result_com))
{
$usercom = $rowcom['comment'];
$comenter = $rowcom['user'];
echo "<p style='color:#0c88b5' $comenter</p>". ":" ;
echo $usercom. "<br>" ;
}
if (isset($_POST['commen'])) {
$sqlhash= "SELECT * FROM posts WHERE post= '$message' ";
$result_hash = mysqli_query($conn,$sqlhash);
while($rowhash = mysqli_fetch_assoc( $result_hash))
{
$user1 = $_SESSION['username'];
$comment = $_POST['commen'];
$time = $rowhash['time'];
$time2 = $_SESSION['time'];
$sql3 = "INSERT INTO comment (user, comment, hash) VALUES
('$user1','$comment', '$id')";
if($conn->query($sql3) === TRUE) {
header('Location: timeline.php');
}else {
echo"error";
}
Make some changes at database level in your post table to manage the reply thread on a post.
Add a parent_id column with default null that contains the post id for which the reply or comment is made.
For each comment or reply, put an entry in parent_id column.
To show post, fetch the records having parent_id IS NULL. By this you will get the post only, put order by on id to get in a proper order.
For each post you can retrieve comment or reply by putting a condition like parent_id IS NOT NULL
This will help you.
first I have a login form in c# that asks the user to input his email and password then these are data are sent to the domain then I retrieve it in php so I wrote a sql query to get the logged in user id and this works fine till the
if(isset($_POST['y']))
inside of it there is an insert query this query works but doesn't insert the user id ! I tried to figure it out but I dont know whats the problem .
here's the code :
<?php
session_start();
$con = mysqli_connect("mysql7.000webhost.com","a1945567_host","12345678ab","a1945567_db");
$sql = "SELECT ID FROM user WHERE Email = '".$_GET["txt_UserName"]."'AND Password = '".sha1($_GET["txt_Password"])."'";
$result = $con->query($sql);
$
$row = mysqli_fetch_array($result,MYSQLI_NUM);
$_SESSION['ID'] = $row[0] ;
echo "SUCCESS";
echo $usrID = $row[0];
if(isset($_POST['y'])){
$sql = "INSERT INTO `question13_interaction` (uid,no_0,no_1) VALUES ('".$usrID."','".$_POST['y']."',0)";
$con->query($sql);
// mysqli_query($con,$sql);
}
else if(isset($_POST["z"])){
//$sumcount = "INSERT INTO question13_interaction (sumcount)";
//$result = mysqli_query($con,$sumcount);
$sql1 = "INSERT INTO question13_interaction(uid,no_1,no_0) VALUES('".$row[0]."','".$_POST["z"]."',0)";
mysqli_query($con,$sql1);
}
//}
/*else
{
echo "FAILED";
}*/
?>
you have an extra"$" in the code:
$result = $con->query($sql);
$
probably should just be :
$result = $con->query($sql);
also I don;t think you want the echo in this statement - it will probably not set it to the correct value for your query:
echo $usrID = $row[0];
should be
$usrID = $row[0];
Except for the redundant "$", there is another question. There should be a white space between single quote and "AND", or mysql cann't parse the query correctly
ok so the problem is that when this form is submitted and there are some input fields that have been left blank the blank data is written to the database and because I do not wish for duplicate inputs of each field the second person who fills in the form can't submit unless they have left different fields empty.
I do not wish to make it so people have to fill out all fields as not everyone will have the usernames that each field asks for.
if(isset($_POST["signupbtn"])) {
if ($log_username) {
/// getting data from submitted form into local variables
$x = preg_replace('#[^a-z 0-9]#i', '', $_POST['xbox']);
$p = preg_replace('#[^a-z 0-9]#i', '', $_POST['psn']);
$s = preg_replace('#[^a-z 0-9]#i', '', $_POST['steam']);
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR GAMER PROFILES
$sqli = "SELECT username FROM player WHERE xbox='$x' LIMIT 1";
$query = mysqli_query($db_conx, $sqli);
$x_check = mysqli_num_rows($query);
// -------------------------------------------
if ($x_check > 0){
echo "Xbox Gamer-Tag already linked to a user on this website";
exit();
} else if (is_numeric($x[0])) {
echo 'Xbox Gamer-Tag cannot begin with a number';
exit();
}
$sqli = "SELECT username FROM player WHERE psn='$p' LIMIT 1";
$query = mysqli_query($db_conx, $sqli);
$p_check = mysqli_num_rows($query);
// -------------------------------------------
if ($p_check > 0){
echo "PSN User already linked to a user on this website";
exit();
} else if (is_numeric($p[0])) {
echo 'PSN User cannot begin with a number';
exit();
}
$sqli = "SELECT username FROM player WHERE steam='$s' LIMIT 1";
$query = mysqli_query($db_conx, $sqli);
$s_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if ($s_check > 0){
echo "Steam account already linked to a user on this website";
exit();
} else if (is_numeric($s[0])) {
echo 'Steam account cannot begin with a number';
exit();
} else { $sqli = "INSERT INTO player (id, username, xbox, psn, steam, ip, created, lastupdated, notecheck)
VALUES ('$id','$log_username','$x','$p','$s','$ip',NOW(),NOW(),NOW())";
$query = mysqli_query($db_conx, $sqli);
echo "Gamer Profiles Updated";
}
exit();
if (!file_exists("p_player/$log_username")) {
mkdir("p_player/$log_username", 0755);
}
}
}
Above is the php and this works fine it writes the information to the table without a problem other then the fact it also rights the blank data to the database. If any could point me in the right direction or even solve my problem I will appreciate it a lot. I have looked all over google but I can't seem to find anything because all the answer I do find are not exactly what I mean and as I am new to PHP the task seems to be harder to find the correct answer I am looking for. Thanks for you time in reading this.
You pretty much got it, I would do the following
For steam for example
if ($s != ''){
$sqli = "SELECT username FROM player WHERE steam='$s' LIMIT 1";
$query = mysqli_query($db_conx, $sqli);
$s_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if ($s_check > 0){
echo "Steam account already linked to a user on this website";
exit();
} else if (is_numeric($s[0])) {
echo 'Steam account cannot begin with a number';
exit();
}
} else {
$sqli = "INSERT INTO player (id, username, xbox, psn, steam, ip, created, lastupdated, notecheck)
VALUES ('$id','$log_username','$x','$p','$s','$ip',NOW(),NOW(),NOW())";
$query = mysqli_query($db_conx, $sqli);
echo "Gamer Profiles Updated";
}
Then allow duplicate values in that field. This will allow blank fields, but not duplicate fields that contain data.
You can still allow multiple NULL values. Set those unique columns to have a default value of NULL, so if nothing get passed it will store NULL instead of an empty value.
I wanna do the following: Check if a user is already in the second table. If the user is, I get back the echo: "User is in database" and it should also add a value to the table, when the user is or is not in the database. As of now it seems to do the right thing, but doesn't change the value next to user.
<?php
$DB_HostName = "localhost";
$DB_Name = "db";
$DB_User = "user";
$DB_Pass = "pw";
$DB_Table = "connection";
$DB_Table2 = "contacts";
$con = mysql_connect($DB_HostName,$DB_User,$DB_Pass) or die (mysql_error());
mysql_select_db($DB_Name,$con) or die(mysql_error());
$query = "SELECT User FROM $DB_Table left join $DB_Table2 on User = Number";
if ($result) {
if (mysql_num_rows($result) > 0) {
echo "This user is already in database";
mysql_query("INSERT INTO $DB_Table2 (Answer)
VALUES ('http://myserver/thumbsup.png')");
}
else {
echo "This user isn't in the database";
mysql_query("INSERT INTO $DB_Table2 (Answer)
VALUES ('http://myserver/thumbsdown.png')");
}
}
mysql_close($con);
?>
When looking at the code, it's hard to see what you're trying to do here. Anyhow, I do think you need to check which user you're looking from the table.
$query = "SELECT User FROM $table_id left join $table_id2 on User = Number";
should be more like
$query = "SELECT User FROM $DB_Table left join $DB_Table2 on User = Number where $DB_Table.User = " . $_SESSION['userid'];
if you have authenticated the user some way and the users id number is in a session variable called 'userid'. You clearly have not thought this through, because you're adding links to the second table with default values on every other key.