I am having a problem trying to display the username on the profile page from the $_GET, the session is created but unable to display the username on the profile page.
<?php include("template/header.php");
include("requires/connection.php"); ?>
<?php
if(isset($_GET['u'])) {
$username = mysqli_real_escape_string($_GET['u']);
if(ctype_alnum($username)) {
// Check user exists
$check = mysqli_query("SELECT username FROM users WHERE username='$username'");
if(mysqli_num_rows($check)===1) {
$get = mysqli_fetch_assoc($check);
$username = $get['username'];
}
else {
echo "<h2>User doesn't exist</h2>";
exit();
}
}
}
?>
<div class="profile-content-container">
<h1>Profile <?php echo "$username"; ?></h1>
<p>Welcome</p>
</div><!-- end of profile-content-container -->
<div class="profileMenu">
<div id="leftsideMenu">
<ul>
<li>Home</li>
<li>My Profile</li>
<li></li>
<li></li>
<li>Logout</li>
</ul><!-- end of menu -->
</div><!-- end of leftsideMenu -->
</div><!-- end of profileMenu -->
<?php include("template/footer.php"); ?>
Both mysqli_real_escape_string() and mysqli_query() functions require that the DB connection be passed as the first parameter; yours doesn't have that.
mysqli_real_escape_string($con, $_GET['u'])
^^^^^ see that?
so...
$username = mysqli_real_escape_string($con, $_GET['u']);
^^^^^ add the db connection variable
and for the query
mysqli_query($con, "SELECT ...
^^^^^ see that?
I used $con here, because there is no indication as to which variable you are using to assign the connection to.
References:
http://php.net/manual/en/mysqli.query.php
http://php.net/manual/en/mysqli.real-escape-string.php
Sidenote: You may want to change this
if(mysqli_num_rows($check)===1)
to
if(mysqli_num_rows($check) >0 )
where I seen in some case that ===1 failed.
Another thing, changing this block of code
$get = mysqli_fetch_assoc($check);
$username = $get['username'];
to, and using a while loop
while($get = mysqli_fetch_assoc($check)){
// or mysqli_fetch_array
$username = $get['username'];
}
Plus, your DB connection should be mysqli_ based and not mysql_ or PDO, which is also unknownst to us.
Those different MySQL APIs do not intermix.
References:
http://php.net/manual/en/function.mysqli-connect.php
http://php.net/manual/en/mysqlinfo.api.choosing.php
Add or die(mysqli_error($con)) to mysqli_query() to check for errors.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
Your code shows a GET array; without knowing where that is populated from, make sure it's set and not empty.
If using a form, then make sure that a POST method isn't implied.
If your form is using a POST method, then you should be using POST and not GET. Make sure the element has a "name" attribute, IF you're using form.
Also unknownst to us.
Again, if you're using a form with a POST method, or whatever, make sure there is a name attribute for it.
I.e.:
<input type="text" name="u">
Edit:
This part will throw an undefined variable notice:
<h1>Profile <?php echo "$username"; ?></h1>
So, use a conditional statement for it:
<h1>Profile
<?php
if(isset($username) && !empty($username)) {
echo $username;
}
else{
echo "Username is empty or not set somewhere.";
}
?>
</h1>
or use a ternary operator
<h1>Profile <?php echo $username ? $username : ""; ?></h1>
or
<h1>Profile <?php echo $username ? $username : "It is empty"; ?></h1>
or
<h1>Profile <?php echo !empty($_GET['u']) ? $_GET['u'] : ""; ?></h1>
or
<h1>Profile <?php echo !empty($_GET['u']) ? $_GET['u'] : "It is empty."; ?></h1>
As you stated in comments, you are using ?u="username" which should read without quotes ?u=username or as an example ?u=john no quotes and may be case sensitive. So john may not be the same as John with an uppercase "J".
Related
How do I echo a user's name and his specific country? Like this:
Account name: leo
Country: Germany
The account name is working.
PHP at the top of the page is:
<?php
session_start();
if (!isset($_SESSION['username'])) {
$_SESSION['msg'] = "You must log in first";
header('location: login.php');
}
if (isset($_GET['logout'])) {
session_destroy();
unset($_SESSION['username']);
header("location: login.php");
}
?>
Connect to database (seperate file server.php):
$db = mysqli_connect('localhost', 'root', '', 'registration');
HTML:
<li class="p-li">Account name: <?php echo $_SESSION['username']; ?></li>
<li class="p-li">Country:<?php echo $_a['a']; ?> </li>
You need to define $_a at the moment it doesn't appear to be referencing anything so would be blank. Forgetting that though you asked about SQL query in the comments.
SQL Query would be
$id = $_SESSION['username'];
"SELECT Country FROM registration WHERE username='%".id."%'"
Please be aware that's just a snippet of code as you said you wanted the SQL query. I defined $id as the users username as you said you wanted to get country by username, I would though recommend you use the id column of the table as this will always be unique.
Why can'user information doesn't appear? do i need to specify something in login.php?
please help
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
session_start();
$username=$_SESSION['username'];
$qry = "SELECT * FROM users WHERE username='$username'";
$result=mysqli_query($con,$qry);
$row=mysqli_fetch_assoc($result);
$login_session=$row['username'];
$facebook=$row['facebook'];
$name=$row['name'];
$email=$row['email'];
?>
<p><?php echo $facebook ?></p>
<p><?php echo $username ?></p>
<p><?php echo $email ?></p>
<p><?php echo $password ?></p>
and here is my login php Below I think there's problem with Session starting
<?php
session_start();
error_reporting(E_ALL); // check all type of error
ini_set('display_errors',1); // display those errors
require 'db.php' ;
if(!empty($_POST['username']) && !empty($_POST['password'])){ // check with posetd value
$user_name = $_POST['username'];
$password = md5($_POST['password']);
$query = "SELECT * FROM users where username='$user_name' and password = '$password'"; // don't use plain password, use password hashing mechanism
$result = mysqli_query($con,$query); // run the query
if(mysqli_num_rows($result)==1){ // if data comes
$_SESSION['username']=$username;
header('location:profile.php'); // go to other page
}else{
echo "Login creadentials are not correct"; // else no user is there with the given credentials
}
}
?>
<?php
include 'Session.php';
?>
End of code here
The problem is in this: (look at the variables in ^^^^^^^^^).
$user_name = $_POST['username'];
^^^^^^^^^^
$password = md5($_POST['password']);
$query = "SELECT * FROM users where ... '$password'";
$result = mysqli_query($con,$query); // run the query
if(mysqli_num_rows($result)==1){ // if data comes
$_SESSION['username']=$username;
^^^^^^^^^
You assigned the $user_name variable to the $_POST['username'] array, yet you assigned the $_SESSION['username'] session array to the $username variable.
That should have read as:
$_SESSION['username']=$user_name;
What you should have done was to check if the session was set/not empty in an if/else conditional statement.
Make sure that the form does have the same name attribute for the POST array.
Note:
You should add an exit; after the header:
header('location:profile.php');
exit;
Otherwise, your code may want to continue executing below it.
Additional notes.
Your code is open to an SQL injection; please use a prepared statement:
https://en.wikipedia.org/wiki/Prepared_statement
You should also look into hashing passwords safely using password_hash() instead of MD5 since that function is no longer considered safe to use in this day and age:
http://php.net/manual/en/function.password-hash.php
Note: If and when you do decide to switch to password_hash(), make sure the (password) column is long enough to hold the hash, 60+ / or better; 255.
I am working on a comment system & I created a page that admins can be able to delete comments. I have coded everything & it seems to be right but I don't know why it's not working at all...
Here's the code to the admins page:
<html>
<head>
<title>Admins Page</title>
</head>
<body>
<?php
function getCM(){
global $con;
$get_comment = "select * from product_comments where type='0'";
$run_comment = mysqli_query($con, $get_comment);
while($row_comment = mysqli_fetch_array($run_comment)){
$cmid = $row_comment["id"];
$cmcode = $row_comment["productcode"];
$cmemail = $row_comment["email"];
$cmname= $row_comment["name"];
$cmcomment = $row_comment["comment"];
$cmdate = $row_comment["modified_date"];
$cmtime = $row_comment["modified_time"];
$cmtype = $row_comment["type"];
echo "
<div class='container'>
<div id='table' class='table-editable'>
<span class='table-add glyphicon glyphicon-plus'></span>
<table class='table'>
<tr>
<th>Comment ID #$cmid</th>
</tr>
<tr>
<td contenteditable='true'>$cmcomment</td>
<td>
<span class='table-remove glyphicon glyphicon-remove'></span>
</td>
<td>
<a href='delete.php?id=$cmid'>Delete</a>
</td>
</tr>
</div>
";
}
}
?>
</body>
</html>
And here's the code to delete.php page:
<?php
session_start();
if (!isset($_SESSION["manager"])) {
header("location: admin_login.php");
exit();
}
require '../php_includes/init/db_conx.php';
require '../functions/func.php';
if (isset($_GET['cmid'])){
$comment_id = $_GET['cmid'];
mysqli_query("DELETE FROM product_comments WHERE id='$comment_id'") or die(mysql_error());
echo "<script>alert('Comment has been deleted!')</script>";
header("Location: product_comments.php");
}
?>
Please if you know what's my problem please let me know that...
There are a few things wrong here.
You didn't connect to your query mysqli_query("DELETE...
That function requires a database connection parameter be passed.
Consult: http://php.net/manual/en/mysqli.query.php
Then mysql_error() that mysql_ function does not mix with anything other than its own API, use mysqli_error($con), assuming a successful connection with mysqli_ and $con as its variable.
Consult: http://php.net/manual/en/function.mysqli-connect.php
Your present code is open to SQL injection. Use mysqli_* with prepared statements, or PDO with prepared statements.
On the PHP side:
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
// rest of your code
Sidenote: Displaying errors should only be done in staging, and never production.
should there be errors elsewhere in your code.
which there is, in this part of your code:
echo "<script>alert('Comment has been deleted!')</script>";
header("Location: product_comments.php");
You are outputting before header, and need to remove the echo and adding exit; for the header.
Consult: How to fix "Headers already sent" error in PHP
Then this:
<a href='delete.php?id=$cmid'>Delete</a>
You are using ?id and referencing the $_GET['cmid'] array.
That bit ^ about the "id" is called "Teach a person HOW to fish".
Footnotes:
I have no idea where and how you are calling the getCM() function.
the error you have is
$comment_id = $_GET['cmid'];
change it to this
$comment_id = $_GET['id'];
toexplain whz
<a href='delete.php?id=$cmid'>Delete</a>
U called the cmid not id. hence u need to get id
Sorry if my Title is crappy but I've looked everywhere and i just don't know how to do this.
OK. what i want to do is display information from a specific id from a table row.
first page
employees.php
<?php
require 'header.php';
require 'connect.php';
$sql1 = mysql_query("SELECT * FROM employees ORDER BY id ASC");
while($runrows = mysql_fetch_array($sql1)){
$employename = $runrows["employename"];
$minidescription = $runrows["minidescription"];
$bigdescription = $runrows["bigdescription"];
echo "
<!-- Employe Profile Start -->
<div class='ProfileWrap'>
<section class='Profile'>
<div class='HeadShot'>
<div class='Separator'></div>
<img width='90' height='136' alt='Employe Headshot' class='EmployeImage' src=img/headshots/".$runrows['images'] ." />
<div class='EmployeInfo'>
<legend class='EmployeName'>
<b>
Employe Name: $employename
</b>
</legend>
<div class='EmployeDes'>
<p>
Employe Descript $minidescription...
</p>
</div>
<a href='readmore.php?id=" .$id = $runrows["id"]. "' id='demo' alt='Read More'>
<div class='ReadMore'>
<b>
Read More
</b>
</div>
</a>
</div>
</div>
</section>
</div>
<!-- employe Profile End -->
";
} // close while loop
?>
<?php require 'footer.php'; ?>
second page
employe.php
<?php
require 'header.php';
require 'connect.php';
echo "<a href='index.php'>Back</a>";
$sql2 = mysql_query("SELECT * FROM employees WHERE id=$id");
while($runrows = mysql_fetch_array($sql2)){
$id = $runrows["id"];
$employename = $runrows["employename"];
$minidescription = $runrows["minidescription"];
$bigdescription = $runrows["bigdescription"];
echo "
<legend class='EmployeName'>
<b>
Employe Name: $employename
</b>
</legend>
<div class='EmployeDes'>
<p>
Employe Description: $bigdescription...
</p>
</div>
";
};
require 'footer.php';
?>
and you would click
[Read More]
then it would go to another page called readmore.php
"Click" [Read More] -> readmore.php?id=14 -> display specific info from that id from the database.
username
minidescription
->
click [Read More]
then it would show up like readmore.php?id=14 in the small address bar at the
bottom left
->
new page
->
largedescription
i want to be able to click on an item in a site that has a read more button and have it take me to another page where it displays the description info for that specific id
yes i realize I'm a complete newbie but I'm still learning and that was a crappy example of what i want to accomplish but i hope you understand what I'm trying to do none the less.
sorry if this already exists but I've looked everywhere and couldn't find what i was looking for. If someone has a link to share that can do what I've asked this question can just be deleted.
Thanks in Advance! hope someone can help me figure this out.
First, note #Matthew Johnson's answer about using Mysqli or PDO. Here are a few code specifics, though. When you generate the link to the page, you need this:
<a href='readmore.php?id=" . $runrows["id"] . "' id='demo' alt='Read More'>
Using $id = $runrows["id"] doesn't place the value into the url, it simply declares the value of the $id variable.
Then in your readmore.php file, the id can be capture from the URL using the $_GET array:
if (isset($_GET['id'])) {
$id = $_GET['id'];
}
The mysql_* functions are deprecated, and should no longer be used. Mysqli or PDO should be used, along with prepared statements. The code as you have it is susceptible to sql injection attacks. A simplified version of what you're trying to do would look something like this:
To Link:
//this gets all the name and mini, loops through and displays....
$stmt = $mysqli->prepare("SELECT id, employename, minidescription FROM employees");
$stmt->execute();
$stmt->bind_result($id, $employeename, $minidescription);
while($stmt->fetch()) {
echo "<p><a href='readmore.php?id=$id'>$employeename</a>: $minidescription</p>";
}
The Read More:
//make sure it's set, if so assign it...
$id = (isset($_GET['id']) ? $_GET['id'] : "";
//this gets the info using the id variable from the URL...
$stmt = $mysqli->prepare("SELECT employename, minidescription, bigdescription FROM employees WHERE id = ?");
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->bind_result($employeename, $minidescription, $bigdescription);
$stmt->fetch();
echo "$employeename: $bigdescription";
Using mysqli and prepared statements, as shown here, protects you against bobby tables and sql injection attacks. You can learn more about mysqli from the manual. Here's a tutorial with a quick run through of how prepared statements work.
Edit:
The code above still needs a database connection. The warning of an undefined variable is saying that the $mysqli variable hasn't been defined. The fatal error is due to the fact that the prepare statement failed. To create a connection, it would look similar to this:
define("HOST", "Host URL");
define("USER", "dbUser");
define("PASSWORD", "password");
define("DATABASE", "databaseName");
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
This would replace the code in your connect.php.
i have a list of user reviews that a user can choose to approve or delete.
I have the reviews.php file which lists the pending reviews, a approve_review.php file and a delete_review.php file.
Once the user approves the review i need the mysql column 'approve' to be changed from '0' to '1'. Same applies for the delete but instead of updating 'approve' it will update 'delete'.
Everything i've tried isn't working. please can someone tell me where i'm going wrong. Thanks.
reviews.php:
<?php
$pending_set = get_pending_reviews();
while ($reviews = mysql_fetch_array($pending_set)) {
?>
<div class="prof-content-pend-reviews" id="reviews">
<div class="pend-review-content">
<?php echo "{$reviews['content']}"; ?>
</div>
<div class="approve"></div>
<div class="delete"></div>
</div>
<? } ?>
approve_review.php:
<?php
require_once("session.php");
require_once("functions.php");
require('_config/connection.php');
approve_review ($_GET['review'], $_SESSION['user']);
header('Location: http://localhost/ptb1/reviews.php');
?>
Function:
function approve_review($review_id, $user) {
global $connection;
global $_SESSION;
$query = "UPDATE ptb_reviews
SET approved='1'
WHERE id=$review_id
AND to_user_id=$user";
mysql_query($query, $connection);
}
A parameter is missing to approve_review.php ... its has to be something like this:
<div class="approve"></div>
You have to replace TheID with your php variable.
Greatings!
There are some things wrong here:
You are not actually sending any parameters to your script;
Your script is wide open to sql injection, you should switch to prepared statements in PDO / mysqli.