Username and ID change after i search for something - php

I have a small social website, with profile pages and a search page. It all works fine and on the menu bar it displays the users username with a link to their profile via profile.php?id=5 (for example).
How ever when I search for something via search.php it all works fine, but then when I reload a page after searching, suddenly the username is displayed as 'p' and the link goes to profile.php?id=p
Does anybody have any idea what's happening?
Tell me if you need any more information, and thanks in advance.
The code:
<?php
//capture search term and remove spaces at its both ends if the is any
$searchTerm = trim($_GET['search']);
//check whether the name parsed is empty
if($searchTerm == "")
{
echo "Enter name you are searching for.";
exit();
}
//database connection info
$host = ""; //server
$db = ""; //database name
$user = ""; //dabases user name
$pwd = ""; //password
//connecting to server and creating link to database
$link = mysqli_connect($host, $user, $pwd, $db);
//MYSQL search statement
$query = "SELECT * FROM users WHERE username SOUNDS LIKE '%$searchTerm%' or fname SOUNDS LIKE '%$searchTerm%' or lname SOUNDS LIKE '%$searchTerm%'";
$results = mysqli_query($link, $query);
echo "<div class='searched'>Results for ";
echo $searchTerm;
echo "</div>";
/* check whethere there were matching records in the table
by counting the number of results returned */
if(mysqli_num_rows($results) >= 1)
{
$output = "";
while($row = mysqli_fetch_array($results))
{
$output .="<div class='user'><a href='profile?id=$row[id]'>";
$output .= "<img class='search_pp' src='" . $row['picture'] . "'/><br>";
$output .= "<div class='search_username'> " . $row['username'] . "</div>";
$output .= "<div class='search_full'>Full name: " . $row['fname'] . " " . $row['lname'] . "</div>";
$output .= "<div class='search_sex'>" . $row['sex'] . "</div></div></a>";
}
echo $output;
}
else
echo "No records of " . $searchTerm;
?>
This is where the username changes to 'p'
<?php echo htmlentities($_SESSION['user']['username'], ENT_QUOTES, 'UTF-8'); ?>
and this is where the id in a link changes to 'p'
<a href="profile?id=<?php echo htmlentities($_SESSION['user']['id'], ENT_QUOTES, 'UTF-8'); ?>">
then the users username and id changes to 'p' all throughout the site

1 - WHere do you set your $_SESSION['user'] ?
2 - Can you do a var_dump($_SESSION['user']); before and after the refresh to see what's going on?

Related

How to Remove Slug from my Post , Post.php?Slug=postname-title

I have made a blog in PHP, on Post.php with If isset get I am checking Post ID and than getting slug of same ID from database and accessing the post with that slug.
The issue is its generating Url like: Post.php?Slug=postname-title
I want to make it Post.php?postname-title OR urls.com/postname-title
Please note I am getting post from database matching with slug If any how I do not set php to Get in url it is not getting value from the same slug.
Please guide if it will be done via .htaccess or any other way?
<?php
// add mysql_real_escape_string to slug, to prevent sql injection
$slug = $_GET["slug"];
$sql = "SELECT * FROM posts WHERE slug = '" . mysqli_real_escape_string($db, $_GET["slug"]) . "'";
$result = mysqli_query($db, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while ($row = mysqli_fetch_assoc($result)) {
echo "<h2>" . $row["title"] . "</h2>";
echo "<div id='post-details'>" . "Posted on " . $row["post_date"] . " -- " . "Last Update " . $row["last_edited"] .
"</div>";
if (loggedin()) { echo "<div id='postactions'>This Post:<a href='create_note.php?id=" . $row["id"] . "'>Add Notes</a>";
echo 'Delete Post';
echo 'Edit</div>'; }
$cat_id = $row["cat_id"];
$sql = "SELECT * FROM categories WHERE id = $cat_id";
$resultone = mysqli_query($db, $sql);
if (mysqli_num_rows($resultone) > 0) {
// output data of each row
while ($rowone = mysqli_fetch_assoc($resultone)) {
$cat_name = $rowone["name"];
echo "<div id='post-category'>" . "Category: <a href='all-categories.php?cat_id=$cat_id'>$cat_name</a>" . "</div>";
}
}
echo "<p>" . htmlspecialchars_decode($row["body"]) . "</p>";
$_SESSION["post_id"] = $row["id"];
$postid = $row["id"];
}
} else {
echo "0 results";
}
?>
If you want a simple .htaccess version, you could use the following rule:
RewriteRule ^post/(.+) Post.php?Slug=$1
This will change your URL from a pretty URL like: yourdomain.com/post/postname-title to yourdomain.com/Post.php?Slug=postname-title

My PHP code to search for a first name or last name from a table in a database is not printing anything to my webpage

The user suppose to input first name or last name into a search bar in a web-page and it suppose to list attributes from the table into the web-page. No matter what I type into the search bar, nothing is outputted. I followed this video on how to search in php. I tried looking at it over an hour but I can't find anything wrong. I get no error messages in my webpage.
<?php
$serverName = 'localhost';
$userName = 'root';
$password = '';
$databaseName = 'project3';
$connection = mysqli_connect($serverName, $userName, $password,
$databaseName);
if (!$connection) {
die("Connection Failed: " . mysqli_connect_error());
}
echo "Connected Successfully!! <br>";
$output = '';
if (isset($_Post['search'])) {
$searchq = $_Post['search'];
$searchq = preg_replace("#[^0-9a-z]#i", "", $searchq);
$query = mysqli_query("SELECT * from employee WHERE fname LIKE
'%$searchq%' OR"
. "lname LIKE '%$searchq%") or die("failed");
$count = mysqli_num_rows($query);
if ($count == 0) {
$output = 'No search results';
} else {
while ($row = mysqli_fetch_array($query)) {
$firstname = $row['fname'];
$lastname = $row['lname'];
$id = $row['id'];
$output .= '<div>' . $firstname . '' . $lname . '</div>';
echo "hi";
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Database Webpage</title>
<font color ="white">
<h1 style="background-color:black; text-align: center">Datebase Website</h1>
<font color ="black">
</head>
<body>
<form action = "index.php" method = "POST">
<input type = "text" name ="search" placeholder="Search"/>
<input type= "submit" value = ">>"/>
</form>
<?php print("$output"); ?>
</body>
</html>
The mysqli_query does need 2 parameters, as the PHP api shows with the procedural form that you have.
So, for that part, the call should look like this:
$query = mysqli_query($connection, "SELECT * from employee WHERE fname LIKE
'%$searchq%' OR"
. "lname LIKE '%$searchq%") or die("failed");
However, there will be trouble with the query. Note this portion of the query:
'%$searchq%' OR" <--- No space after the OR
. "lname LIKE '%$searchq%")
^--- No space before lname
Either one of the those 2 areas needs a space.
That last part of the query string will ultimately look like this:
'%$searchq%' ORlname LIKE '%$searchq%
^--- trouble (no space) ^---and trouble here (missing a closing single quote)
Sometimes it is useful to set the query separately, so that you can echo it out to check that it is syntactically correct as far as spacing around keywords, columns, values, comma usage (when needed), proper quoting, etc.
Consider this difference:
$query = "SELECT * from employee WHERE fname LIKE '%$searchq%' OR "
. "lname LIKE '%$searchq%'";
// query check (delete after validation, or comment-out)
echo $query;
$result = mysqli_query($connection, $query);
// I like to use $result, as the query call will return a result set with SELECT
// or false with failure. (though it can return true for other query types, see the api link)
It can also helpful to output the error as part of the die message:
if (!$result) { // Doh! something wrong...
die('failed: ' . mysqli_error($connection));
} else {
$count = mysqli_num_rows($result); // check the result count
if ($count == 0) {
$output = 'No search results';
} else {
while ($row = mysqli_fetch_array($result)) { // fetch a row
$firstname = $row['fname'];
$lastname = $row['lname'];
$id = $row['id'];
$output .= '<div>' . $firstname . '' . $lname . '</div>';
echo "hi";
}
}
}
HTH

Put results in different divs depending on what comes out of the database?

How it looks:
https://jsfiddle.net/jef2L8m6/
How it should look:
https://jsfiddle.net/jef2L8m6/1/
I know it looks really bad, this is just for testing purposes only.
Some of the Backend Code:
<?php //Selects all of the logged in users messages.
$name = $_SESSION["name"];
$con = mysqli_connect('localhost','root','','chat');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM `chat` ORDER BY date";
$result = mysqli_query($con,$sql);
$numrows = mysqli_num_rows($result);
if( $numrows == "0" or !isset($_SESSION["name"])){
echo "<div class='msg'>You are not registered (Or there are no messages to display)</div>";
exit();
}else{
echo "";
}
echo "<div class='msg_container'>";
while($row = mysqli_fetch_array($result)) {
echo "<div class='msg_user'>";
echo "<div class='username_user'><span>" . $row['username'] . "</span></div>";
echo "<div class='message_user'><span>" . $row['message'] . "</span></div>";
echo "</div>";
}
echo "";
mysqli_close($con);
?>
Thank you so much for taking your time to read this.
I am trying to figure out how I would change the div tags of each separate user depending on their name?
Is there any way to do this using PHP, I have tried doing 2 separate query's of one that selects just the users messages and another that selects everyones (excluding the users)
But none of them worked due to it not ordering them correctly.
Could I somehow change the div's using PHP if the username that comes out is not equal to the username in the session?
Thank's so much, if you don't think I explained this very well please give me some feedback and I will change/add what you need, THANK YOU!
Thank you so much "u_mulder", you have been very helpful in making me think of a simple way to solve this problem.
I was thinking way too complex for something so simple!
Here is the final code for anyone who this may help:
while($row = mysqli_fetch_array($result)) {
$class_msg = "msg";
$class_username = "username";
$class_message = "message";
if ($row['username'] == $_SESSION['name']) {
$class_msg = "msg_user";
$class_username = "username_user";
$class_message = "message_user";
}
echo "<div class='$class_msg'>";
echo "<div class='$class_username'><span>" . $row['username'] . "</span></div>";
echo "<div class='$class_message'><span>" . $row['message'] . "</span></div>";
echo "</div>";
}
while($row = mysqli_fetch_array($result)) {
$class = 'msg';
if ($row['username'] == $_SESSION['name']) {
$class = 'msg_user';
}
echo "<div class='" . $class . "'>";
// other codes here
}

Passing two php variables to another page from a link

Ok so I'm building a simple question/answer site and this is a loop that outputs all the questions asked previously in link form. I'm trying to concat two variables to the next page url so I can get them and work with them there but it will only allow one? I've tried everything but not working? See the only comment section of my code for the crux of the issue. Thank you.
<?php
$servername = "127.0.0.1";
$username = "dylan326";
$password = "";
$dbname = "questions87";
$port = 3306;
$conn = mysqli_connect($servername, $username, $password, $dbname,
$port);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "<a href='index.html'> Log out </a><br>
<a href='ask.php'> Ask a question</a><br>
<br />
<br />";
echo "Answer another users question: <br><br />";
$sql = "SELECT q_id,question, username FROM questions";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result))
{
$q_id = $row['q_id'];
$question = $row['question'];
$username = $row['username'];
//right here I need to add(concat) the second variable $username
//I need to get both on the next page url but not allowing me to
echo ('<a href="totalqs.php?q_id=' . $q_id .' " >' . $question .
'</a>' . '<br>');
}
} else {
echo "0 results";
}
mysqli_close($conn);
?>
Try this (assuming that $username has a value):
echo ('<a href="totalqs.php?q_id=' . $q_id .' " >' . $question . " Username:" . $username . '</a>' . '<br>');
It looks like you're doing HTTP GET so instead of trying to concat 2 strings, why not just have something like
totalqs.php?q_id=$q_id&question=$question&username=$username
Then in the totalqs.php, you'll do something like
$q_id = $_GET['q_id'];
$question = $_GET['question'];
$username = $_GET['username'];
This is assuming you have access to totalqs.php.
You can send to variables by adding the & and then continuing to add values.
Example
example.php?one=value&second=value
In your case
totalqs.php?q_id=$q_id&username=$username
Use this code in your echo statement. This concatenates your second value $username with name user:
echo ''.$question.'<br />';
Note that you do not need parentheses in your echo statement. You need to properly concatenate your string (you need to learn more about concatenation). In the next page, you can access q_id and user as
$id = $_GET['q_id'];
$username = $_GET['user'];
Get requests can pass multiple variables for example: {host}?var1=val1&var2=val2&var2=val3
You could echo out a link with a get request in it:
echo ('<a href="totalqs.php?q_id=' . $q_id .'&username='. $username .'" >' . $question .'</a>' . '<br>');
And then, you could use $_GET to retrieve these vars in totalqs.php. Like:
$_GET['username']
would give you the value of the username.

link to specific user profile php

I'm creating a search bar feature on my website where the user can search for users using a name.The search result may come up with multiple users with similar names (ex. if I search "Jenna", my database may have multiple users with the name "Jenna" so multiple results will show).I want the user to be able to click on one of the profiles and see that specific "Jenna's" user profile. Kind of like Twitter, where I can search for accounts and view different profiles. Right now I have code that returns the search and also makes the search result a clickable link. However, when I try to save the user id, it only saves the latest user id.
home.php (where the search bar for users is0
<form method="GET" action="search.php" id="searchform">
Search for users:
<input type="text" name="search_user" placeholder="Enter username">
<input type="submit" name="submit" value="Search">
</form>
search.php (prints out the users with the name that the user is searching for)
session_start();
$user = '';
$password = '';
$db = 'userAccounts';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect($host, $user, $password, $db);
mysqli_query($link,"GRANT ALL ON comment_schema TO 'oviya'#'localhost'");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$search_user = $_GET['search_user'];
$sql = "SELECT * FROM users WHERE username LIKE '%$search_user%'";
$result = mysqli_query($link, $sql);
if(mysqli_num_rows($result)>0){
while ($row = mysqli_fetch_assoc($result)) {
$a = '<a';
$b = ' href="';
$c = 'user_profiles.php';
$d = '">';
$e = $row['username'];
$f = '</a';
$g = '>';
$_SESSION['user'] = $row['user_id'];
$userID = $_SESSION['user'];
echo $a.$b.$c.$d.$e.$f.$g;
header("Location: user_profiles.php");
}
}
user_profiles.php (supposed to be where a specific user's profile is shown, based on the link the user clicks with the specific userID)
session_start();
$userID=$_SESSION['user'];
$link = mysqli_connect('localhost', 'x', '', 'userAccounts');
$query="SELECT * FROM dataTable WHERE user_id='$userID'";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="output" >';
$entry_id = $row["entry_id"];
$output= $row["activity"];
echo "Activity: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
$output= $row["duration"];
echo "Duration: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')." hrs"."<br>"."<br>";
$output= $row["date_"];
echo "Date: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
echo '</div>';
}
I get where my mistake is, the while loop in search.php will only save the latest userID so the link will always take me to the user profile with that useriD. I'm just not sure how to implement it so that when the user views the list of profiles, the link they click will take them to a specific profile based on the user id.
You need to do changes in search and user.php files :
Search.php :
<?php
session_start();
$user = '';
$password = '';
$db = 'userAccounts';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect($host, $user, $password, $db);
mysqli_query($link, "GRANT ALL ON comment_schema TO 'oviya'#'localhost'");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$search_user = $_GET['search_user'];
$sql = "SELECT * FROM users WHERE username LIKE '%$search_user%'";
$result = mysqli_query($link, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$id = $row['user_id'];
?>
<a href="user_profiles.php?id=<?php echo $id; ?>" >
<?php echo $row['username']; ?>
</a>
<?php
$_SESSION['user'] = $row['user_id'];
$userID = $_SESSION['user'];
header("Location: user_profiles.php");
}
}
User_profile.php:
$userid = $_GET['id'];
$link = mysqli_connect('localhost', 'x', '', 'userAccounts');
$query = "SELECT * FROM dataTable WHERE user_id='$userid'";
$results = mysqli_query($link, $query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="output" >';
$entry_id = $row["entry_id"];
$output = $row["activity"];
echo "Activity: ";
echo htmlspecialchars($output, ENT_QUOTES, 'UTF-8') . "<br>" . "<br>";
$output = $row["duration"];
echo "Duration: ";
echo htmlspecialchars($output, ENT_QUOTES, 'UTF-8') . " hrs" . "<br>" . "<br>";
$output = $row["date_"];
echo "Date: ";
echo htmlspecialchars($output, ENT_QUOTES, 'UTF-8') . "<br>" . "<br>";
echo '</div>';
}
Very first thing, you are saving multiple user ids to a string.
Another thing, you are saving it in while loop.
Therefore, latest value updates old value.
In your case, it will always save the last value. That is prime issue.
You can take array of user ids and save them in it.
$userIds = array();
while ($row = mysqli_fetch_assoc($result)) {
$a = '<a';
$b = ' href="';
$c = 'user_profiles.php';
$d = '">';
$e = $row['username'];
$f = '</a';
$g = '>';
$userIds[] = $row['user_id'];
$userID = $_SESSION['user'];
echo $a.$b.$c.$d.$e.$f.$g;
header("Location: user_profiles.php");
}
$_SESSION['user'] = $userIds;
And in your user_profiles.php, loop over the array or use MySQL IN() condition to get all user profiles.
Also, why did you take too many variables for html link. You can do it in single variable using concatenation like following:
$userIds = array();
while ($row = mysqli_fetch_assoc($result)) {
$a = '<a'
. ' href="';
. 'user_profiles.php';
. '">';
. $row['username'];
. '</a';
. '>';
$userIds[] = $row['user_id'];
$userID = $_SESSION['user'];
echo $a;
header("Location: user_profiles.php");
}
$_SESSION['user'] = $userIds;
Another mistake is that you are echo ing HTML link and doing redirection.
That will cause headers already sent... error.
This will display list of users with searched string
if(mysqli_num_rows($result)>0){
while ($row = mysqli_fetch_assoc($result)) {
$link="<a href='user_profiles.php?user_id=".$row['user_id']."'>".$row['username']."</a>";
}
}
After clicking on link it will redirect to user_profiles.php (no need to header. header is used for automatic redirection)
In user_profiles.php
session_start();
$userID=$_GET['user_id'];
$link = mysqli_connect('localhost', 'x', '', 'userAccounts');
$query="SELECT * FROM dataTable WHERE user_id='$userID'";
$results = mysqli_query($link,$query);
while ($row = mysqli_fetch_assoc($results)) {
echo '<div class="output" >';
$entry_id = $row["entry_id"];
$output= $row["activity"];
echo "Activity: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
$output= $row["duration"];
echo "Duration: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')." hrs"."<br>"."<br>";
$output= $row["date_"];
echo "Date: ";
echo htmlspecialchars($output ,ENT_QUOTES,'UTF-8')."<br>"."<br>";
echo '</div>';
}

Categories