database in php mysqli - php

I am writing a chat on php, when I try to log in, user_id is recorded in the session, after a successful attempt, a chat page appears where all the messages are written but the problem is that all the messages were written by me, but it is not true. There are some messages which has been written by other users. So, how can I solve this problem by using JOIN? Can you give me some adive or improve my code?
This is code for log in:
<?php
session_start();
include 'db.php';
if (isset($_POST['email-e']) && isset($_POST['password-pass'])) {
$email_e = mysqli_real_escape_string($mysqli,$_POST['email-e']);
$password_pass = crypt($_POST['password-pass']);
$query = "SELECT id, email, password FROM users_data WHERE email = '$email_e' AND password = '$password_pass'";
$sql = mysqli_query($mysqli,$query) or die(mysqli_error());
if (mysqli_num_rows($sql) == 1) {
$row = mysqli_fetch_assoc($sql);
$_SESSION['user_id'] = $row['id'];
$_SESSION['email-e'] = $row['email'];
setcookie("CookieMy", $row['email'], time()+60*60*24*10);
}
else {
echo 'User not found!';
header("Location: login.html");
}
}
if (isset($_SESSION['email-e'])){
header("Location: chat.php");
} else {
$email_e = '';
if (isset($_COOKIE['CookieMy'])){
$email_e = htmlspecialchars($_COOKIE['CookieMy']);
}
}
?>
This is chat.php code:
<?php
session_start();
include 'db_chat.php';
// header('Content-Type: text/html; charset=utf-8');
//echo trim($_SESSION['email-e'])." <br />"."You are authorized <br />";
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Chat</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<title>Chat</title>
<style>
form,p,span{margin:0;padding:0}
input{font:12px arial}
a{color:#00f;text-decoration:none}
a:hover{text-decoration:underline}
#wrapper,
#loginform{margin:0 auto;padding-bottom:25px;background:#ebf4fb;width:504px;border:1px solid #acd8f0}#loginform{padding-top:18px}#loginform p{margin:5px}
#chatbox{text-align:left;margin:0 auto;margin-bottom:25px;padding:10px;background:#fff;height:270px;width:430px;border:1px solid #acd8f0;overflow:auto}
#usermsg{
width:380px;
height: 50px;
border:1px solid #acd8f0;
border-radius: 3px 3px 3px 3px;
}
#submitmsg{width:70px; height: 53px; border-radius: 5px 5px 5px 5px; cursor: pointer;}
.error{color:#f00}
#menu{padding:12.5px 25px 12.5px 25px}
.welcome{float:left}
.logout{float:right}
.msgln{margin:0 0 2px 0}
</style>
</head>
<body>
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome, <?php echo trim($_SESSION['email-e'])?><b></b></p>
<p class="logout" name="logout">
<a name="logout" id="exit" href="#">Exit Chat</a>
</p>
<div style="clear:both"></div>
</div>
<div id="chatbox">
<?php
if(isset($_POST['submitmsg'])) {
if(!empty($_POST['usermsg']) && is_string($_POST['usermsg'])) {
$time = date("Y-m-d H:i:s");
$usermsg = trim($_POST['usermsg']);
$sql_chat ="INSERT INTO `users_chat` (usermsg,time)
VALUES('{$usermsg}','{$time}')";
$res = mysqli_query($mysqli_chat,$sql_chat);
}
}
$query_chat = "SELECT * FROM `users_chat`";
$res = mysqli_query($mysqli_chat,$query_chat);
while($row_chat = mysqli_fetch_array($res)):?>
<?php $_SESSION['user_id'] = $row_chat['id'];?>
Email: <?=$row_chat['email-e']?> <br>
Message: <?=$row_chat['usermsg']?> <br>
Time: <?=$row_chat['time']?> <br>
<?php endwhile;?>
</div>
<form name="message" action="" method="post">
<input name="usermsg" type="text" id="usermsg" style="margin-left:25px;">
<input name="submitmsg" type="submit" id="submitmsg" value="Send"/><br>
</form>
</div>
</body>
</html>
This is structure of my users_chat table:
CREATE TABLE `users_chat` (
`id` int(11) NOT NULL,
`username` varchar(255) NOT NULL,
`usermsg` varchar(255) NOT NULL,
`user_id` int(11) NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

What is the structure of your users_chat table. I don't see you assign poster id to each message when insert to the database. You must have a field in your users_chat like poster_id which is the foreign key to the users_data table's id and run this sql in the handle POST request INSERT INTO users_chat (poster_id, usermsg, time) VALUES('{$_SESSION["user_id"]}', '{$usermsg}','{$time}')
while($row_chat = mysqli_fetch_array($res)):?>
<?php $_SESSION['user_id'] = $row_chat['id'];?>
this will modify the user_id in the session to the id of the chat message, I don't think this is what you want.

Related

I got a problem with select option and value

I try to keep the value from selected options after the button is clicked.
For now, I have done this with my inputs(range,text) and it's working but I can't figure how to do this with my select option.
ADDITIONAL THINGS(you have to create them to run it)
c13ustawienia.php
<?php
$serwer='localhost';
$uzytk='root';
$haslo='';
$baza='komis';
?>
c13dane.txt
1993|Volkswagen|Passat|19000
1973|Opel|Blitz|12000
1997|Volkswagen|Passat|17000
2010|Mercedes|M5|29000
2001|Volkswagen|Passat|29000
1990|Volkswagen|Passat|23000
2018|Tesla|Super|129000
2018|sla|Super|9000
1992|Volkswagen|Passat|10000
2006|Audi|B9|74000
2009|Volkswagen|Passat|89000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Baza</title>
<style>
table {border-collapse: collapse;}
td,th {border: 1px blue solid;}
th {background-color: azure;}
.id {width: 20px; text-align: center;}
.mar {width: 90px;}
.mod {width: 70px;}
.rok {width: 40px; text-align: right;}
.cena {width: 50px; text-align: right;}
.zolty {background-color: yellow;}
.pomar {background-color:orange;}
[type=text] {width:60px;}
header {height: 60px; background-color:greenyellow;}
header>img {height: 75%; text-align: center;}
nav {height: 400px; width: 30%; background-color:khaki;
float: left;}
main {height: 400px; width: 70%; background-color:moccasin;
float: left;}
footer {height: 40px; background-color: powderblue;
clear: both; text-align: center; color:blue;}
</style>
<script>
function wartosc() {
min=document.getElementById('cmin');
max=document.getElementById('cmax');
wmin=document.getElementById('wmin');
wmax=document.getElementById('wmax');
minint=parseInt(min.value);
maxint=parseInt(max.value);
if(maxint<minint)
maxint=minint+1;
wmin.value=minint;
min.value=minint;
wmax.value=maxint;
max.value=maxint;
}
</script>
</head>
<body>
<?php
function tworz_baze() {
require('c13ustawienia.php');
$link=mysqli_connect($serwer, $uzytk, $haslo);
mysqli_query($link, "DROP DATABASE $baza");
mysqli_query($link, "CREATE DATABASE $baza");
mysqli_query($link, "USE $baza");
mysqli_query($link, "CREATE TABLE auta (
ID int(8) NOT NULL AUTO_INCREMENT PRIMARY KEY,
marka varchar(20),
model varchar(25),
rok int(4),
cena double)");
return $link;
} // tworz_baze()
function czytajdane($plik) {
$f=fopen($plik, 'r');
while(!feof($f)) {
$linia=rtrim(fgets($f));
if(strlen($linia)>5)
$tab[]=explode('|', $linia);
}
return $tab;
} // czytajdane($plik)
function dobazy($link, $tablica) {
foreach ($tablica as $sam) {
list($rok, $mar, $mod, $cena)=$sam;
mysqli_query($link, "INSERT INTO auta VALUES
(NULL, '$mar', '$mod', $rok, $cena)");
}
} // dobazy($link, $tablica)
function pisz($li, $marka, $cenamin, $cenamax) {
echo "<h3>Wybrano:<br>marka: $marka<br>
zakres cen: $cenamin - $cenamax zł</h3>";
echo "<table>
<tr><th>id</th><th>marka</th><th>model</th>
<th>rok</th><th>cena</th></tr>";
$wyn=mysqli_query($li, "SELECT * FROM auta WHERE
marka='$marka' AND cena>=$cenamin AND cena<=$cenamax");
$licznik=FALSE;
while($wiersz=mysqli_fetch_array($wyn)) {
list($id, $mar, $mod, $rok, $cena)=$wiersz;
$kolor = $licznik ? 'zolty' : 'pomar';
echo "<tr class=\"$kolor\"><th class=\"id\">$id</td>
<td class=\"mar\">$mar</td>
<td class=\"mod\">$mod</td>
<td class=\"rok\">$rok</td>
<td class=\"cena\">$cena</td></tr>";
$licznik=!$licznik;
}
echo '</table>';
mysqli_close($li);
} // pisz($li, $model, $cenamax)
function filtry() {
if(isset($_GET['cmin']))
$tab['cmin']=$_GET['cmin'];
else
$tab['cmin']=0;
if(isset($_GET['cmax']))
$tab['cmax']=$_GET['cmax'];
else
$tab['cmax']=CENAMAKS;
if(isset($_GET['marka']))
$tab['marka']=$_GET['marka'];
else
$tab['marka']='Volkswagen';
return $tab;
} // filtry()
function lista($link) {
$w=mysqli_query($link, "SELECT DISTINCT marka
from auta ORDER BY marka");
while($m=mysqli_fetch_array($w))
echo '<option value="'.$m['marka'].'">'
.$m['marka'].'</option>';
// $x=$m['marka'];
// "<option value=\"$x\">....
} // lista($link)
?>
<header>
<img src="auto.png" alt="auto">
<span>Komis samochodowy</span>
</header>
<nav>
<h3>Filtry:</h3>
<form action="c41.php" method="GET">
Cena:<br>
od: <input type="range" name="cmin" id="cmin"
min="0" max="<?php echo CENAMAKS ?>" value="<?php echo $tf['cenamin'];?>"
onchange="wartosc()">
<br>
do :<input type="range" name="cmax" id="cmax"
min="0" max="<?php echo CENAMAKS ?>"
value="<?php echo $tf['cenamin'];?>"
onchange="wartosc()">
<br>
<input type="text" name="wmin" id="wmin" disabled
value="<?php echo $tf['cenamin'];?>"
> -
<input type="text" name="wmax" id="wmax" disabled
value="<?php echo $tf['cenamax'];?>"
><br>
<select name="marka" id="marka">
<?php lista($li); ?>
</select>
<input type="submit" value="Filtruj">
<input type="reset" value="Czyść">
</form>
</nav>
<main>
<?php pisz($li, $tf['marka'], $tf['cmin'], $tf['cmax']); ?>
</main>
<footer>
Adam Kowal ©
</footer>
</body>
</html>
To make inputs work I have giving them variable of function and pointed right key of database to have what I want, but i have no clue how to make it work with select option
frame of code that gives me what i want in inputs: value="<?php echo $tf['cenamin'];?>"
Change your code with the following:
First add a new parameter to the "lista" function to be able to mark the selected value, e.g.
function lista($link, $selected = "default") {
// function code here
}
Secondly, modify the function to respect the passed value and match it to the value gotten from the database:
while($m=mysqli_fetch_array($w)) {
$status = "";
if ($selected == $m['marka']) $status = "selected";
echo '<option '.$selected.' value="'.$m['marka'].'">' .$m['marka'].'</option>';
}
Thirdly, pass the selected value to the function in your code, e.g.:
<?php lista($li, $_GET['marka']); ?>
NB! You should NOT use your current code in any production environments: it includes several SQL injections and isn't built up by best practises (e.g. separating html from the program code etc).

Nothing is being echoed when using mysqli_num_rows() [duplicate]

This question already has answers here:
SELECT COUNT(*) AS count - How to use this count
(5 answers)
Closed 2 years ago.
I am sorry if this is a noob question, but I've been searching all over the internet for an answer and could find nothing that could solve my issue. Anyways, I've taken a look at the php documentation on mysqli_num_rows() (which is https://www.php.net/manual/en/mysqli-result.num-rows.php) since I am trying to find the amount of rows in a column. My table looks like this:
id | follower | followee
1 Xp10d3 IiBlurBeriI
2 IiBlurBeriI Xp10d3
In id number 1, the table shows that IiBlurBeriI has a follower of Xp10d3, and in id number 2 the table shows that Xp10d3 has a follower of IiBlurBeriI. I am trying to get all the subscribers where the username is equal to the profile that is being viewed. Anyways, I used the mysqli_num_rows() method to try and execute this but obviously it doesn't work. I don't get any MySQL errors whatsoever, but when viewing the amount of followers it is blank like this:
Username
followers.
following.
But I want it to look like this:
Username
5 followers.
2 following.
The rest of the MySQL that I used to view the profile worked fine; it was just the follower/following system that I had an issue with. My code is below:
<?php
session_start();
$servername = "localhost"; // Host name
$user = "xxxx"; // Mysql username
$pass = "xxxx"; // Mysql password
$dbname = "xxxx"; // Database name
$tbl_name = "forum_question"; // Table name
// Connect to server and select databse.
$conn = new mysqli($servername, $user, $pass, $dbname);
$userGet = $_GET['username'];
$userGetSQL = "SELECT USERNAME FROM data WHERE USERNAME='".$userGet."'";
$result = $conn->query($userGetSQL);
$userRow = $result->fetch_assoc();
$pfp = "SELECT PFP FROM data WHERE USERNAME = '".$_GET['username']."'";
$pfpresult = $conn->query($pfp);
$pfprow = $pfpresult->fetch_assoc();
$rank = "SELECT LEVEL FROM data WHERE USERNAME = '".$_GET['username']."'";
$rresult = $conn->query($rank);
$followers = "SELECT * FROM subscribers WHERE follower = '".$_GET['username']."'";
$fresult = $conn->query($followers);
$fcnt = $fresult->num_rows;
//echo "FOR TESTING PURPOSES! Followers query: " . $followers . ". Result: " . $fresult . ". num_rows: " . $fcnt . ".";
$following = "SELECT * FROM subscribers WHERE followee = '".$_GET['username']."'";
$ffresult = $conn->query($following);
$ffcnt = $ffresult->num_rows;
//echo "FOR TESTING PURPOSES! Following query: " . $following . ". Result: " . $ffresult . ". num_rows: " . $ffcnt. ".";
$desc = "SELECT DESCRIPTON FROM data WHERE USERNAME = '".$_GET['username']."'";
$descresult = $conn->query($desc);
$descRow = $descresult->fetch_assoc();
if (!isset($_SESSION['username']) && empty($_SESSION['username'])) {
echo 'You are not logged in! Go home to login!';
} else {
?>
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
body {
text-align: center;
font-family: sans-serif;
}
.card {
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
max-width: 300px;
margin: auto;
text-align: center;
}
.title {
color: grey;
font-size: 18px;
}
.msg{
border: none;
outline: 0;
display: inline-block;
padding: 8px;
color: white;
background-color: #000;
text-align: center;
cursor: pointer;
width: 100%;
font-size: 18px;
}
a {
text-decoration: none;
font-size: 22px;
color: black;
}
.msg:hover, a:hover {
opacity: 0.7;
}
</style>
</head>
<body>
<button type="button" style="cursor:pointer">
Home
</button>
<br />
<?php
$check = mysqli_query($conn, "SELECT * FROM subscribers WHERE follower = '".$_SESSION['username']."' AND followee = '".$_GET['username']."'");
if (mysqli_num_rows($check) > 0) {
?>
<button type="button" style="cursor:pointer">
<a href='unfollow.php?username=<?php echo $userGet ?>'>Unfollow</a>
</button>
<?php
} else {
?>
<button type="button" style="cursor:pointer">
<a href='follow.php?username=<?php echo $userGet ?>'>Follow</a>
</button>
<?php
}
?>
<div class="card">
<?php
if ($pfprow['PFP'] == none.png) {
?>
<img src="<?php echo $pfprow['PFP'] ?>" id="pfp" style="width:100%" />
<?php
} else {
?>
<img src="pfp/<?php echo $pfprow['PFP'] ?>" id="pfp" style="width:100%" />
<?php
}
?>
<h1 id="username"><?php echo $_GET['username'] ?></h2>
<p id="title"><?php echo $rrow['LEVEL'] ?></p>
<p><strong><?php echo $fcount ?></strong> followers.</p>
<p><strong><?php echo $ffcount ?></strong> following.</p>
<div class="desc">
<?php
echo $descRow['DESCRIPTON'];
?>
</div>
<p><button class="msg"><i class="fa fa-envelope-o" aria-hidden="true"></i> Send Message</button></p>
</div>
</body>
</html>
<?php
}
exit();
?>
On a side note, yes I know my code is vulnerable to SQL injection. I am trying to learn how to use prepared statements (I am a new to PHP but have used HTML+CSS for a couple of years) so that I can change my code later on. I don't believe I have any INSERT statements so this should be fine.
Setting aside the SQL injection vulnerabilities that you already mentioned, if you want to know how many rows have, for example, follower = 'some_follower', do a COUNT instead:
SELECT COUNT(1) FROM subscribers WHERE follower = 'some_follower'
Because if you do a SELECT * FROM subscribers WHERE follower = 'some_follower' you are asking the DB to return all the results, while you just want to know the COUNT.
Example in PHP:
$result = $conn->query("SELECT COUNT(1) FROM subscribers WHERE follower = 'some_follower'");
$row = $result->fetch_row();
echo '#: ', $row[0];

how to differentiate between different inputs in the same html form using php

I'm building a chatbot in php I want the functionality of that chatbot to be that it is used for resetting the password, so it asks for employee's PIS_CODE which it uses as a primary key to change the password in the password column, you can see my database table.
see it has columns PIS_CODE and password, so I ask the user for PIS_CODE and then it asks the user for the new password and then it changes the password in the corresponding column
so I've been able to take the PIS_CODE and use it as a primary key to reset the password but the password which is reset is the PIS_CODE itself
see here I wanted to reset the password for 41000000 PIS_CODE but it reset the password to 41000000 itself. So it seems like my chatbot assumes the input value to be the pis code and it updates the password column with that value only, so my chatbot is not able to differentiate between different inputs. Plus I want to use only a single form and a single input field.
you can see my chatbot here.
HTML Code :
<div class="form-group">
<form action="process.php" id="form" name="f2" method="POST" >
<input type="textarea" id="tt" name="input" placeholder="Type Your Message" style="position:absolute; bottom:0; height:30px; width:100%; height:50px;" required />
</div>
// this is the code which takes the input for the PIS_CODE
$msgg=$_POST['input'];
// this is the code which takes the input for the password
$pass=$_POST['input'];
// the problem is it saves the same input(that is PIS_CODE) in both the variables($msgg and $pass)
FULL Code:
<?php
require_once("config.php");
$msgg=$_POST['input'];
$msg=strtolower($msgg);
$ID = $msg;
$length=strlen($msg);
$flag=0;
$pass=$_POST['input'];
$update = "UPDATE lala SET password='$pass' WHERE PIS_CODE=".$msg;
$res_4=mysqli_query($con,$update);
$sql1 = "SELECT * FROM lala WHERE PIS_CODE='$msg'";
$res_u = mysqli_query($con, $sql1);
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style>
.in
{
background-color:rgb(64,128,255);
color:white;
padding:10px;
right:0;
width:130px;
text-align: center;
height:auto;
border-radius: 5px;
margin-left: 120px;
margin-bottom: 5px;
}
.out
{
background-color:rgb(241,240,240);
color:black;
padding:10px;
left:5;
width:130px;
text-align: center;
height:auto;
border-radius: 15px;
}
</style>
<body>
<div class="in">
<?php echo "$msgg"; ?>
</div><br>
<div class="out">
<?php
if (($_POST['input']) =='password reset')
{
echo "Do you want to reset your password? ";
}
else if (($_POST['input']) =='yes')
{
echo "Sure, Please provide PIS code ";
}
if (mysqli_num_rows($res_u) == 1)
{
echo 'Pis verified';
echo "Enter new password";
}
if($update){//if the update worked
echo "Update successful!";
}
?>
</div><br>
</body>
</html>
You could use PHP session. This would do what you want:
require_once("config.php");
$msgg=$_POST['input'];
$msg=strtolower($msgg);
$ID = $msg;
$length=strlen($msg);
$flag=0;
session_start();
if(isset($_SESSION['PIS_CODE'])){
$pass=$_POST['input'];
$update = "UPDATE lala SET password='$pass' WHERE PIS_CODE=".$_SESSION['PIS_CODE'];
$res_4=mysqli_query($con,$update);
unset($_SESSION['PIS_CODE']);
}
else{
$sql1 = "SELECT * FROM lala WHERE PIS_CODE='$msg'";
$res_u = mysqli_query($con, $sql1);
if (mysqli_num_rows($res_u) == 1) {
$_SESSION['PIS_CODE'] = $msg;
}
}
If i were you (i.e. working on a chatbot), i'd use the $_SESSION object for more than that. You could keep your simple 1 input form, and use PHP session to keep information about the next expected answer, or for a serie of questions like in your example, to know what is the current question, an many other possible usage.

create login and logout session in php and database

I want to create login and logout session
My table in mysql database is looking like this
CREATE TABLE members (
id int(10) NOT NULL auto_increment,
username varchar(20) NOT NULL,
password varchar(20) NOT NULL, PRIMARY KEY (id) )
ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
and mysql connection named as loginproc.php
<?php
// Inialize session
session_start();
// Include database connection settings
$hostname = 'localhost'; // Your MySQL hostname. Usualy named as 'localhost', so you're NOT necessary to change this even this script has already online on the internet.
$dbname = 'database'; // Your database name.
$username = 'root'; // Your database username.
$password = ''; // Your database password. If your database has no password, leave it empty.
// Let's connect to host
mysql_connect($hostname, $username, $password) or DIE('Connection to host is failed, perhaps the service is down!');
/ Select the database
mysql_select_db($dbname) or DIE('Database name is not available!');
// Retrieve username and password from database according to user's input
$login = mysql_query("SELECT count(*) FROM members WHERE (username = '" . mysql_real_escape_string($_POST['user']) . "') and (password = '" . mysql_real_escape_string(md5($_POST['pass'])) . "')");
$result=mysql_fetch_array($login);
// Check username and password match
if (mysql_num_rows($result) == 1) {
// Set username session variable
$_SESSION['username'] = $_POST['user'];
// Jump to secured page
header('Location: securedpage.php');
}
else {
// Jump to login page
header('Location:career.php');
}
?>
Then created securedpage.php
<?php
// Inialize session
session_start();
// Check, if username session is NOT set then this page will jump to login page
if (!isset($_SESSION['user'])) {
header('Location: career.php');
}
?>
<html>
<head>
<title>Secured Page</title>
</head>
<body>
<p>This is secured page with session: <b><?php echo $_SESSION['username']; ?></b>
<br>You can put your restricted information here.</p>
<p>Logout</p>
</body>
</html>
index.php
<html>
<head>
</head>
<body>
<form action="loginproc.php" method="post">
UserName:<input type="text" name="user" >
<p> </p>
Password:<input type="password" name="pass" >
<p> </p>
<input type="submit" value=" Login Here " >
<span class="style30">| New?</span>
<a href="signup.php"><span class="style32">Start Here</span>
</form></body></html>
and finally logout page named as logout.php
<?php
// Inialize session
session_start();
// Delete certain session
unset($_SESSION['username']);
// Delete all session variables
// session_destroy();
// Jump to login page
header('Location: index.php');
?>
Now my problem is when i am entering username and password it will stay only at index.php , it is not going to another page. please see this code and tell me when i am doing wrong.
Thanks.
I have a solution for your problem. You have to bit modify your code as mentioned below -
<?php
// Inialize session
session_start();
//----***Use variabel to capture start time *****------
// Check, if username session is NOT set then this page will jump to login page
if (!isset($_SESSION['user'])) {
header('Location: career.php');
}
?>
And in logout page add one entry as -
<?php
// Inialize session
session_start();
// Delete certain session
unset($_SESSION['username']);
//---****Use end time variable ---------
// Subtract previous start time variable and end time variale
// Delete all session variables
// session_destroy();
// Jump to login page
header('Location: index.php');
?>
Don't use this line
$result=mysql_fetch_array($login);
This will fetch the result into $result as an array, and later own you are using mysql_num_rows() function (which is used for resource , i.e in your case $login)
You the following code
$login = mysql_query("SELECT count(*) FROM members WHERE (username = '" . mysql_real_escape_string($_POST['user']) . "') and (password = '" . mysql_real_escape_string(md5($_POST['pass'])) . "')");
// Check username and password match
if (mysql_num_rows($login) == 1) {
// Set username session variable
$_SESSION['username'] = $_POST['user'];
// Jump to secured page
header('Location: securedpage.php');
}
else {
// Jump to login page
header('Location:career.php');
}
You have a problem here:
$login = mysql_query("SELECT count(*) FROM members WHERE (username = '". mysql_real_escape_string($_POST['user']) . "') and (password = '" . mysql_real_escape_string(md5($_POST['pass'])) . "')");
$result=mysql_fetch_array($login);
// Check username and password match
if (mysql_num_rows($result) == 1) {
your query will always retrieves 1 row on mysql_num_rows($result) because it retrieves the count of users with the condition, if no one match the username and password, the query retrieves
|count(*)|
+--------+
|0 |
and it is 1 row
I see two problems:
mysql_num_rows takes resource type as parameter. You are passing the result of mysql_fetch_array which can either be an array or FALSE.
You're using deprecated mysql extension. You should be using either MySQLi or PDO for new code.
To fix the mysql_num_rows problem in point 1, use if (mysql_num_rows($login)) {:
$login = mysql_query("SELECT count(*) FROM members WHERE (username = '" . mysql_real_escape_string($_POST['user']) . "') and (password = '" . mysql_real_escape_string(md5($_POST['pass'])) . "')");
$result=mysql_fetch_array($login);
// Check username and password match
if (mysql_num_rows($login) == 1) {
index.php
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="css/style.css">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,700,800' rel='stylesheet' type='text/css'>
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png">
<style>
.head{
margin:auto;
margin-top: 40px;
margin-bottom: 40px;
width: 500px;
height: 50px;
text-align:center;
}
</style>
</head>
<body>
<div class="head"><h1> <span class="strong"></span></h1></div>
<div style="padding:0;" align="center" class="login-page">
<img src="img/oms.png"><br><br>
<div class="form" >
<form class="login-form" name="frm" action="Logging.php" method="POST">
<input type="text" placeholder="username" name="usrname"/>
<input type="password" placeholder="password" name="password"/>
<button type="submit" onclick="return logincheck()">login</button>
<p class="message"> Forgot Password Click here</p>
</form>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script type="text/javascript">
function logincheck()
{
var x = document.frm.usrname.value;
var y = document.frm.password.value;
if(x =="" || x == null){
alert("Enter the Username ");
return false;
}
else if(y=="" || y == null){
alert("Enter the Password ");
return false;
}else{
return true;
}
}
$('.message a').click(function(){
$('form').animate({height: "toggle", opacity: "toggle"}, "slow");
});
</script>
</body>
<?php include 'footer1.php';?>
</html>
Logging.php
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="css/style.css">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,700,800' rel='stylesheet' type='text/css'>
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png">
<style>
.head{
margin:auto;
margin-top: 40px;
margin-bottom: 40px;
width: 500px;
height: 50px;
text-align:center;
}
</style>
</head>
<body>
<div class="head"><h1> <span class="strong"></span></h1></div>
<div style="padding:0;" align="center" class="login-page">
<img src="img/oms.png"><br><br>
<div class="form" >
<form class="login-form" name="frm" action="Logging.php" method="POST">
<input type="text" placeholder="username" name="usrname"/>
<input type="password" placeholder="password" name="password"/>
<button type="submit" onclick="return logincheck()">login</button>
<p class="message"> Forgot Password Click here</p>
</form>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script type="text/javascript">
function logincheck()
{
var x = document.frm.usrname.value;
var y = document.frm.password.value;
if(x =="" || x == null){
alert("Enter the Username ");
return false;
}
else if(y=="" || y == null){
alert("Enter the Password ");
return false;
}else{
return true;
}
}
$('.message a').click(function(){
$('form').animate({height: "toggle", opacity: "toggle"}, "slow");
});
</script>
</body>
<?php include 'footer1.php';?>
</html>
Logout.php
<?php
include 'header.php';
include 'footer.php';
session_destroy();
echo "<script>alert('Successfully Logged Out');window.location.href='index.php'</script>";
?>
forgotpass1.php
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="css/style.css">
<link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,700,800' rel='stylesheet' type='text/css'>
<link rel="icon" type="image/png" sizes="32x32" href="img/favicon-32x32.png">
<style>
.head{
margin:auto;
margin-top: 40px;
margin-bottom: 40px;
width: 500px;
height: 50px;
text-align:center;
}
</style>
</head>
<body>
<div class="head"><h1> <span class="strong"></span></h1></div>
<div style="padding:0;" align="center" class="login-page">
<img src="img/oms.png"><br><br>
<div class="form" >
<form class="login-form" name="frm" action="validateemail1.php" method="POST">
<input type="text" placeholder="Email" name="email"/>
<table width="100%">
<tr><td align="left">
<button type="submit" name="Back" value="Back" onclick="history.go(-1);" >Back</button></td><td>&nbsp </td><td align="left"> <button type="submit" name="submit" onclick="return logincheck()">Send Email</button></td></tr></table>
</form>
</div>
</div>
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
<script type="text/javascript">
function logincheck()
{
var y = document.frm.email.value;
if(y=="" || y == null){
alert("Enter the Email ");
return false;
}else{
return true;
}
}
$('.message a').click(function(){
$('form').animate({height: "toggle", opacity: "toggle"}, "slow");
});
</script>
</body>
</html>
<?php include 'footer1.php';?>
validateemail1.php
<?php
include 'dbConfig.php';
if (isset($_POST['submit'])){
$email=$_POST['email'];
$n=0;
$query=mysqli_query($con,"SELECT * FROM signup where email ='".$email."'");
while($row=mysqli_fetch_array($query))
{
$db_email=$row['email'];
if($db_email==$email)
{
$n++;
$to=$row['email'];
$subject = "Your Password ";
$txtn = '<table align="center" border="0" cellpadding="0" cellspacing="0" width="1000">
<tr>
<td align="center" bgcolor="#2ce0e8" style="padding: 7px 0 10px 0;background:#f55322 ">
<img src="http://saiss.co.in/supreme_oms/img/oms.png" alt="http://saiss.co.in/supreme_oms/index" width="84" height="36" style="display: block;" />
</td>
</tr>
<td bgcolor="#ffffff" style="padding: 20px 0 30px 0"><center>Hi ,'.$row["username"].'<br>
Your password is: '.$row["password"].'<br> Click to Login</center>
</td>
<tr>
<td bgcolor="#f55322" style="padding: 25px 0px 18px 23px;color: #fff;font-size: 12px;">
© <?php echo date("Y"); ?> OMS All RIGHTS RESERVED.
</td>
<td align="right">
</td>
</tr>
</table>';
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= 'From: <OMS>' . "\r\n";
mail($to,$subject,$txtn,$headers);
echo "<script>alert('We Sent Password To Your Email Address');window.location.href='index.php';</script>";
}
}
if($n==0)
{
echo "<script>alert('Your email is Not Matching with our database');window.location.href='index.php';</script>";
}
}
?>
Logging.php
<?php
session_start();
include 'dbConfig.php';
$logname = $_POST['usrname'];
$logpass = $_POST['password'];
if(isset($_POST['usrname'])) {
$name = $_POST['usrname'];
}
if(isset($_POST['password'])) {
$name = $_POST['password'];
}
if($logname != null && trim($logname) !="" && trim($logpass) !="" && $logpass !=null)
{
$getvalue ="";
$sql_query = "Select * from signup where username='".$logname."'and password ='".$logpass."'";
$changepass="";
$result_set = mysqli_query($con,$sql_query);
if(mysqli_num_rows($result_set)==0){
echo "<script>alert('Invalid Username/Password');window.location.href='index.php'</script>";
}else{
while($row=mysqli_fetch_row($result_set))
{
$getvalue = $row[0];
$changepass = $row[3];
}
$_SESSION["usrnam"] = $getvalue;
if($changepass=="Y"){
echo "<script>window.location.href='changepassword.php'</script>";
}else
{
echo "<script>window.location.href='dashboard.php'</script>";
}
}
}else{
echo "<script>alert('Invalid Username/Password');window.location.href='index.php'</script>";
}
?>

Toggle Panels With PHP

I wonder whether someone may be able to help me please.
From some demos and tutorials I've found, I've put together this page which adds toggle panes to a page using values from a mySQL database to populate the fields.
The problem I'm having is that at each layer only the first out of multiple records is shown.
e.g. The screen currently shows 16/03/2012 as the only record, there should be one other record for the 23/02/2012.
Then within the 16/03/2012, the next level should show two items, whereas it is only showing one.
I've been working on this for a while now but I can't seem to find the solution of how to show the correct number of records.
I just wondered whether someone could perhaps have a look at this please and let me know where I'm going wrong.
I've added the full script below for reference.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Panel Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(".content").hide();
//toggle the componenet with class msg_body
jQuery(".heading").click(function()
{
jQuery(this).next(".content").slideToggle(500);
});
});
</script>
<style type="text/css">
body {
margin: 20px auto;
font: 12px Verdana,Arial, Helvetica, sans-serif;
}
.layer1 {
margin: 0;
padding: 0;
width: 500px;
}
.heading {
margin: 1px;
color: #fff;
padding: 3px 10px;
cursor: pointer;
position: relative;
background-color:#c30;
}
.content {
padding: 5px 10px;
background-color:#fafafa;
}
p { padding: 5px 0; }
</style>
</head>
<?php
mysql_connect("hostname", "username", "password")or
die(mysql_error());
mysql_select_db("database");
$result = mysql_query("SELECT userdetails.userid, finds.dateoftrip, detectinglocations.locationname, finds.userid, finds.locationid, detectinglocations.locationid, finds.findname, finds.finddescription FROM userdetails, finds, detectinglocations WHERE finds.userid=userdetails.userid AND finds.locationid=detectinglocations.locationid AND finds.userid = 1 ORDER BY dateoftrip DESC");
if (mysql_num_rows($result) == 0)
// table is empty
echo 'There are currently no finds recorded for this location.';
else
{
while ($row = mysql_fetch_array($result))
{
$dateoftrip = $row['dateoftrip'];
$findname = $row['findname'];
{
}
}
}
?>
<body>
<div class="layer1">
<p class="heading"><input name="dateoftrip" id="dateoftrip" type="text" value="<?php echo $dateoftrip;?>" disabled="disabled"/></p>
<div class="content">
<input name="findname" id="findname" type="text" value="<?php echo $findname;?>" disabled="disabled"/>
</div>
</div>
</body>
</html>
Many thanks and kind regards
You are fetching all the records but using only the last one.
You should put this:
<div class="layer1">
<p class="heading"><input name="dateoftrip" id="dateoftrip" type="text" value="<?php echo $dateoftrip;?>" disabled="disabled"/></p>
<div class="content">
<input name="findname" id="findname" type="text" value="<?php echo $findname;?>" disabled="disabled"/>
</div>
</div>
in the while loop which fetch the data:
while ($row = mysql_fetch_array($result))
{
$dateoftrip = $row['dateoftrip'];
$findname = $row['findname'];
So it will look like this:
while ($row = mysql_fetch_array($result))
{
$dateoftrip = $row['dateoftrip'];
$findname = $row['findname'];
echo '<div class="layer1">
<p class="heading"><input name="dateoftrip" id="dateoftrip" type="text" value="'.$dateoftrip.'" disabled="disabled"/></p>
<div class="content">
<input name="findname" id="findname" type="text" value="'.$findname.'" disabled="disabled"/>
</div>
</div>';
}
You need to put your output inside your loop. Also you may have to modify your javascript to account for the multiple content ids.
You should also make the form controls into arrays so you'll be able to parse them if needed (see below).
For example, this is how to modify the form.
?>
<body>
<div class="layer1">
<?php
while ($row = mysql_fetch_array($result))
{
$dateoftrip = $row['dateoftrip'];
$findname = $row['findname'];
$i++;
?>
<p class="heading"><input name="dateoftrip[]" id="dateoftrip" type="text" value="<?php echo $dateoftrip;?>" disabled="disabled"/></p>
<div class="content">
<input name="findname[]" id="findname" type="text" value="<?php echo $findname;?>" disabled="disabled"/>
<?php
{
}
}
}
?>
</div>
</div>

Categories