I'm trying to create a SQL query that takes the values of an entire table and dumps them into an array that I can call based the value of a URL parameter.
The parameter passed into the url will be ?username=User1.
I need the query to filter results in the database that are related to the that user (for example - their name, email address, interests etc).
I want to then be able to store them in an array that I can use to call and display the values, for example;
<?php echo htmlentities($row['profiles']['username'], ENT_QUOTES, 'UTF-8'); ?>
<?php echo htmlentities($row['profiles']['location_city'], ENT_QUOTES, 'UTF-8'); ?>
I use the following PHP to set the $u variable in PHP
My SQL query so far is as follows
$query = "
SELECT
user_id,
username,
displayname,
displayage,
location_city,
language
FROM profiles WHERE username='$u'
";
I then use the following PHP code to try and pass the data into an array;
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
My full code for profile.php;
<?php $_GET['u'] = 'u'; ?>
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: index.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to index.php");
}
// Everything below this point in the file is secured by the login system
// We can retrieve a list of members from the database using a SELECT query.
// In this case we do not have a WHERE clause because we want to select all
// of the rows from the database table.
$query = "
SELECT
id,
username,
email
FROM profiles WHERE username='$u'
";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll();
?>
<?php include('header.php') ?>
<div class="pages navbar-through toolbar-through">
<div class="page" data-page="profile">
<div class="page-content">
<div class="content-block">
<div class="content-block-inner">
<p>Profile content will go here</p>
Go Back<br />
</div>
</div>
</div>
</div>
</div>
<?php include('footer.php') ?>
Change profile.php file contents as shown below:
<?php $username = (isset($_GET['username']))? trim(strip_tags($_GET['username'])) : ""; ?>
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// At the top of the page we check to see whether the user is logged in or not
if(empty($_SESSION['user']))
{
// If they are not, we redirect them to the login page.
header("Location: index.php");
// Remember that this die statement is absolutely critical. Without it,
// people can view your members-only content without logging in.
die("Redirecting to index.php");
}
// Everything below this point in the file is secured by the login system
// We can retrieve a list of members from the database using a SELECT query.
// In this case we do not have a WHERE clause because we want to select all
// of the rows from the database table.
$query = "
SELECT
user_id,
username,
displayname,
displayage,
location_city,
language
FROM profiles WHERE username = '$username'
";
try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query: " . $ex->getMessage());
}
// Finally, we can retrieve all of the found rows into an array using fetchAll
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<?php include('header.php') ?>
<div class="pages navbar-through toolbar-through">
<div class="page" data-page="profile">
<div class="page-content">
<div class="content-block">
<div class="content-block-inner">
<p>Profile content will go here</p>
<?php foreach($rows as $row): ?>
<div>Username: <?php echo $row['username'] ?></div>
<div>Location: <?php echo $row['location_city'] ?></div>
<?php endforeach; ?>
Go Back<br />
</div>
</div>
</div>
</div>
</div>
<?php include('footer.php') ?>
Related
I'm trying to make login system by a tutorial. I'm making everything like in tutorial but it says my details are incorrect and it wont log me in but everything is correct. I can't find is there anywhere mistake in code or something. Any help is welcome!
Index.php code:
<?php #admin/index.php
#####[make sure you put this code before any html output]#####
//connect to server
$dbc = mysqli_connect('localhost','root','pw') or
die('could not connect: '. mysqli_connect_error());
//select db
mysqli_select_db($dbc, 'dbname') or die('no db connection');
//check if the login form has been submitted
if(isset($_POST['go'])){
#####form submitted, check data...#####
//step 1a: sanitise and store data into vars (storing encrypted password)
$usr = mysqli_real_escape_string($dbc, htmlentities($_POST['u_name']));
$psw = SHA1($_POST['u_pass']) ; //using SHA1() to encrypt passwords
//step2: create query to check if username and password match
$q = "SELECT * FROM kasutaja WHERE name='$usr' AND pass='$psw' ";
//step3: run the query and store result
$res = mysqli_query($dbc, $q);
//make sure we have a positive result
if(mysqli_num_rows($res) == 1){
######### LOGGING IN ##########
//starting a session
session_start();
//creating a log SESSION VARIABLE that will persist through pages
$_SESSION['log'] = 'in';
//redirecting to restricted page
header('location:restricted.php');
} else {
//create an error message
$error = 'Wrong details. Please try again';
}
}//end isset go
?>
<!-- HTML FORM GOES HERE -->
<!-- LOGIN FORM in: admin/index.php -->
<form method="post" action="#">
<p><label for="u_name">username:</label></p>
<p><input type="text" name="u_name" value=""></p>
<p><label for="u_pass">password:</label></p>
<p><input type="password" name="u_pass" value=""></p>
<p><button type="submit" name="go">log me in</button></p>
</form>
<!-- A paragraph to display eventual errors -->
<p><strong><?php if(isset($error)){echo $error;} ?></strong></p>
Restricted page code:
<?php #admin/restricted.php
#####[make sure you put this code before any html output]#####
//starting the session
session_start();
//checking if a log SESSION VARIABLE has been set
if( !isset($_SESSION['log']) || ($_SESSION['log'] != 'in') ){
//if the user is not allowed, display a message and a link to go back to login page
echo "You are not allowed. back to login page";
//then abort the script
exit();
}
/**
* #### CODE FOR LOG OUT #### click here to see the logout tutorial
*/
?>
<!-- RESTRICTED PAGE HTML GOES HERE -->
<h1> TEST </h1>
Thanks for helping!
This is a fix for http://www.cramerz.com/php/php_login_system which contains errors that the OP downloaded from the Web. No wonder the OP had a hard time.
It queries the wrong columns for one thing and inserts into the wrong table.
Another error with their code is this line:
echo "You are not allowed. back to login page";
which would throw an error and should read as, and escaping the quotes for index.php
echo "You are not allowed. back to login page";
Rewrite
Most of the Websites have a sort of private section where normal users are not allowed. You can think about an ADMIN section where the webmaster finds his CMS, a private area with sensitive personal information or even just the email manager you use to handle your emails.
All of these cases have something in common: they restrict access to allowed users only, with a login system.
To create an authentication system you will need:
A database, a table called users with at least three columns: id, username, password
A HTML form where users fill in their usernames and passwords
A PHP script that will check if usernames and passwords provided actually exist
A private area users can access only if successfully logged in
STEP 1. create a table called users:
a) Use PhpMyAdmin or any other GUI to quickly create a table
CREATE TABLE `users` (
`id` INT( 5 ) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 50 ) NOT NULL ,
`password` VARCHAR( 50 ) NOT NULL
)
b) Insert a couple of users:
INSERT INTO `users`
( `id` , `username` , `password` )
VALUES ( NULL , 'john', SHA1('johnPsw' ) ),
( NULL , 'james', SHA1('jamesPsw') ),
( NULL , 'jim', SHA1('jimPsw' ) );
PLEASE NOTE: we are using the SHA1() function to encrypt passwords.
STEP 2. login form:
<!-- LOGIN FORM in: admin/index.php -->
<form method="post" action="">
<p><label for="u_name">username:</label></p>
<p><input type="text" name="u_name" value=""></p>
<p><label for="u_pass">password:</label></p>
<p><input type="password" name="u_pass" value=""></p>
<p><button type="submit" name="go">log me in</button></p>
</form>
<!-- A paragraph to display eventual errors -->
<p><strong><?php if(isset($error)){echo $error;} ?></strong></p>
STEP 3. php script:
<?php #admin/index.php
#####[make sure you put this code before any html output]#####
//connect to server
$dbc = mysqli_connect('localhost','root','') or
die('could not connect: '. mysqli_connect_error());
//select db
mysqli_select_db($dbc, 'examples') or die('no db connection');
//check if the login form has been submitted
if(isset($_POST['go'])){
#####form submitted, check data...#####
//step 1a: sanitise and store data into vars (storing encrypted password)
$usr = mysqli_real_escape_string($dbc, htmlentities($_POST['u_name']));
$psw = SHA1($_POST['u_pass']) ; //using SHA1() to encrypt passwords
//step2: create query to check if username and password match
$q = "SELECT * FROM users WHERE username='$usr' AND password='$psw' ";
//step3: run the query and store result
$res = mysqli_query($dbc, $q);
//make sure we have a positive result
if(mysqli_num_rows($res) == 1){
######### LOGGING IN ##########
//starting a session
session_start();
//creating a log SESSION VARIABLE that will persist through pages
$_SESSION['log'] = 'in';
//redirecting to restricted page
header('location:restricted.php');
} else {
//create an error message
$error = 'Wrong details. Please try again';
}
}//end isset go
?>
<!-- HTML FORM GOES HERE -->
STEP 4. restricted page:
<?php #admin/restricted.php
#####[make sure you put this code before any html output]#####
//starting the session
session_start();
//checking if a log SESSION VARIABLE has been set
if( !isset($_SESSION['log']) || ($_SESSION['log'] != 'in') ){
//if the user is not allowed, display a message and a link to go back to login page
echo "You are not allowed. back to login page";
//then abort the script
exit();
}
else{
echo "Success!";
}
/**
* #### CODE FOR LOG OUT #### click here to see the logout tutorial
*/
?>
<!-- RESTRICTED PAGE HTML GOES HERE -->
I created a PHP form which allows users to Register and Log in. Now I created another page named View.php that will show all the registered users in my MySQL database. The code I used was
while($row=mysqli_fetch_assoc($sql))...
and it displayed all the users successfully.
Now I created another PHP page which I named profile.php. I want to add a link from every result on view.php which will redirect to profile.php?user=(their username). But I don't know how.
In this line:
echo "<small><a href = 'profile.php?user=$them'>[View Profile]</a></small><br/>";
instead of using your fixed $them, just use $row['id']. Then you can fetch the user with that id in your profile.php file:
$id = $_GET['user'];
$sql = "SELECT * FROM users where id = $id";
Note that this code is prone to sql injection. I only posted it to make the idea easier to understand. See here how to do it right.
I do not know the code you are using to achieve the result but having something like :
$query = "SELECT * FROM database WHERE id=$id";
$query = mysql_query($query);
This will filter out the profile page according to the user id
In your view.php considering that you have a column named 'username' , change the following :
please not, it's preferably to put the ID column If you want to put the id column, simply change the $row['username'] to $row['id'] and the same in the query in profile.php
<?php
...
while($row=mysqli_fetch_assoc($result)) {
echo "---------------------<br/>";
echo "<b>".$row['fullname']."</b><br/>";
echo "<small><i>".$row['course']."</i></small><br/>";
echo "<small><a href = 'friends.php?user=".$row['username']."'>[View Profile]</a></small><br/>";
echo "---------------------<br/><br/>";
}
?>
And in your
profile.php
<?php session_start();
if($_SESSION['logged_in']==false) {
header("Location:login.php");
}
include("header.php");
?>
<html>
<head>
<title>View School-Mates</title>
</head>
<body>
<center>
<h1>My School-Mates</h1>
<small>View or Add them in your Trust List</small>
<br/><br/>
<hr>
</center>
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test_basic', "root", "");
$stmt = $dbh->prepare("SELECT * FROM USERS WHERE username= ?");
if ($stmt->execute(array($_GET['user']))) {
while ($row = $stmt->fetch()) {
//here you will have your row with all your username data
}
}
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
</body>
</html>
Please read more about PDO from here and how to do connections this is required because you get data from your $_GET variable, and thus you need to avoid for sql injection
Hopefully this is what you wanted, if not, please let me know so i can adjust the code
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 am new to PHP and just wanting to make a basic page where i can see all the users in the database and delete them. I have come this far but it keeps on telling me that I have an i have and Undefined index: user_id and although it tells me that it has deleted the fields it has not deleted anything. Here is my code:
<?php include_once "includes/scripts.php"; ?>
<?php include_once "includes/connect.php";?>
<?php include_once "includes/cms_page_security.php";?>
<div id="cms_container"><br>
<br>
<h1>MANAGE USERS<img src="images/three_column_grid_line.png" alt="line"></h1>
<p class="logout_btn">Back</p>
<?php
$tbl="users"; // Table name
$sql = "SELECT * FROM $tbl";
$result = mysql_query($sql, $connect);
while($rows = mysql_fetch_array($result)){
?>
<?php
echo $rows['user_id'];
echo $rows['user_name'];
echo $rows['user_password'];
?>
delete
<?php
}
?>
<?php
mysql_close();
?>
</div><!--cms_container-->
</body>
</html>
The page that it should link to that deletes the query:
<?php include_once "includes/connect.php";?>
<?php
$tbl="users";
$user_id= $_GET ['user_id'];
$sql="DELETE FROM $tbl WHERE user_id = '$user_id'";
$result = mysql_query($sql, $connect);
if($result){
echo "Deleted Successfully";
echo "<BR>";
echo "<a href='delete.php'>Back to main page</a>";
}else {
echo "ERROR";
}
?>
<?php
mysql_close();
?>
In delete_user.php you must get user_id
$user_id= $_GET ['id'];
because in your delete link GET variable is "id", not "user_id"
You really should be using PDO instead.
The issue is in the information that you are passing.
The link : delete
is looking for an 'id' but you're later looking for 'user_id'
If you change it to delete, it should work.
I still strongly suggest you look into PDO instead though, it's much more secure and easier to work with.
Example of PDO Delete
public function deleteUser($username, $user_id){
if($this->isAdmin($username) == true){
$query = $this->db->prepare('DELETE FROM users WHERE user_id = ?');
$query->bindValue(1, $user_id);
try{
$query->execute();
}catch(PDOException $e){
die($e->getMessage());
}
}else{
return false;
}
}
I'm running an extra check to make sure the person who is requesting the deletion is an admin member but you should be able to see the structure
In addition to the other answers:
It looks like this line could be a fatal error, if php short tags aren't enabled:
delete
The php manual says:
*PHP also allows for short tags <? and ?>
(which are discouraged because they are only available if enabled with
short_open_tag php.ini configuration file directive, or if PHP was configured
with the--enable-short-tags option.*
http://php.net/manual/en/language.basic-syntax.phptags.php
The SQL query will be successful even if it alters zero rows. You are prefixing your user ids with a space when you are generating your HTML (id= <?), so you aren't matching any rows (since "1" won't be matched by " 1").
Where you are creating your 'Delete' link
delete
You're creating a variable of 'id', but later you look for 'user_id.
Change your link to
delete
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.