I'm just learning PHP and I'd like to do a basic login. Once logged in, I'd like to show basic information from the user (in this example, just the name), but for some reason I'm not getting the name printed. Could you help me please?
<?php
include "config.php";
// Session
if(!isset($_SESSION['uname'])){
header('Location: login.php');
}
// Logout
if(isset($_POST['but_logout'])){
session_destroy();
header('Location: login.php');
}
// CHECK THIS
$sql_query = "select * from users where username='".$uname."'";
$result = mysqli_query($con,$sql_query);
$row = mysqli_fetch_array($result);
?>
<!doctype html>
<html>
<head></head>
<body>
<form method='post' action="">
<h1>Dashboard</h1>
<div>
<!-- CHECK THIS -->
<h2>Hello <?php echo $row['name']; ?></h2>
</div>
<div>
<input type="submit" value="Logout" name="but_logout">
</div>
</form>
</body>
</html>
The login, logout and session are already working.
The table structure contains a table named users with the columns: id, username, password, name, email.
Thanks
$uname is undefinded
Try: $_SESSION['uname'] on line 14;
Alway u can debug this e.g. var_dump($sql_query) and execute it in phpmyadmin
And if you want use $row['name'], you must have assoc array: $row = mysqli_fetch_assoc($result);
this is a very basic example:
first of all you must to open a conection to your server and database, create a php file, lets call "CONEXION_DB.php" and add the next code:
<?php
function ConexionDBServer($DB_Con)
{
$servername = "your_server";
$username = "your_user";
$password = "your_password";
$conDB = mysqli_connect($servername, $username, $password);
if (!$conDB)
{
die('Could not connect: ' . mysqli_error());
return -1;
}
$DB = mysqli_select_db($conDB, $DB_Con);
if (!$DB)
{
echo "<SCRIPT LANGUAGE='javascript'>
alert('CONEXION WITH DB FAIL');
</SCRIPT>";
return -1;
}
return $conDB;
}
?>
now create your "main" page, lets call "main_page.php", and add:
<?php
echo "example mysql </br>";
?>
<!doctype html>
<html>
<head></head>
<body>
<form action="<?php echo $PHP_SELF?>" method="POST">
<input size=10 maxlength="150" type="text" name="txtUsuario">
<input type="submit" value="Login" name="cmdLogin">
</form>
<?php
if($_POST[txtUsuario])
{
$sql_query = "select * from users where username='" . $_POST[txtUsuario] . "'";
require_once('CONEXION_DB.php');
$con=ConexionDBServer("name_of_your_db");
$result = mysqli_query($con,$sql_query);
while($row = mysqli_fetch_array($result))
{
echo $row['username'] . "</br>";
}
mysqli_close($con);
}
?>
</body>
</html>
as you can see, in order to capture the input entry from your form, you must to use the $_POST method.
Related
I have created a customer database in which 4-5 staff will have access to login to view, edit and delete records.
I need the html table that lists the customer records to show an 'Edit' and 'Delete' link only when the logged in userID ($_SESSION[userID]) matches the userID of who created the record. So, if a staff member created 3 out 5 records, they should only see an 'edit' and 'delete' hyperlink against these three records, and nothing on the other two.
I have managed to get to the point of the sessions working - however, being new to PHP I am not sure where exactly to put my IF statement to echo the 'Edit' and 'Delete' links - and completely lost in how to write it exactly. I have tried many attempts, but am tearing my hair out now! Any help will be hugely appreciated.
This is my session start file (authenticate.php):
<?php
session_start();
$_SESSION["staffID"] = "staffID";
?>
Staff login file (staff_login.php):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Staff login</title>
</head>
<body>
<?php
require("db.php");
session_start();
// If form submitted, insert values into the database.
if (isset($_POST['username'])){
// removes backslashes
$username = stripslashes($_REQUEST['username']);
//escapes special characters in a string
$username = mysqli_real_escape_string($con,$username);
$password = stripslashes($_REQUEST['password']);
$password = mysqli_real_escape_string($con,$password);
//Checking if user existing in the database or not
$query = "SELECT * FROM `staff login` WHERE username='$username'
and password='$password'";
$result = mysqli_query($con,$query) or die(mysql_error());
$rows = mysqli_num_rows($result);
if($rows==1){
$_SESSION['username'] = $username;
$_SESSION[staffID] = $rows["$staffID"];
// Redirect user to edit_contact.php - was index.php -
header("Location: edit_contact.php");
}
else
{
echo "<div class='form'>
<h3>Username/password is incorrect.</h3>
<br/>Click here to <a href='staff_login.php'>Login</a></div>";
}
}else{
?>
<div class="form">
<h1>Staff login</h1>
<form action="" method="post" name="login">
<input type="text" name="username" placeholder="Username" required />
<input type="password" name="password" placeholder="Password" required />
<input name="submit" type="submit" value="Login" />
</form>
</div>
<?php } ?>
</body>
</html>
And the php file to show the records in a table with the 'Edit' and 'Delete' hyperlinks:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Edit contact</title>
</head>
<body>
<h2>Tate Finance Customer contact details</h2>
<?php
//***edit_contact.php***///
// Developed by: []
// Contact: []
// Created: [November 2018]
// Last Modified: [26 November 2018]
/* Purpose: This file lists all contacts from the mycontacts database in a table for logged in users to add, edit or delete their contacts.*/
//include authenticate.php file on all secure pages
require('db.php');
include("authenticate.php");
?>
<!--Add welcome note to staff user-->
<p>Welcome <?php echo $_SESSION['username']; ?>!</p>
<p>Logout</p>
<h3>Add new customer</h3>
<?php
$con = mysqli_connect("localhost","root","xxxxxx","mycontacts");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
// Show all contacts from database in a table list
$query = "SELECT * FROM contact ORDER BY conName ASC";
$rst = mysqli_query($con,$query);
if($rst)
{
if(mysqli_num_rows($rst)>0)
{
// Table design for contacts list
echo "<table border='1'><tr><td>Edit contact</td><td>Name</td><td>Address</td><td>Phone</td><td>Mobile</td><td>Email</td></tr>";
while ($row = mysqli_fetch_assoc($rst))
{
/* Present contacts details in table list according to id selected, with links to edit or delete according to contactID selected */
/* This is where I think my IF statement needs to go, but can't figure out how/what to write to make it work */
echo "<tr><td>Edit Delete</td><td>".$row['conName']."</td><td>".$row['conAddress']."</td><td>".$row['conPhone']."</td><td>".$row['conMobile']."</td><td>".$row['conEmail']."</td></tr>";
}
echo "</table>";
}
}
else
{
echo "No results found";
}
}
?>
</body>
</html>
while ($row = mysqli_fetch_assoc($rst))
{
echo "<tr>";
if($_SESSION["staffID"] == $id_of_creator){
echo "<td>".
"Edit".
"<a href=delete_record.php?
id=".$row['contactID']."> Delete</a> ".
"</td>";
}else echo "<td></td>";
echo "<td>".$row['conName']."</td><td>".$row['conAddress']."</td><td>".$row['conPhone']."</td><td>".$row['conMobile']."</td><td>".$row['conEmail']."</td></tr>";
}
<?php
while($row = mysqli_fetch_assoc($selectAllCustomer)){
$id = $row['customer_id'];
$name= $row['customer_id'];
$email= $row['customer_email'];
echo "<tr>";
if($_SESSION['staffID'] == $Admin_Id){
echo "<td>".$name."</td>";
echo "<td>".$email."</td>";
echo "<td>";
echo "<a href='editPage.php?edit='".$id."'>Edit</a>";
echo "</td><td>";
echo "<a href='deletePage.php?delete='".$id."'>Delete</a>";
echo "</td>";
}else{
echo "<td>".$name."</td>";
echo "<td>".$email."</td>";
}
echo "</tr>";
}
NB: the valiable $admin_Id, is a id of the creator
?>
I am currently creating a quiz using PHP, HTML and mySQL for simply practice. However, I keep running into a problem where, the question displayed is different to the actual question linked to the answer. So where the user is correct, the answer is wrong.
Here is what I have for the question page:
<?php
session_start();
session_unset();
$link = mysqli_connect("xxxx","xxxx","xxxx", "xxxx");
if(mysqli_connect_error()) {
echo "There was an error connecting to the database!";
}else{
$qNo = rand(1,2);
$query = "SELECT * FROM questions WHERE questionID = '".$qNo."'";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
$answer = $row[2];
$question = $row[1];
if(isset($_POST['submit'])){
$_SESSION['question'] = $row[1];
$_SESSION['answer'] = $answer;
$_SESSION['userAnswer'] = $_POST['userAnswer'];
header("Location: process.php");
}
}
?>
<html>
<head>
<title>Quiz v2</title>
</head>
<body>
<h1>Welcome to Quiz!</h1>
<div>
<p><a><?php print_r($question);?></a></p>
<form method="post">
<label for="answer">Answer: </label><input name="userAnswer">
<button name="submit">Answer</button>
</form>
</div>
</body>
</html>
This is what I have for the process page:
<?php
session_start();
$link = mysqli_connect("xxx","xxxx","xxxx", "xxxx");
if(mysqli_connect_error()) {
echo "There was an error connecting to the database!";
}else{
echo $_SESSION['userAnswer'];
echo $_SESSION['answer'];
echo $_SESSION['question'];
if($_SESSION['userAnswer']==$_SESSION['answer']){
}
}
?>
Over here you can see the question displayed is:
enter image description here
But this is what is actually being asked and compared:
enter image description here
Session is used in my project. After log in successfully, session_start() is called in my login.php page. And then it will go to another page:repair_device.php. In repair_device.php,
isset($_SESSION["admin"])&&$_SESSION["admin"]==true //this can pass
and alert("testInDR") can be showed correctly. But sql did nothing.
If I choose log on directly in repair_device.php, for example:
$conn = new PDO('mysql:host=localhost;port=3306;dbname=xxx' , 'xxx' , 'xxxx');
$conn->setAttribute(PDO::ATTR_ORACLE_NULLS, true);
sql= "select * from hpc_repairdevice order by datetime desc" works fine.
Here is the code of login.html
<form class="login" action="index.php" method="post">
<span>account:</span><input type="text" name="username" /><br /><br />
<span>password:</span><input type="password" name="password"/><br /><br />
<span>verificationCode:</span><input type="text" name="code" /><img id="code" src="create_code.php" alt="another" style="cursor: pointer; vertical-align:middle;" onClick="create_code()"/><br /><br />
<input type="submit" style="margin-left:35%" value="logon" /><input type="reset" value="" /> </div>
</form>
Here is the code of index.php
<?php
session_start();
if(!isset($_GET['log_out']) && ($_POST['code'] != $_SESSION['code']))
{
echo "wrong verificationCodeļ¼<br />" . "<meta http-equiv='refresh' content='2;url=index.html'>";
}
if(!isset($_GET['log_out']))
{
$user = $_POST['username'];
$pwd = $_POST['password'];
if($user!=null & $pwd!=null)
{
try
{
$conn=new PDO('mysql:host=x.x.x.x;port=3306;dbname=hpc',$user,$pwd);
}
catch(PDOException $e)
{
echo "faile<br />".$e->getMessage()."<meta http-equiv='refresh' content='1;url=index.html'>";
}
if($conn)
{
$_SESSION["admin"]=true;
$stas = $conn->getAttribute(PDO::ATTR_CONNECTION_STATUS);
.....
echo "<script language='javascript' type='text/javascript'>";
echo "window.location.href='http://xx.xx.xx.xx/repair_device.php'";
echo "</script>";
.....
}
}
}
?>
Here is the code of create_code.php
<?php
session_start();
//create pic
header("Content-type: image/png");
.....
$_SESSION['code'] = $verifyCode; //stor verification code in session
......
?>
Here is the code of repair_device.php
<!DOCTYPE html>
<html>
<head>
......
</head>
<body>
<?php
session_start();
// $conn = new PDO('mysql:host=localhost;port=3306;dbname=xxx' , 'xxx' , 'xxxx');
//$conn->setAttribute(PDO::ATTR_ORACLE_NULLS, true);
$admin=false;
if(isset($_SESSION["admin"])&&$_SESSION["admin"]==true)
{
alert("testInDR");
$sql = "select * from hpc_repairdevice order by datetime desc";
......
$sel=$conn->query($sql);
......
}
?>
</body>
</html>
I suppose session id should be passed to repair_device.php, but I don't know how. Who can help me ?
A database connection isn't passed with the session. One popular way is to have a DB bootstrap file that is included at the head of any page that needs access to the database (Or an autoloader).
<?php //index.php, repair_device.php
require_once('db.php');
//rest of page
And in the db page you setup your connection (and probably start the session)
<?php // db.php
session_start();
$conn = new PDO('mysql:host=localhost;port=3306;dbname=xxx' , 'xxx' , 'xxxx');
$conn->setAttribute(PDO::ATTR_ORACLE_NULLS, true);
Then the result that would be rendered by PHP would be
<?php // index.php
session_start();
$conn = new PDO('mysql:host=localhost;port=3306;dbname=xxx' , 'xxx' , 'xxxx');
$conn->setAttribute(PDO::ATTR_ORACLE_NULLS, true);
//rest of page
Including the connection on any page that needs it simply requires the one line of code.
Iam trying to create a private messaging system in which user sends message to another user and that content is inserted into database..Iam using a random number called hash to identify a conversation between two people..table for that is "message_group" and table for saving messages is "messages"..here comes the problem..
When I type something in text area and click on sendmessage button it inserts the data into the messages database..But if type something again and try to send it , the data wont enter into database..coz of this the other person is getting only first message..Please help me solving this problem..here's the code
<html>
<head>
<title>new convo</title>
</head>
<body>
<?php include 'connect.php';?>
<?php include 'message_title_bar.php';?>
<?php include 'functions.php';?>
<div>
<?php
if(isset($_GET['user']) && !empty($_GET['user'])){
?>
<form method='post'>
<?php
if(isset($_POST['message']) && !empty($_POST['message'])){
$my_id=$_SESSION['user_id'];
$user=$_GET['user'];
$random_number=rand();
$message=$_POST['message'];
$connect = mysqli_connect('localhost','root','','php_mysql_login_system');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query_string = "SELECT `hash` FROM `message_group` WHERE (`user_one`='$my_id' AND `user_two`='$user') OR (`user_one`='$user' AND `user_two`='$my_id')";
$check_con=mysqli_query($connect,$query_string) or die(mysqli_error($connect));
if(mysqli_num_rows($check_con)==1){
echo "<p>Conversation already Started</p>";
}else{
$connect = mysqli_connect('localhost','root','','php_mysql_login_system');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($connect,"INSERT INTO message_group VALUES('$my_id' , '$user' , '$random_number')");
mysqli_query($connect,"INSERT INTO messages VALUES ('','$random_number','$my_id','$message')");
echo "<p>Conversation started</p>";
}
}
?>
Enter message:<br />
<textarea name='message' rows='7' cols='60'></textarea>
<br />
<br />
<input type='submit' name="submit" value="sendmessage" />
</form>
<?php
}
else{
echo "<b>Select User</b>";
$connect = mysqli_connect('localhost','root','','php_mysql_login_system');
$user_list=mysqli_query($connect,"SELECT `id`,`username` FROM `users`");
while($run_user=mysqli_fetch_array($user_list)){
$user = $run_user['id'];
$username = $run_user['username'];
echo "<p><a href='send.php?user=$user'>$username</a></p>";
}
}
?>
</div>
</body>
</html>
Any help is appreciated.
<html><head><title>new convo</title></head><body>
<?php include 'connect.php'; ?>
<?php include 'message_title_bar.php'; ?>
<?php include 'functions.php'; ?>
<?php $connect = mysqli_connect('localhost', 'root', '', 'php_mysql_login_system'); if (mysqli_connect_errno()) echo "Failed to connect to MySQL: " . mysqli_connect_error(); ?>
<div>
<?php
if (isset($_GET['user']) && !empty($_GET['user'])) {
?>
<form method='post'>
<?php
if (isset($_POST['message']) && !empty($_POST['message'])) {
$my_id = $_SESSION['user_id'];
$user = $_GET['user'];
$message = $_POST['message'];
$query_string = "SELECT `hash` FROM `message_group` WHERE (`user_one`='$my_id' AND `user_two`='$user') OR (`user_one`='$user' AND `user_two`='$my_id')";
$check_con = mysqli_query($connect, $query_string);
if (mysqli_num_rows($check_con)) {
$f_array = mysqli_fetch_array($check_con);
$hash = $f_array['hash'];
echo "<p>Conversation already Started</p>";
} else {
$hash = rand();
mysqli_query($connect, "INSERT INTO message_group VALUES('$my_id' , '$user' , '$hash')");
echo "<p>Conversation started</p>";
}
mysqli_query($connect, "INSERT INTO messages VALUES ('', '$hash', '$my_id', '$message')");
}
?>
<label for="message">Enter message:</label>
<textarea name='message' id="message" rows='7' cols='60'></textarea>
<br/>
<br/>
<input type='submit' name="submit" value="sendmessage"/>
</form>
<?php
} else {
echo "<b>Select User</b>";
$user_list = mysqli_query($connect, "SELECT `id`,`username` FROM `users`");
while ($run_user = mysqli_fetch_array($user_list)) {
$user = $run_user['id'];
$username = $run_user['username'];
echo "<p><a href='send.php?user=$user'>$username</a></p>";
}
}
?>
</div>
</body>
</html>
There are many mistakes in code brother read basic first... and you are not using echo function to print old chat.
Just echo old chat. before post function.
steps:
1. Check if users already chatting.
2. If they are chatting echo chat which they already chatted.
3. If not chatting then start new chat.
4. if they are not chatting you dont need to echo anything just echo new message.
Your present code will just show you last message i think. because your page getting reload. and after it loads its just printing your last message in my view.. you need to print old chat as well.
I have a page with a who does a post to the same page. I want that page to be refreshed with new data after a succesful database INSERT.
Let me add some code.
default.php
<?php
session_start();
require("dbconfig.php");
include("head.php");
//if user is not signed in, redirect to login page
if (!isset($_SESSION['sess_user']) ) {
header ("Location: login.php");
exit;
}
?>
<body>
<div id="menu">
<?php
include("menu.php"); //include the menu
?>
</div>
<div id="page_content">
<?php
include ($p); //Include selection from menu.php
?>
</div>
?>
dbconfig.php
<?php
DEFINE ('DB_USER', 'someuser');
DEFINE ('DB_PASSWORD', 'somepassword');
DEFINE ('DB_HOST', 'localhost');
DEFINE ('DB_NAME', 'somedatabase');
$connection = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or
die('Connection to the specified database couldn\'t be established');
mysql_select_db(DB_NAME) or
die ('Specified database couldn\'t be selected');
function db_escape ($post)
{
if (is_string($post) ) {
if (get_magic_quotes_gpc() ) {
$post = stripslashes($post);
}
return mysql_real_escape_string ($post);
}
foreach ($post as $key => $val) {
$post [$key] = db_escape($val);
}
return $post;
}
?>
page/cities.php
<?php
//if not signed in correctly, redirect to login page
session_start();
if (!isset($_SESSION['sess_user']) ) {
header ("Location: login.php");
exit;
}
?>
<h2>Available cities</h2>
<?php
//List all available cities from database
$cities_query = "SELECT city_name FROM city_selection";
$cities_result = mysql_query($cities_query);
while ($row = mysql_fetch_assoc($cities_result)) {
echo $row['city_name'] . "<br />";
}
?>
<?php
//Add new city to list
if(isset($_POST['submit'])){
$city_name = $_POST['city_name'];
$query="INSERT into city_selection (city_name) values ('$city_name')";
$result = mysql_query($query);
}
?>
<hr>
<h2>Add new city</h2>
<form method="post" action="default.php?p=settings_cities">
Namn: <input type="text" name="city_name">
<input type="submit" name="submit" value="Add city">
</form>
This code may not be pretty but it works. It succesfully adds a new record to the database however I want the page/cities.php to be refreshed with my ny record after the post. Is this possible?
Let me add that this i my first ever php page. I've only read some books so don't bash me for beeing a bad programmer :)
Yes, just move your insert part to above your select part.
page/cities.php
<?php
//if not signed in correctly, redirect to login page
session_start();
if (!isset($_SESSION['sess_user']) ) {
header ("Location: login.php");
exit;
}
//Add new city to list
if(isset($_POST['submit'])){
$city_name = $_POST['city_name'];
$query="INSERT into city_selection (city_name) values ('$city_name')";
$result = mysql_query($query);
}
?>
<h2>Available cities</h2>
<?php
//List all available cities from database
$cities_query = "SELECT city_name FROM city_selection";
$cities_result = mysql_query($cities_query);
while ($row = mysql_fetch_assoc($cities_result)) {
echo $row['city_name'] . "<br />";
}
?>
<hr>
<h2>Add new city</h2>
<form method="post" action="default.php?p=settings_cities">
Namn: <input type="text" name="city_name">
<input type="submit" name="submit" value="Add city">
</form>
You can also refresh a page with javascript :
<script type="text/javascript">
document.location = "URL"
</script>
Read up on the Post-Redirect-Get pattern, and redirect the browser to the same page after saving the record. The redirect should be done through PHP's header function.
As your code works now, someone refreshing through F5 will insert the same value again... P-R-G avoids this problem.
Just do the
if(isset($_POST['submit'])){
//yada yada
before you do the select