#Edit 2,
I think the problem stems from passing arguments.
<br />
<b>Warning</b>: mysqli_connect(): (HY000/2002): Connection refused in <b>/opt/lampp/htdocs/ch1/saveEmail.php</b> on line <b>12</b><br />
Failed to connect to MySQL: Connection refused<br />
<b>Warning</b>: mysqli_query() expects parameter 1 to be mysqli, bool given in <b>/opt/lampp/htdocs/ch1/saveEmail.php</b> on line <b>30</b><br />
<br />
<b>Warning</b>: mysqli_close() expects parameter 1 to be mysqli, bool given in <b>/opt/lampp/htdocs/ch1/saveEmail.php</b> on line <b>41</b><br />
#Edit, if I disable doRecord method and assign a random number to $retVal, I can see its value from the console. I think the problem is about the function’s body.
I’m trying to save information which is put by the fields into MySQL database. But I cannot see even what the result is by exit(json_encode(array("response" => $response))); or exit(json_encode(array("response" => "not entered")));. I’m sure database works, I tested. Also, button onclick works, but no more. What’s the wrong?
saveEmail.php
<?php
function doRecord($host, $username, $password, $dbName,
$senderName, $senderMail, $senderSubject, $senderBody, $cronInput) {
$retVal = 0;
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = new mysqli($host, $username, $password, $dbName);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$date = gmdate('Y-m-d h:i:s', time());
/*$htmlBody =
"bodyy <p>link burada </p>
<p> </p>
<p>fdgfd</p>";
*/
// Attempt insert query execution
$sql = "INSERT INTO staj.info(name, email, subject, body, progressTime, cronInput)
VALUES
('$senderName', '$senderMail', '$senderSubject', '$senderBody', '$date', '$cronInput');";
if(mysqli_query($link, $sql)){
//echo "Records inserted successfully.";
$retVal = 1;
} else{
//echo "\n\nERROR: Could not able to execute $sql. " . mysqli_error($link);
$retVal = 0;
}
// Close connection
mysqli_close($link);
return $retVal;
}
if (isset($_POST['cron'])) {
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$body = $_POST['body'];
$cron = $_POST['cron'];
$retVal = doRecord("127.0.0.1", "root", "12345678", "staj",
$name, $email, $subject, $body, $cron);
if ($retVal == 1) {
$response = "Mail is put into database";
} else {
$response = "SQL error.";
}
exit(json_encode(array("response" => $response)));
} else {
exit(json_encode(array("response" => "not entered")));
}
?>
index.php
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.12/summernote.css" rel="stylesheet">
<style type="text/css">
textarea, input {
margin-bottom: 10px;
}
</style>
</head>
<body>
<div class="container" style="margin-top:100px;">
<div class="row justify-content-center">
<div class="col-md-6 col-md-offset-3">
<label for="name">Name:</label>
<input id="name" placeholder="Name" class="form-control" required>
<label for="email">E-mail:</label>
<input id="email" placeholder="E-mail" class="form-control" required>
<label for="subject">Subject:</label>
<input id="subject" placeholder="Name" class="form-control" required>
<!--<label for="body">Body:</label>-->
<textarea id="summernote" placeholder="Email body" name="editordata"></textarea>
<label for="cron">Crontab:</label>
<input id="cron" placeholder="CronTab Input" class="form-control">
<input type="button" onclick="saveMail()" value="Save it to Database" class="btn btn-success btn-info">
</div>
</div>
</div>
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<script type="text/javascript">
function isNotEmpty(caller) {
if (caller.val() == "") {
caller.css('border', '1px solid red');
return false;
} else {
caller.css('border', '');
return true;
}
}
function saveMail() {
console.log("SaVinG Attempt...");
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#summernote");
var cron = $("#cron");
if (isNotEmpty(cron)) {
$.ajax({
url: 'saveEmail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
subject: subject.val(),
body: body.val(),
cron: cron.val()
}, success: function (response) {
console.log(response);
}
});
}
}
</script>
<!-- WYSIWYG editor jses -->
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.12/summernote.js"></script>
<script>
$(document).ready(function() {
$('#summernote').summernote({
height: 300,
focus: true
});
});
</script>
</body>
</html>
It seems like you have an incorrect quotation mark in your saveEmail.php file. If you use code highlighting, it's easier to see. Instead of:
exit(json_encode(array("response" => "not entered”)));
Try:
exit(json_encode(array("response" => "not entered")));
EDIT:
To see what kind of error blocks your AJAX call, put these lines of call at the beginning of saveEmail.php:
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
Then temporarily change your ajax call to look like this:
$.ajax({
url: 'saveEmail.php',
method: 'POST',
data: {
name: name.val(),
email: email.val(),
subject: subject.val(),
body: body.val(),
cron: cron.val()
}, success: function (response) {
console.log(response);
} });
Related
I made a chat service in php. When you get to the chat, it says "Welcome, --Username--." My problem is I added a login field, now I can't send messages and the username isn't displayed. I've looked everywhere but it seems since my code is so "unique", nothing seems to be helping. --i didn't make this all on my own, I used someone else's code for the login and someone's code for the service itself.
login.php
<?php
session_start();
echo isset($_SESSION['login']);
if(isset($_SESSION['login'])) {
header('LOCATION:admin.php'); die();
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="text-center">Login</h3>
<?php
if(isset($_POST['submit'])){
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:admin.php'); die();
} {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
if($username === 'admon' && $password === 'password'){
$_SESSION['login'] = true; header('LOCATION:admin.php'); die();
} {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
}
?>
<form action="" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password" required>
</div>
<button type="submit" name="submit" class="btn btn-default">Login</button>
</form>
</div>
</body>
</html>
admin.php
<?php
session_start();
if(!isset($_SESSION['login'])) {
header('LOCATION:login.php'); die();
}
if(isset($_GET['logout'])){
//Simple exit message
$logout_message = "<div class='msgln'><span class='left-info'>User <b class='user-name-left'>". $_SESSION['name'] ."</b> has left the chat session.</span><br></div>";
file_put_contents("log.html", $logout_message, FILE_APPEND | LOCK_EX);
session_destroy();
header("Location: login.php"); //Redirect the user
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>English Pricks</title>
<meta name="description" content="A Group Chat." />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome, <b><?php echo $username['username']; ?></b>. Image Dump...</p>
<p>Emoji's → </p>
<button id="emoji-button" style="border: none;">😀</button>
<p class="logout"><a id="exit" href="#">Leave</a></p>
</div>
<div id="chatbox">
<?php
if(file_exists("log.html") && filesize("log.html") > 0){
$contents = file_get_contents("log.html");
echo $contents;
}
?>
</div>
<form name="message" action="">
<input name="usermsg" type="text" id="usermsg" style="outline: none;" spellcheck="true"/>
<input name="submitmsg" type="submit" id="submitmsg" value="↑" />
</form>
</div>
<script type="text/javascript" src="./jquery.min.js"></script>
<script src="emoji.js"></script>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function () {
var picker = new EmojiButton();
var button = document.querySelector('#emoji-button');
button.addEventListener('click', function () {
picker.showPicker(button);
picker.on('emoji', emoji => {
document.querySelector('#usermsg').value += emoji;
});
});
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$("#submitmsg").click(function(){
var clientmsg = $.trim($("#usermsg").val());
if(clientmsg.length >= 1){ // Prevents Spamming the Enter Key
$.post("post.php", {text: clientmsg});
$("#usermsg").val("");
}else{
}
return false;
});
function loadLog() {
var oldscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Scroll height before the request
$.ajax({
url: "log.html",
cache: false,
success: function (html) {
$("#chatbox").html(html); //Insert chat log into the #chatbox div
//Auto-scroll
var newscrollHeight = $("#chatbox")[0].scrollHeight - 20; //Scroll height after the request
if(newscrollHeight > oldscrollHeight){
$("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
}
}
});
}
setInterval (loadLog, 1000);
$("#exit").click(function () {
var exit = confirm("Are you sure you want to leave?");
if (exit == true) {
window.location = "index.php?logout=true";
}
});
});
</script>
</body>
</html>
In login.php file else was missing in if blocks and in order to see username you should add it to $_SESSION in the same way as you did with
$_SESSION['login'], cause i don't see anything else which can serve as temp storage in provided code. Another issue is that you placed header() function with login and password check right inside html code. This will trigger warning on a runtime that headers were already sent. In order to avoid that place your checking code in the top of the file and also check if there are no spaces before or after <?php php opening tag.
Example of fixed login.php file you can find below.
<?php
session_start();
function setSessionData($name, $value) {
$_SESSION[$name] = $value;
}
function redirectWithData($username = '') {
setSessionData('login', true);
setSessionData('username', $username);
header('Location:admin.php');
die();
}
if(isset($_SESSION['login'])) {
header('Location:admin.php'); die();
}
if(isset($_POST['submit'])) {
$username = $_POST['username']; $password = $_POST['password'];
if($username === 'admin' && $password === 'password'){
redirectWithData($username);
} elseif($username === 'admon' && $password === 'password'){
redirectWithData($username);
} else {
echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<title>Login</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h3 class="text-center">Login</h3>
<form action="" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username" required>
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="password" required>
</div>
<button type="submit" name="submit" class="btn btn-default">Login</button>
</form>
</div>
</body>
</html>
On admin page you can then display username
Welcome, <b><?php echo $_SESSION['username']; ?>
Regarding admin.php functionality. Logic for adding messages according to JavaScript code located in post.php file.
$.post("post.php", {text: clientmsg});
So, why its adding or not adding it is hard to answer for obvious reasons )
And btw, in your logout logic in admin.php file change
window.location = "index.php?logout=true"; -> window.location = "?logout=true"; it will fallback to the same page on which you already have redirect logic.
I want to move a value from page stepone php to page steptwo php
the value is generated automatically by js on stepone php,
and then I want to use the same value ( id for the submission ) on steptwo php
any ideas ?
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form action="action_pageone.php" method="POST">
<label for="FullName">Full Name</label><br>
<input type="text" id="FullName" name="FullName"><br>
<!-- this input -->
<input type="hidden" name="ID" id="ID" value="" maxlength="16" size="16">
<!-- this input -->
<input type="submit" value="Submit">
</form>
<script>
function randomNumber(len) {
var randomNumber;
var n = '';
for (var count = 0; count < len; count++) {
randomNumber = Math.floor(Math.random() * 10);
n += randomNumber.toString();
}
return n;
}
window.onload = function() {
document.getElementById("ID").value = randomNumber(9);
};
</script>
</body>
</html>
and the action_pageone here it is
so i need to copy this ID to the other page mentioned ( steptwo)
the exact ID
<?php
$ID = $_POST['ID'];
$FullName = $_POST['FullName'];
// Database Connection
$servername = "localhost";
$username = "";
$password = "";
$db = "";
$conn = new mysqli('localhost', 'username', 'password', 'db') or die($conn->connect_error);
$conn->set_charset("utf8");
if ($conn->connect_error){
die("Connection failed: ". $conn->connect_error);
}
$sql = "insert into Registration(ID,FullName) values('$ID','$FullName')";
if ($conn->query($sql) === TRUE) {
header('location: steptwo.php');
} else {
echo " Registration not Success ";
}
$conn->close();
?>
any suggestions guys ?
for me it doesnt matter if its js or php , i need it to work :(
You can use the Web Cache,like cookie or session,then use the php to read this ID value.
there is many ways to do it
use input type hidden and keep pushing it on submit buttons
pass it in URL like google.com?id=2&name=mike and fetch it using $_GET['id']
keep it in session/cookie/js webstorage
You can do this in 2 ways, use hidden form and submit it or use ajax to post it.
hidden form
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form action="action_pageone.php" method="POST" name="form1">
<label for="FullName">Full Name</label><br>
<input type="text" id="FullName" name="FullName"><br>
<!-- this input -->
<input type="hidden" name="ID" id="ID" value="" maxlength="16" size="16">
<!-- this input -->
<input type="button" onclick = "submit()" value="Submit">
</form>
<form action="action_pagetwo.php" method="POST" name="form2">
<!-- this input -->
<input type="hidden" name="ID" id="ID" value="" maxlength="16" size="16">
<!-- this input -->
</form>
<script>
function submit()
{
document.forms['form1'].submit();
document.forms['form2'].submit();
//wait what form to submit?.. confused...? yes me 2 lol
}
function randomNumber(len) {
var randomNumber;
var n = '';
for (var count = 0; count < len; count++) {
randomNumber = Math.floor(Math.random() * 10);
n += randomNumber.toString();
}
return n;
}
window.onload = function() {
document.getElementById("ID").value = randomNumber(9);
};
</script>
</body>
</html>
This might a way to achieve what you want but might be inappropriate as after the form gets submitted it actually redirects to the action page. But still you can sort out how you want your response by yourself.
Ajax (after receiving ID in your first php file you pass it to the second one)
<?php
$ID = $_POST['ID'];
$FullName = $_POST['FullName'];
if($ID != NULL)
echo '<script>
$.ajax({
url: "action_pagetwo.php",
type: "post",
data: {
id: '.$ID.'
},
success: function(result) {
console.log("done bro");
}
});
</script>';
// Database Connection
$servername = "localhost";
$username = "";
$password = "";
$db = "";
$conn = new mysqli('localhost', 'username', 'password', 'db') or die($conn->connect_error);
$conn->set_charset("utf8");
if ($conn->connect_error){
die("Connection failed: ". $conn->connect_error);
}
$sql = "insert into Registration(ID,FullName) values('$ID','$FullName')";
if ($conn->query($sql) === TRUE) {
header('location: steptwo.php');
} else {
echo " Registration not Success ";
}
$conn->close();
?>
You can pass the ID in your html page itself to both php files, but you should choose what you want, you want to pass it without redirecting or you wanna direct to page by submitting.
So, I am trying to retrieve data from my mysql database after a user registers or logins. The thing is that it somehow retrieves the letter "u" and that's weird, because there is no place that contains the letter "u".
This is the result I am getting as of now
https://imgur.com/t3XBrPN
index.php(where user registers or logs in)
<?php include('server.php') ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>PwettyKittyPincesa</title>
<link href="./style.css" type="text/css" rel="stylesheet" />
<script>
function start(){
closeForm();
closeRegForm();
}
function openForm() {
document.getElementById("myForm").style.display = "block";
closeRegForm();
}
function closeForm() {
document.getElementById("myForm").style.display = "none";
}
function openRegForm() {
document.getElementById("myRegForm").style.display = "block";
closeForm();
}
function closeRegForm() {
document.getElementById("myRegForm").style.display = "none";
}
</script>
</head>
<body onload="start()">
<nav>
<button class="button" type="submit" onclick="openForm()">Влез</button>
<button class="buttonReg" type="submit" onclick="openRegForm()">Регистрирай се</button>
<img src="Logo4.png" class="Logo" alt="Logo">
</nav>
<div class="form-popupRegister" id="myRegForm">
<form method="post" action="server.php" class="form-containerReg">
<h1>Регистрирация</h1>
<label for="username"><b>Име</b></label>
<input type="text" name="username" placeholder="Въведете името на лейдито" value="<?php echo $username; ?>">
<label for="email"><b>Е-майл</b></label>
<input type="email" name="email" placeholder="Въведете e-mail" value="<?php echo $email; ?>">
<label for="password_1"><b>Парола</b></label>
<input type="password" placeholder="Въведете парола" name="password_1">
<label for="password_2"><b>Повторете Парола</b></label>
<input type="password" placeholder="Въведете парола повторно" name="password_2">
<button type="submit" class="btnReg" name="reg_user">Register</button>
<button type="button" class="btn-cancelReg" onclick="closeRegForm()">Close</button>
</form>
</div>
<div class="form-popup" id="myForm">
<form method="post" action="server.php" class="form-container">
<h1>Влизане</h1>
<label for="username"><b>Име</b></label>
<input type="text" name="username" value="<?php echo $username; ?>">
<label for="password"><b>Парола</b></label>
<input type="password" name="password">
<button type="submit" class="btn" name="login_user">Login</button>
<button type="button" class="btn-cancel" onclick="closeForm()">Close</button>
</form>
</div>
</body>
</html>
index2.php(where the data should be output)
<?php include('server.php') ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>PwettyKittyPincesa</title>
<link href="./style.css" type="text/css" rel="stylesheet" />
<script>
function getUserStats(){
<?php
$queryThree = "SELECT * FROM `register` WHERE ID='$idQuery' ";
$userStats = mysqli_query($db,$queryThree);
$userStatsTwo = mysqli_fetch_assoc($userStats);
?>
}
</script>
</head>
<body onload="getUserStats()">
<div class="navWrapper">
<div class="statistics">
<div class="profilePicture" name="profilePicture">
<label class="profilePictureLabel" for="profilePicture"><b><?php echo userStatsTwo['username']; ?></b></label>
</div>
<div class="money" name="money">
<label class="rubyLabel" for="ruby"><b><?php echo userStatsTwo['money']; ?></b></label>
</div>
<div class="diamond" name="diamond">
<label class="diamondLabel" for="diamond"><b><?php echo userStatsTwo['diamonds']; ?></b></label>
</div>
<div class="ruby" name="ruby">
<label class="rubyLabel" for="ruby"><b><?php echo userStatsTwo['ruby']; ?></b></label>
</div>
<div class="level" name="level">
<label class="levelLabel" for="level"><b>Level:<?php echo userStatsTwo['level']; ?></b></label>
</div>
</div>
</div>
</body>
</html>
server.php(where the data is being processed)
<?php
session_start();
// initializing variables
$username = "";
$email = "";
$idQuery = "";
$errors = array();
// connect to the database
$db = mysqli_connect('localhost', 'id9159890_uregisterdb', 'censored', 'id9159890_registerdb');
// REGISTER USER
if (isset($_POST['reg_user'])) {
// receive all input values from the form
$username = mysqli_real_escape_string($db, $_POST['username']);
$email = mysqli_real_escape_string($db, $_POST['email']);
$password_1 = mysqli_real_escape_string($db, $_POST['password_1']);
$password_2 = mysqli_real_escape_string($db, $_POST['password_2']);
// form validation: ensure that the form is correctly filled ...
// by adding (array_push()) corresponding error unto $errors array
if (empty($username)) { array_push($errors, "Username is required"); }
if (empty($email)) { array_push($errors, "Email is required"); }
if (empty($password_1)) { array_push($errors, "Password is required"); }
if ($password_1 != $password_2) {
array_push($errors, "The two passwords do not match");
}
// first check the database to make sure
// a user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM `register` WHERE username='$username' OR email='$email' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
if ($user) { // if user exists
if ($user['username'] === $username) {
array_push($errors, "Username already exists");
}
if ($user['email'] === $email) {
array_push($errors, "email already exists");
}
}
// Finally, register user if there are no errors in the form
if (count($errors) == 0) {
$password = md5($password_1);//encrypt the password before saving in the database
$query = "INSERT INTO `register` (username, password, email, money, ruby, diamonds, levelpoints, level)
VALUES ('$username', '$password', '$email', '0', '0', '0', '0', '0')";
mysqli_query($db, $query);
$idQuery = "SELECT ID FROM `register` WHERE username='$username'";
mysqli_query($db, $idQuery);
$_SESSION['username'] = $username;
$_SESSION['userid'] = $idQuery;
$_SESSION['success'] = "You are now logged in";
header('location: index2.php');
}
}
// LOGIN USER
if (isset($_POST['login_user'])) {
$username = mysqli_real_escape_string($db, $_POST['username']);
$password = mysqli_real_escape_string($db, $_POST['password']);
if (empty($username)) {
array_push($errors, "Username is required");
}
if (empty($password)) {
array_push($errors, "Password is required");
}
if (count($errors) == 0) {
$password = md5($password);
$query = "SELECT * FROM `register` WHERE username='$username'";
$results = mysqli_query($db, $query);
if (mysqli_num_rows($results) == 1) {
$_SESSION['username'] = $username;
$_SESSION['success'] = "You are now logged in";
header('location: index2.php');
}else {
array_push($errors, "Wrong username/password combination");
}
}
}
?>
The results that I should be getting are(from top to bottom and left to right)
Username, Level, Money, Diamond, Ruby and their values should respectively be Username, 0, 0, 0, 0.
I've tried everything and nothing changes, I've re-constructed my code twice and it still outputs only that and nothing else.
You have an issue here in your code:
$idQuery = "SELECT ID FROM `register` WHERE username='$username'";
mysqli_query($db, $idQuery);
$_SESSION['username'] = $username;
$_SESSION['userid'] = $idQuery;
As i mentioned in my comment, check what are you getting in echo "SELECT * FROM register WHERE ID='$idQuery' "; you definitely getting this kind of result:
SELECT * FROM register` WHERE ID= 'SELECT ID FROM `register` WHERE username='somename''
For sub query, remove quotes around your variable from:
"SELECT * FROM register` WHERE ID='$idQuery' ";
should be:
"SELECT * FROM register` WHERE ID = $idQuery";
Note that, this is success case, as you show your result here https://imgur.com/P64hqvI, your query is working fine..
You also need to use some protection for $idQuery if $idQuery == '' then your you can't get any result also.
As #patrick-q mentioned, use session to store username or ID instead of saving a full query.
Second, you code is wide open for SQL injection, for preventing, use PDO.
Some helpful links:
Are PDO prepared statements sufficient to prevent SQL injection?
How can I prevent SQL injection in PHP?
Hi I'm currently working on codeigniter framework and I'm currently working on a project which is basically an admin/employee login system.
Currently I have been able to create a login form, and can successfully get a user to login, after having checked the user exists.
I just wanted to be pointed in the right direction as to how I could go about this to be able to login an employee user to an employees page, and an admin user to an admin page.
This is what I have at the moment, which is fully functioning using bootstrap as a front end framework. But allows any user to login.
By the way I have only one table name "employees" which consist only for employee user and admin user from mysql database.
Here is the view: (login.php)
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=1,initial-scale=1,user-scalable=1" />
<title> Login Form </title>
<link href="http://fonts.googleapis.com/css?family=Lato:100italic,100,300italic,300,400italic,400,700italic,700,900italic,900" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="<?php echo base_url()?>assets/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="<?php echo base_url()?>assets/css/styles.css" />
<script src="<?php echo base_url()?>assets/js/bootstrap.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<script>
$(document).ready(function () {
var elements = document.getElementsByTagName("INPUT");
for (var i = 0; i < elements.length; i++) {
elements[i].oninvalid = function (e) {
e.target.setCustomValidity("");
if (!e.target.validity.valid) {
switch (e.srcElement.id) {
case "username":
e.target.setCustomValidity("Username cannot be blank");
break;
case "pass":
e.target.setCustomValidity("Password cannot be blank");
break;
}
}
};
elements[i].oninput = function (e) {
e.target.setCustomValidity("");
};
}
})
</script>
<style type="text/css">
.back{
position: absolute;
bottom: 0px;
left: 0px;
}
</style>
<section class="container">
<section class="login-form">
<form class="form-signin" action="goClock" method="post" role="login">
<img src="<?php echo base_url()?>assets/images/easypay.png" class="img-responsive center-block" alt="" />
<input type="text" class="form-control input-lg" placeholder="username" name='user' required id="username" autocomplete="off" autofocus />
<input type="password" class="form-control input-lg" placeholder="Password" name='password' required id="pass" required />
<?php
if(!empty($login_error)) {
echo $login_error;
}
?>
<button name='login' class="btn btn-lg btn-block btn-primary" value=" LOGIN " type="submit" id="button2">Login</button>
</form>
<p class="text-center" style="font-weight: bold; font-size: 60;" id="demo"></p>
<script>
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}
</script>
</section>
</section>
<div class="back">
<input class="btn btn-warning" action="action" type="button" value="<- Back" onclick="location.href = 'index';" />
</div>
</body>
</html>
Here is the controller: (home.php)
public function goClock($message = null) {
$this->load->view('imports/header');
$this->load->view('imports/menu');
if (!is_null($this->input->post('login'))) {
$username = $this->input->post('user');
$password = $this->input->post('password');
$userdata = $this->model_home->get_userinfo($username, $password);
$_SESSION['is_loggedin'] = true;
if ($userdata !== false) {
$this->session->set_userdata($userdata);
redirect('home/goHome');
}else {
$data['login_error'] = '<p style="font-size: 16px; color: red;" align="center">Invalid Username or Password</p>';
$this->load->view('login', $data);
}
}else {
$data['username'] = $this->input->post('user');
$data['password'] = $this->input->post('password');
$this->load->view('clock', $data);
}
}
And finally here is the model: (model_home.php)
public function get_userinfo($username = null, $password = null) {
if ($username && $password) {
$this->db->select('username, password, empnum');
$this->db->where('username', $username);
$this->db->where('password', $password);
$query = $this->db->get('employees');
if ($query->num_rows()) {
return $query->result_array()[0];
}
}
return false;
}
Just to clarify I have only one controller, my main controller by default which is home.php. In conclusion my aim is to be able to redirect an admin user to admin.php and to be able to redirect a employee user to employee.php (Hasn't been created yet).
P.S I already have a column in my table in PhpMyAdmin called "employees".
Please help me. Thank you in advance.
you should add one extra column in Database named as user_type and Set default value=0 for that and for "admin" set it 1.
Now modify your query like this:
if ($username && $password) {
$this->db->select('username, password, empnum,user_type');
$this->db->where('username', $username);
$this->db->where('password', $password);
$query = $this->db->get('employees');
if ($query->num_rows()) {
return $query->result_array()[0];
}
}
Now check the $userdata[] array value having user_type key if it is 1 then
$this->load->view('admin', $data);
else he is user_type = 0 which means employee
$this->load->view('employee', $data);
NOTE:I can provide the way but here you have to modify your array key and view name as per the need.
First create a filed with name usertype in your database employees table.
Run this query in your phpMyadmin database
ALTER TABLE `employees` ADD `usertype` ENUM('user','employee') NOT NULL DEFAULT 'user' ;
and add following code on your Model
public function get_userinfo($username = null, $password = null) {
if ($username && $password) {
$this->db->select('username, password, empnum,usertype');
$this->db->where('username', $username);
$this->db->where('password', $password);
$query = $this->db->get('employees');
if ($query->num_rows()) {
return $query->row();
}
}
return false;
}
And on your controller
public function goClock($message = null) {
$this->load->view('imports/header');
$this->load->view('imports/menu');
if (!is_null($this->input->post('login'))) {
$username = $this->input->post('user');
$password = $this->input->post('password');
$userdata = $this->model_home->get_userinfo($username, $password);
$_SESSION['is_loggedin'] = true;
if ($userdata !== false) {
if($userdata->usertype=='user'){ # if user then redirect to user page
redirect('home/goHome');
}else{
# If employee redirect to admin page
}
}else {
$data['login_error'] = '<p style="font-size: 16px; color: red;" align="center">Invalid Username or Password</p>';
$this->load->view('login', $data);
}
}else {
$data['username'] = $this->input->post('user');
$data['password'] = $this->input->post('password');
$this->load->view('clock', $data);
}
}
after implementing a jquery form validation and redirecting with function btn_onclick()
{ window.location.href = "http://localhost/loginprivate.php";} from index.php to loginprivate.php my webapps php script wont be executed. The user become trough a javascript function and window.location.href from index.php redirected loginprivate.php you can see here. After the first pageload the page become loaded again with <script src="loadagain.js"></script> this works fine too.
Now the problem is that if I click the submit button the php code wont become executed, that can I see because no cookies become created, and the user become redirected to index.php.
my php code:
if(isset($_POST["submit"]))
{
$hostname='localhost';
$username='root';
$password='';
unset($_POST['password']);
$salt = '';
for ($i = 0; $i < 22; $i++) {
$salt .= substr('./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', mt_rand(0, 63), 1);
}
$_POST['password'] = crypt($_POST['password'],'$2a$10$'.$salt);
$new = 0;
try {
$dbh = new PDO("mysql:host=$hostname;dbname=search",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "INSERT INTO users (username, password)
VALUES ('".$_POST["username"]."','".$_POST["password"]."')";
if ($dbh->query($sql)) {
echo "New Record Inserted Successfully";
}
else{
echo "Data not successfully Inserted.";
}
$new = $dbh->lastInsertId();
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
if ($new > 0)
{
$t = time() + 60 * 60 * 24 * 1000;
setcookie("username", $_POST['username'], $t);
setcookie("userid", $new , $t);
}
else
{
}
}
my html code:
<head>
<meta charset="UTF-8" />
<title>
HTML Document Structure
</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<link rel="stylesheet" href="themes/my-costum-theme.min.css" />
<link rel="stylesheet" href="themes/jquery.mobile.icons.min.css" />
<script src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile.structure-1.4.5.min.css" />
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.14.0/jquery.validate.min.js"></script>
<!-- Einstellungen zur Defintion als WebApp -->
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<script src="loadagain.js"></script>
<script>
$(document).ready(function () {
$('#myform').ajaxForm();
$('#myform').validate({ // initialize the plugin
rules: {
username: {
required: true,
minlength: 2,
maxlength: 30
},
password: {
required: true,
minlength: 3,
maxlength: 30
}
},
submitHandler: function (form) { // for demo
$.ajax({
type: 'post',
url: 'loginprivate.php' //url where you want to post the stuff.
data:{
username: 'root',
password: 'maxicora123'
},
success: function(res){
//here you will get res as response from php page, either logged in or some error.
window.location.href = "http://localhost/loc/main.php";
}
});
return false; // for demo
}
});
});
</script>
</head>
<body>
<div class="ui-page" data-theme="b" data-role="page">
<div data-role="header"><h1>localcorps</h1></div>
<div id="wrapper1" style=" width: 90%; padding-right:5%; padding-left:5%" name="wrapper1">
<form name="login-form" id="myform" class="login-form" action="./loginprivate.php" method="post">
<div class="header1"></div>
<div class="content1">
<div data-role="fieldcontain">
<label for="username">Username:</label>
<input name="username" type="text" class="input username" id="username"/>
</div>
</div>
<div data-role="fieldcontain">
<label for="password">Password:</label>
<input name="password" type="password" class="input password" id="password"/>
</div>
<div class="footer">
<input type="submit" name="submit" value="Login" class="button"/>
</div>
</form>
</div>
</div>
</div>
</body>
According to your comment, I get now only this "Array ( )" on my screen. it means that you ain't posting anything to PHP page.
That's just because, you're redirecting the control to PHP page instead of submitting the form.
so, you can validate the code using jQuery and on successful validation do a ajax post request instead of shifting the control.window.location.href = "http://localhost/lak/main.php";
instead of shifting control, do a post.
$.ajax({
type: 'post',
url: 'loginprivate.php' //url where you want to post the stuff.
data:{
username: 'someUserName',
password: 'xxxxxxxxxxxx'
},
success: function(res){
//here you will get res as response from php page, either logged in or some error.
//and if you're logged in successfully, redirect here now.
}
});
Hope this will help.