How to display user data after logged in? - php

I am trying to display information regarding the user after they have logged in. After the user has logged in the user will be redirected to success.php. I use MySQL and a form is an HTML form.
I tried writing the success page in two different ways
success.php (1)
session_start();
if (!isset($_SESSION["loggein"]) || $_SESSION["loggein"] == false) {
include ("getUser.php");
// header("Location: getUser.php");
echo "done";
}
success.php (2)
<?php
session_start();
if (!isset($_SESSION["loggein"]) || $_SESSION["loggein"] == false) {
echo "done";
}
?>
<h2>you have logged in</h2>
<p><?php include ("getUser.php");?></p>
I tried to include a file getUser.php that is suppose to retrive everything regarding the user.
getUser.php
$username = mysqli_real_escape_string($connection, $_REQUEST['username']);
$sql= "select * from userTable where username = '$username'";
if($result = mysqli_query($connection, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<table";
echo "<tr>";
echo "<th>username</th>";
echo "<th>city</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['city'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_free_result($result);
} else{
echo "No user" . mysqli_error($connection);
}
}
I keep getting the "No user" error message from the getUser.php. I do not understand why I get it

In getuser.php you didnt make connection with your database.So add the below line at top of your php document.
$connection = new mysqli("HOST_NAME","USER_NAME","PASSWORD","DATABASE_NAME") or die("Connect failed: %s\n". $connection -> error);

This more than likely will not solve your issue but I believe it could lead you closer or help us better understand what is going on. I can't comment yet so I am posting it here and will continue to help you along until we solve the problem.
Add this to the top of your php documents:
ini_set('display_errors', 1);
ini_set('log_errors',1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
It will write errors to a text document stored on your server to help us debug your issue.

Related

Setup single record MySQL and PHP

How to set a single record to a user profile? For example username, password, email, and wallet. I need to show only date for each user login. This script shows wallet but first user id person and I need to show the user who is logged in.
HTML and PHP:
<?php
$con=mysqli_connect("mysql","root","pass","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT wallet FROM users LIMIT 1");
echo "<table border='0'>
<tr>
<th>wallet</th>
</tr>";
while($record = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $record['wallet'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
To answer you fully.
Start by updating your user table when your users log in by changing the status true or false depending on your implementation.
Also start a session
your code now becomes
<?php
session_start();
$con=mysqli_connect("mysql","root","pass","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Login logics
$res= mysqli_query($con,"SELECT * FROM users where username='user' and password ='pass'");
if($res)
{
$user = mysql_fetch_row($res);
//Keep track of the current logged in user
$_SESSION['user'] = $user['id'];
}
//Now your logic to get wallet or any other thing for the current logged in user
$currentUser = $_SESSION['user'];
$result = mysqli_query($con,"SELECT wallet FROM users where id=".$currentUser.");
echo "<table border='0'>
<tr>
<th>wallet</th>
</tr>";
$record = mysqli_fetch_row($result)
echo "<tr>";
echo "<td>" . $record['wallet'] . "</td>";
echo "</tr>";
echo "</table>";
mysqli_close($con);
?>
Hope this helps..
Work with the Edit you dont need the While loop since you are looking for just a record

Run a MySQL query trough pressing a link and escaping backslash

I have this PHP code below that prints the result of a MySQL query in a HTML table. Furthermore, in the table, I create a link of the result that will be used in another query. Lets take a look at the code:
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "root", "DB1");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
$sql = "SELECT * FROM fileDB";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>filename</th>";
echo "<th>filepath</th>";
echo "<th>size</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td><a href='http://mysecreturl.com/test.php?path=" . $row['filepath'] . "'>" . $row['filename'] . "<a/></td>";
echo "<td>" . $row['filepath'] . "</td>";
echo "<td>" . $row['size'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
This code works as intended, but now comes the problem: I want to implement the following: Once you click on the link, another query should be executed, this one to be specific: SELECT * FROM fileDB WHERE filepath = 'the one sent from the link'. I thought to use something like $_GET["filepath"] from the link to set the filepath in the second query. I have two main problems with this:
I don't know any PHP so I have no idea how clicking a link could run another query and generate a new table with results.
This is important to point out, filepath is a string of a Windows path, therefore it contains backslashes like this: C:\something\something etc. When I query this manually in phpMyAdmin I escape the backslashes by writing C:\\something\\something but when getting my result in the table from the code above, the string filepath will have one pair of backslash of course (as it is saved in the database). How could I then perform my second query if the backslashes apparently need to be escaped?
Any help is very appreciated!
I thought you want to download a file. well this is much simpler:
if (isset($_GET["path"])) {
$stmt = mysqli_prepare($link, "SELECT * FROM fileDB WHERE filepath = ?");
mysqli_stmt_bind_param($stmt, "s", $_GET["path"]);
}else{
$stmt = mysqli_prepare($link, "SELECT * FROM fileDB");
}
mysqli_stmt_execute($stmt);
if ($result = mysqli_stmt_get_result($stmt)) {
if(mysqli_num_rows($result) > 0){
...
oh and one more thing you should escape query component in your URL
echo "<td><a href='http://mysecreturl.com/test.php?path=" . urlencode($row['filepath']) . "'>" . $row['filename'] . "<a/></td>";
Now this could be done using get method like <a href="yourpage.php?path='your_filepath'"> then in your php use this <?php if(isset($_GET['filepath'])){//Run your php query here}?>
You can do something like this:
echo '<tr>
<td><form method="get" action="test.php">
<button type="submit" name="path" value="'.$row['filepath'].'">
'.$row['filename'].'</button>
</form></td>
<td>'.$row['filepath'].'</td>
<td>'.$row['size'].'</td>
</tr>';
Untested, but should in theory work. Why you have the link in the filename-table-cell, instead of in the table-cell with the actual path in it, god knows, but you can test it and see if it works.
I would, however, just make this into a $_POST, unless it's important to show the URI in the address bar.
To answer the first question, you can add variables to a link, e.g. if you want to pass a first name and last name in a link you would do this
<?php
$fname = "John"; // First name
$lname = "Doe"; // Last Name
echo "<a href='next_table.php?fname=$fname&lname=$lname'>Next Table</a>";
?>
Then to retrieve the first name and last name on another page you would use this:
<?php
$fname = $_GET["fname"];
$lname = $_GET["lname"];
?>
Let me know if this helps.
Just an if statement to check whether the filepath is set or not and str_replace function to escape backlashes.
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "root", "DB1");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Attempt select query execution
// Check If filpath is set or not
if(!isset($_GET['filepath']))
{
$sql = "SELECT * FROM fileDB";
}
else
{
$filepath=$_GET['filepath'];
//replace backlashes with double backlashes using str_replace
$filepath=str_replace('\\','\\\/',$filepath);
$sql = "SELECT * FROM fileDB WHERE filepath='$filepath'";
}
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo "<table>";
echo "<tr>";
echo "<th>filename</th>";
echo "<th>filepath</th>";
echo "<th>size</th>";
echo "</tr>";
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo "<td><a href='http://mysecreturl.com/test.php?path=" . $row['filepath'] . "'>" . $row['filename'] . "<a/></td>";
echo "<td>" . $row['filepath'] . "</td>";
echo "<td>" . $row['size'] . "</td>";
echo "</tr>";
}
echo "</table>";
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// Close connection
mysqli_close($link);
?>
Change the code:
// Attempt select query execution
$sql = "SELECT * FROM fileDB";
if($result = mysqli_query($link, $sql)){
To:
// Attempt select query execution
if(isset($_REQUEST['file']) && $_REQUEST['file'] !='') {
$sql = "SELECT * FROM fileDB WHERE `file` = '".$_REQUEST['file']."';";
} else {
$sql = "SELECT * FROM fileDB";
}
if($result = mysqli_query($link, $sql)){
This should convey the basic idea, but take to heart about using parameterized queries.

Data not required is being displayed

I have a form where the user enters data e.g. AXZAA QS1QS. This data is Posted to my PHP script. The PHP Script connects to a MYSQL database which contains at the moment 2 records.
The idea is that the PHP script will take the input and compare it to the records in the database. If the records exist they are displayed in a table on a web page otherwise, an error message is displayed.
I am having a number of problems with my PHP script and have modified my script a number of times. However, the thing I am having the biggest problem with is this:
When the form appears for the first time, the message record doesn't exist appears twice, this is before the user has entered any data and is seeing the form for the first time. See picture below.
After entering data (when the PHP script was partially working correctly), if there is a match i.e. records existed, along with the records in the table I would receive an error message telling me that records were not found. To see if I could resolve the problem I added code to tell me what records could not be found, the records that couldn't be found were the ones that were found and the other records from the database which I wasn't looking for. I know the SQL query in my PHP script tells the script to get everything from the database however, I would have thought the if statement would have fixed the problem.
Sorry about writing such a long problem and I hope it's not confusing.
enter code here
<?php
//Connect to the database connection file
require 'databaseconnection.php';
$searchBar=(isset($_POST['searchBar']) ? $_POST['searchBar'] :null);
$userdata = trim($searchBar);
$cleaned_data = preg_split('/[\s]+/', $userdata);
$sql = "SELECT DISTINCT * FROM atable_2";
$result = mysqli_query($database_connection, $sql);
echo "<table border>
<tr>
<th>Allocation</th>
<th>Codes</th>
<th>Names</th>
</tr>";
while($putdatabaseanswer_intoarray = mysqli_fetch_array($result)) {
$allocation_id = $putdatabaseanswer_intoarray["allocation"];
$codes_id = $putdatabaseanswer_intoarray["codes"];
$names_id = $putdatabaseanswer_intoarray["names"];
foreach($cleaned_data as $value) {
if($value==$codes_id) {
echo "<tr>";
echo "<td>" . $allocation_id. "</td>";
echo "<td>" . $codes_id . "</td>";
echo "<td>" . $names_id . "</td>";
echo "</tr>";
}
else
{
echo "<br />";
echo "One or more of the records have not been found: $codes_id";
echo"<br />";
}
}
}
echo "</table>";
?>
Wouldn't it be better to assign $searchbar after an if statement like
`<?php
//Connect to the database connection file
require 'databaseconnection.php';
if(isset($_POST['searchBar']))
{
$searchbar = $_POST['searchBar'];
$userdata = trim($searchBar);
$cleaned_data = preg_split('/[\s]+/', $userdata);
$sql = "SELECT DISTINCT * FROM atable_2";
$result = mysqli_query($database_connection, $sql);
echo "<table border>
<tr>
<th>Allocation</th>
<th>Codes</th>
<th>Names</th>
</tr>";
while($putdatabaseanswer_intoarray = mysqli_fetch_array($result)) {
$allocation_id = $putdatabaseanswer_intoarray["allocation"];
$codes_id = $putdatabaseanswer_intoarray["codes"];
$names_id = $putdatabaseanswer_intoarray["names"];
foreach($cleaned_data as $value) {
if($value==$codes_id) {
echo "<tr>";
echo "<td>" . $allocation_id. "</td>";
echo "<td>" . $codes_id . "</td>";
echo "<td>" . $names_id . "</td>";
echo "</tr>";
}
else
{
echo "<br />";
echo "One or more of the records have not been found: $codes_id";
echo"<br />";
}
}
}
echo "</table>";
}
else{
echo "<p>Please enter a search term</p>";
}
?>
You could then execute the MySQL query within that "if" statement rather than having it execute assuming there is a value

Show mysqli table

Very basic newbie question please; I've managed to retrieve single fields and pull them through to a webpage; but am really struggling to get my head around what's required to show the contents of a table using mysqli.
I get the sense I'm not using the correct type of loop as I'm only seeing the first record in my table repeating infinitely across the page; so if anyone could provide me with the correct syntax to handle requests of this nature I'd be most grateful.
Many thanks!
<?php
require_once ("functions.php");
require_once ("connection.php");
session_start();
?>
<html>
<head>
<title>My Team</title>
<script src="script.js" type="text/javascript"></script><!-- put it on user area pages -->
</head>
<body>
<h1>My Team</h1>
<hr />
<?php
if (logged_in() == false) {
redirect_to("login.php");
}
else {
if (isset($_GET['User_ID']) && $_GET['User_ID'] != "") {
$id = $_GET['User_ID'];
}
else {
$id = $_SESSION['User_ID'];
}
// # connect mysql server
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
// check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
// # query database
// fetch data from mysql database
$sql = "SELECT a.*, b.*, c.* FROM Users a inner join Teams b on a.User_ID=b.User_ID inner join Players c on b.Team_ID=c.Team_ID WHERE a.User_ID = {$id}";
if ($result = $mysqli->query($sql)) {
$user = $result->fetch_array();
}
else {
echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>";
exit();
}
// echo the user profile & team data
echo "<p>Coach: {$user['Username']}</p>";
echo "<p>Team: {$user['Team_Name']}</p>";
// echo the player data in table
while ($row = $user) {
echo "<tr>";
echo "<td>" . $row["Player_Name"] . "</td>";
echo "<td>" . $row["Position"] . "</td>";
echo "</tr>";
}
}
// showing the login & register or logout link
if (logged_in() == true) {
echo 'Log Out';
}
else {
echo 'Login | Register';
}
?>
<hr />
</body>
</html>
That's because you're fetching the result from database only single time with following code.
$user = $result->fetch_array();
You should use $result->fetch_array() in while loop to run through all the records of database like this,
if ($result = $mysqli->query($sql)) {
while ($row=$result->fetch_array()){
echo "<tr>";
echo "<td>" . $row["Player_Name"] . "</td>";
echo "<td>" . $row["Position"] . "</td>";
echo "</tr>";
}
}
So your while loop will come inside the if condition.
Your final code will look something like this,
<?php
require_once ("functions.php");
require_once ("connection.php");
session_start();
?>
<html>
<head>
<title>My Team</title>
<script src="script.js" type="text/javascript"></script><!-- put it on user area pages -->
</head>
<body>
<h1>My Team</h1>
<hr />
<?php
if (logged_in() == false) {
redirect_to("login.php");
}
else {
if (isset($_GET['User_ID']) && $_GET['User_ID'] != "") {
$id = $_GET['User_ID'];
}
else {
$id = $_SESSION['User_ID'];
}
// # connect mysql server
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
// check connection
if ($mysqli->connect_errno) {
echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
exit();
}
// # query database
// fetch data from mysql database
$sql = "SELECT a.*, b.*, c.* FROM Users a inner join Teams b on a.User_ID=b.User_ID inner join Players c on b.Team_ID=c.Team_ID WHERE a.User_ID = {$id}";
if ($result = $mysqli->query($sql)) {
while ($row=$result->fetch_array()){
echo "<tr>";
echo "<td>" . $row["Player_Name"] . "</td>";
echo "<td>" . $row["Position"] . "</td>";
echo "</tr>";
}
}
else {
echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>";
exit();
}
// echo the user profile & team data
echo "<p>Coach: {$user['Username']}</p>";
echo "<p>Team: {$user['Team_Name']}</p>";
// Place above couple of codes accordingly.
}
// showing the login & register or logout link
if (logged_in() == true) {
echo 'Log Out';
}
else {
echo 'Login | Register';
}
?>
<hr />
</body>
</html>
Use you while loop as
while ($row=$result->fetch_array){
echo "<tr>";
echo "<td>" . $row["Player_Name"] . "</td>";
echo "<td>" . $row["Position"] . "</td>";
echo "</tr>";
}

$_POST['variable'] not working

I am having an issue getting the $userid from $_POST. I have done this lots of times before, so I am not sure what I am doing wrong all of a sudden.
Form that is submitting to user_confirm.php
<?php
//confirm user function
function confirmUsers() {
//make connection global
global $con;
//set user variables
$userquery = mysqli_query($con, "SELECT * FROM users WHERE userlevel = 0");
//echo list
echo '<center><form name="userConfirm" action="functions/user_confirm.php" method="post">';
echo '<select name="confirmUser">';
while ($row = mysqli_fetch_array($userquery)) {
echo "<option value='" . $row['userid'] ."'>" . $row['username'] ."</option>";
//in viewing element, the userid is displaying properly
}
echo '<input type="submit" value="Confirm User">';
echo '</select>';
echo '</form></center>';
}
?>
user_confirm.php
<?php
//include db connect
include ("db_con.php");
//set variable names
$userid = $_POST['userid'];
//start session
session_start();
echo $userid;
?>
As you can see, I am simply just trying to echo the variable passed from the form. It is not working and I am totally confused as to why, any ideas?
in case it was needed here is db_con.php
<?php
$con=mysqli_connect("localhost","user","pw","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
You dont have a form field called userid, perhaps you mean the confirmUser field:
$userid = $_POST['confirmUser'];
You are not passing the userid var to user_confirm.php, try renaming your select to userid
The coding looks right to me and should work.
I'm not sure if this will help but try to load the session_start(); first.
The next thing would be to do a print_r($_POST) and see what shows.
Also view the source of the finished html and see how it prints out.
Also I like to use
echo <<
END;
With this you can just type in the html plus the strings with no ' or " unless the html needs it.
I missed the confirmUser myself.. =(

Categories