In these days I tried to write a sort of registration-login system with php and mySql and somehow I managed to do it; now I want to put all the things in a new page with a pop up window: you press the button "register" or "login" and on the screen appears a window with all the stuff and things, that's what I did:
<!DOCTYPE html>
<html>
<head>
<title>FindMyChamp</title>
</head>
<body>
<style type="text/css">
.popUpBox{
display: none;
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
background-color: rgba(0,0,0,0.4);
}
.popUpBoxBody{
margin: 15% auto;
padding: 15px;
background-color: #fefefe;
width: 30%;
}
.closeBtn{
float: right;
font-size: 28px;
}
.container{
width: 300px;
clear: both;
display: block;
margin-left: auto;
margin-right: auto;
text-align: center;
}
.container input{
width: 100%;
clear: both;
}
#send{
width: 50%;
}
</style>
<h1>Test</h1>
<p id="popUpTrigger">Register</p>
<p>Login</p>
<div id="divPopUp" class="popUpBox">
<div class="popUpBoxBody">
<span id="popUpCloser" class="closeBtn">×</span>
<div class="container">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Username: <input type="text" name="username">
Password: <input type="password" name="password">
Repeat Password: <input type="password" name="passwordCheck"><br><br>
<input value="Send" id="send" type="submit" name="sub">
</form>
<?php include('registration.php') ?>
</div>
</div>
</div>
<script type="text/javascript">
var btnOpen = document.getElementById("popUpTrigger");
var popUp = document.getElementById("divPopUp");
var btnClose = document.getElementById("popUpCloser")
btnOpen.onclick = function(){
popUp.style.display = "block";
}
btnClose.onclick = function(){
popUp.style.display ="none";
}
</script>
register.php:
<?php
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if(isset($_POST["sub"])){
$username = $password = $passwordCheck = "";
$flag = true;
$con = mysql_connect('localhost','root','Testpass');
if($_SERVER["REQUEST_METHOD"] == "POST"){
//Controllo se i campi sono vuoti
if(empty($_POST["username"])){
echo "The field 'Username' is required<br>";
} else{
$username = test_input($_POST["username"]);
}
if(empty($_POST["password"])){
echo "The field 'Password' is required<br>";
$flag = false;
} else{
$password = test_input($_POST["password"]);
}
if(empty($_POST["passwordCheck"])){
echo "The field 'Repeat Password' is required<br>";
$flag = false;
} else{
$passwordCheck = test_input($_POST["passwordCheck"]);
}
}
if($password == $passwordCheck && $password != ""){
mysql_select_db('tutorials');
$checkUsernameDuplicate = mysql_query("SELECT * FROM registration WHERE username = '$username'");
if(mysql_num_rows($checkUsernameDuplicate) <= 0){
$cost = 10;
$salt = strtr(base64_encode(mcrypt_create_iv(16,MCRYPT_DEV_URANDOM)), '+', '.');
$salt = sprintf("$2a$%02d$", $cost). $salt;
$hash = crypt($password, $salt);
$sql = "INSERT INTO registration(username,password) VALUES('$username','$hash')";
$retvalue = mysql_query($sql,$con);
if(!$retvalue){
echo "Something went wrong";
} else{
echo "Dati inseriti";
//header("Location: http://localhost/database/login.php");
exit();
}
} else{
echo "Username aldready taken";
}
mysql_close($con);
}
elseif($flag){
echo "<p style='color: red;'>The two password must match</p>";
}
}
?>
Everything works fine, but, when I press the button 'send' the window disappears and all the datas are send to the database, that's ok but I want that the windows remains until the user decides to close it. How can I do that?
use ajax, you can execute your code in register.php without refreshing your page
http://api.jquery.com/jquery.ajax/
Related
I'm working on a project, using PHP, HTML and CSS code. The problem is when I execute it without CSS code it works, but when I add CSS to it the message "successfully created" will be displayed on the bottom status bar of the webpage! Why does this happen and why won't it be displayed on the page?
This is my HTML code:
<div class="bg">
<p>Register | Login</p>
<h3>Registration Form</h3>
<form action="register.php" method = "POST">
Email: <input type = "text" name = "email"><br />
Username: <input type = "text" name = "user"><br />
Password: <input type = "password" name = "pass"><br />
<input type = "submit" value = "Login" name = "submit" />
</form>
</div>
This is my PHP code:
if (isset($_POST["submit"])) {
$email = $_POST['email'];
$user = $_POST['user'];
$pass = $_POST['pass'];
$connection = mysqli_connect('localhost' , 'root' , '', 'website') or die(mysqli_error());
mysqli_select_db($connection , "website") or die("can not select database");
if ($connection) {
$query = mysqli_query($connection ,"SELECT * FROM users WHERE username = '".$user."'");
$numOfRows = mysqli_num_rows($query);
if ($numOfRows == 0){
$sql = "INSERT INTO users( email ,username , password) VALUES('$email', '$user' , '$pass')";
$result = mysqli_query($connection , $sql);
if($result) {
echo "successfully Created";
} else {
echo "failure!";
}
} else {
echo "Username already exist!";
}
} else {
echo "can not connect to database";
}
}
This is my CSS code:
body, html {
height: 100%;
margin: 0;
}
.bg {
background-image: url("SARV.jpg");
height: 100%;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
Because you echo in plain text instead of handling it into your html code. Take a look into your output html.
I have a admin panel for login. I have created a login page with php,
html, java script. I used session to pass user to next page. This working perfectly on my localhost. But on live server i am getting problem, its showing me "loged in successfully" popup and redirecting back to login page. When i print session on localhost its showing me session value but on live server its empty. I have searched so many answers and tried same but still it's not working. Please help and thank you for your time and consideration.
My live server is Apache HTTP Server Version 2.2
My connection file db.php is
<?php
/*Default time zone ,to be able to send mail */
date_default_timezone_set('Asia/Kolkata');
//connect database
$con = mysqli_connect ("localhost","rootuser","password","testdbname"); //host, username, password, database name
//database connect error
if (mysqli_connect_errno())
{
echo "Failed to connect to MySql: " . mysqli_connect_errno();
}
?>
login.php file is
<?php
session_start();
include("includes/db.php");
if(isset($_SESSION['mysesiuid']))
{
header('Location: index.php?alreadyin');
//echo "<script>window.location.assign('index.php?alreadyin')</script>";
}
else
{
?>
<script src="assets/js/validate/jquery.js" type="text/javascript"></script>
<script>
//login script
$(document).ready(function() {
var mazalagna_login_email1 = 1;
var mazalagna_login_email2 = 1;
var mazalagna_login_email3 = 1;
var mazalagna_login_password = 1;
$("#main_login_submit").click(function(){
//password
if($("#mazalagna_pass").val() == ''){
$("#mazalagna_pass").css("border","1px solid red");
$("#mazalagna_password_error").show();
mazalagna_login_password = 1;
}else{
if($("#mazalagna_pass").val().length < 6){
$("#mazalagna_pass").css("border","1px solid red");
$("#mazalagna_password_length_error_longform").show();
$("#mazalagna_password_error").hide();
mazalagna_login_password = 1;
}else{
$("#mazalagna_pass").css("border","1px solid green");
$("#mazalagna_password_length_error_longform").hide();
$("#mazalagna_password_error").hide();
mazalagna_login_password = 0;
}
}
//email
var pattern = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")#(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
var validateMazalagnaEmail = pattern.test($("#mazalagna_email").val());
if($("#mazalagna_email").val() == ''){
$("#mazalagna_email").css("border","1px solid red");
$("#mazalagna_email_error").show();
mazalagna_login_email1 = 1;
}else{
$("#mazalagna_email").css("border","1px solid green");
$("#mazalagna_email_error").hide();
mazalagna_login_email1 = 0;
}
if(!validateMazalagnaEmail){
$("#mazalagna_email").css("border","1px solid red");
$("#mazalagna_email_error").show();
mazalagna_login_email2 = 1;
}else{
$("#mazalagna_email").css("border","1px solid green");
$("#mazalagna_email_error").hide();
mazalagna_login_email2 = 0;
}
if(validateMazalagnaEmail){
$.ajax({
type: "POST",
cache: false,
url: "php/ajax_email_exist.php",
data: { email: $("#mazalagna_email").val()},
success: function (data)
{
if(data != 1){
$("#mazalagna_email").css("border","1px solid green");
$("#mazalagna_exist_email_error").hide();
mazalagna_login_email3 = 0;
}else{
$("#mazalagna_email").css("border","1px solid red");
$("#mazalagna_exist_email_error").show();
mazalagna_login_email3 = 1;
}
if(mazalagna_login_email1 == 0 && mazalagna_login_email2 == 0 && mazalagna_login_email3 == 0 && mazalagna_login_password == 0 ){
$.ajax({
type: "POST",
cache: false,
url: "main_login.php",
data: {
username1: $("#mazalagna_email").val(),
password1: $("#mazalagna_pass").val()
},
success: function (data)
{
alert(data);
//alert("Welcome! You have loged in successfully!");
window.location.replace("index.php");
}
});
}
}
});
}
//edit value
$(".regval").click(function(){
var id = "#"+$(this).attr("id");
var errorId = "#"+$(this).attr("id")+"_error";
$(id).css("border","1px solid #a39e9e");
$(errorId).hide();
});
});
});
</script>
<strong> Enter Details To Login </strong>
<!-- <form role="form" action="" method="post"> -->
<div class="form-group input-group">
<span class="input-group-addon"><i class="fa fa-tag" ></i></span>
<input type="text" id="mazalagna_email" name="mazalagna_email" class="form-control regval" placeholder="Your Username" required />
</div>
<div id="mazalagna_email_error" style="display:none; margin-top:-12px; margin-bottom:12px; text-align:center; color:red; font-size:12px;">Please enter valid Email</div>
<div id="mazalagna_exist_email_error" style="display:none; margin-top:-12px; margin-bottom:12px; text-align:center; color:red; font-size:12px;">Your email id is not registered.</div>
<div class="form-group input-group">
<span class="input-group-addon"><i class="fa fa-lock" ></i></span>
<input type="password" id="mazalagna_pass" name="mazalagna_pass" class="form-control regval" placeholder="Your Password" required />
</div>
<div id="mazalagna_password_error" style="display:none; margin-top:-12px; margin-bottom:12px; text-align:center; color:red; font-size:12px;">Please enter your password</div>
<div id="mazalagna_password_length_error_longform" style="display:none; margin-top:-12px; margin-bottom:12px; text-align:center; color:red; font-size:12px;">Enter min 6 character password</div>
<button type="submit" id="main_login_submit" name="main_login_submit" class="btn btn-primary ">Login Now</button>
<hr />
<!-- </form> -->
<?php } // top else close here ?>
My main_login.php file is
<?php
//connect database
session_start();
require_once 'includes/db.php';
global $con;
$user_email = trim($_POST['username1']);
$user_password = trim($_POST['password1']);
$password = mysqli_real_escape_string($con, md5($user_password));
$res = $con->query("SELECT * FROM useradmins WHERE email='$user_email' AND password='$password'");
$row = $res->fetch_assoc();
$uid = $row['admin_id'];
$name = $row['name'];
$useremail = $row['email'];
$pass = $row['password'];
if($useremail==$user_email && $pass==$password){
$_SESSION['mysesi']=$name;
$_SESSION['mysesiuid']=$useremail;
echo "Loged in successfully.";
//update status and login time
date_default_timezone_set('Asia/Kolkata');
$date_email = date('F j, Y h:i A');
$date = date('Y-m-d H:i:s');
$user = $_SESSION['mysesiuid'];
$ip = $_SERVER['REMOTE_ADDR'];
$httpref = $_SERVER['HTTP_REFERER'];
$httpagent = $_SERVER['HTTP_USER_AGENT'];
$update_last_login="UPDATE useradmins SET admin_status='ONLINE',active_ip_address='$ip',admin_last_login='$date' WHERE admin_id='$user'";
$update_last_login = mysqli_query($con, $update_last_login);
}
else{
echo "Unable to login.";
}
?>
index.php file is
<?php
session_start();
require_once 'includes/db.php';
if(!isset($_SESSION['mysesiuid']))
{
header('Location: login.php');
exit;
}
else
{
?>
<h1>hi success</h1>
<?php } ?> <!-- top else statement close here -->
I've been working on this nonstop and none of the online suggestions have worked.
I have a dynamically created table that refreshes every 5 seconds. There are checkboxes on the table, if you check a box it highlights the row. When the page refreshes all checked states are lost, I need them to be saved, either by local storage or a cookie or even writing out to a file.
Please help and thanks in advance.
My currently working code that does not retain the checked state:
<HTML>
<HEAD>
<TITLE>list</TITLE>
<META name="description" content="">
<META name="keywords" content="">
<meta http-equiv="refresh" content="5" >
<style>
.inv {
display: none;
}
table.sortable thead {
background-color:#999;
color:#222222;
font-weight: bold;
cursor: default;
}
table.sortable tbody {
counter-reset: sortabletablescope;
}
table.sortable thead tr::before {
content: "";
display: table-cell;
}
table.sortable tbody tr::before {
content: counter(sortabletablescope);
counter-increment: sortabletablescope;
display: table-cell;
}
</style>
<script src="../../sorttable.js"></script>
<script>
function toggle_highlight(inputTagReference)
{
var is_checked = inputTagReference.checked; //true or false
if(is_checked)
{
inputTagReference.parentNode.parentNode.style.backgroundColor="yellow";
}
else
{
inputTagReference.parentNode.parentNode.style.backgroundColor="";
}
}
</script>
</HEAD>
<BODY BGCOLOR="#dddddd" TEXT="#000000" LINK="#0000FF" VLINK="#800080">
<h1 align="center">List</h1>
<p align="center"> </p>
<p align="center">
<?php
echo '<div>';
//Create file with headers
system("cmd /C makeit.bat");
//Create html table
echo '<p align="center"> </p>';
echo '<p align="center"> </p>';
echo '<table class="sortable" align="center">';
$row = 0;
$handle = fopen("readylist.txt", "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($row == 0) {
// this is the first line of the file
// it contains titles of columns
$num = count($data);
echo "<thead>\n<tr>";
$row++;
for ($c=0; $c < $num; $c++) {
echo "<th align='left' height='75' width='135'>" . $data[$c] . "</th>";
}
echo "<td></td>";
echo "</tr>\n</thead>\n\n<tbody>";
} else {
// this handles the rest of the lines of the file
$num = count($data);
echo "<tr id=Row0$row>";
$row++;
for ($c=0; $c < $num; $c++) {
echo "<td id=Col0$c>" . $data[$c] . "</td>";
}
echo "<td><input type='checkbox' name='Chk$row id=Chk$row' value='Chk$row' onclick='toggle_highlight(this)'></td>";
echo "</tr>\n";
}
}
fclose($handle);
echo "</tbody>\n</table>";
echo '</div>';
?>
</p>
</BODY>
</HTML>
Here it is with nonworking solution:
<HTML>
<HEAD>
<TITLE>list</TITLE>
<META name="description" content="">
<META name="keywords" content="">
<meta http-equiv="refresh" content="5" >
<style>
#checkbox-container{
margin: 10px 5px;
}
#checkbox-container div{
margin-bottom: 5px;
}
#checkbox-container button{
margin-top: 5px;
}
input[type=text] {
padding: .5em .6em;
display: inline-block;
border: 1px solid #ccc;
box-shadow: inset 0 1px 3px #ddd;
border-radius: 4px;
}
.inv {
display: none;
}
table.sortable thead {
background-color:#999;
color:#222222;
font-weight: bold;
cursor: default;
}
table.sortable tbody {
counter-reset: sortabletablescope;
}
table.sortable thead tr::before {
content: "";
display: table-cell;
}
table.sortable tbody tr::before {
content: counter(sortabletablescope);
counter-increment: sortabletablescope;
display: table-cell;
}
</style>
<script src="../../sorttable.js"></script>
<script src="../../jquery.js"></script>
<script>
var formValues = JSON.parse(localStorage.getItem('formValues')) || {};
var $checkboxes = $("#checkbox-container :checkbox");
var $button = $("#checkbox-container button");
function allChecked(){
return $checkboxes.length === $checkboxes.filter(":checked").length;
}
function updateButtonStatus(){
$button.text(allChecked()? "Uncheck all" : "Check all");
}
function handleButtonClick(){
$checkboxes.prop("checked", allChecked()? false : true)
}
function updateStorage(){
$checkboxes.each(function(){
formValues[this.id] = this.checked;
});
formValues["buttonText"] = $button.text();
localStorage.setItem("formValues", JSON.stringify(formValues));
}
$button.on("click", function() {
handleButtonClick();
updateButtonStatus();
updateStorage();
});
$checkboxes.on("change", function(){
updateButtonStatus();
updateStorage();
});
// On page load
$.each(formValues, function(key, value) {
$("#" + key).prop('checked', value);
});
$button.text(formValues["buttonText"]);
</script>
<script>
function toggle_highlight(inputTagReference)
{
var is_checked = inputTagReference.checked; //true or false
if(is_checked)
{
inputTagReference.parentNode.parentNode.style.backgroundColor="yellow";
}
else
{
inputTagReference.parentNode.parentNode.style.backgroundColor="";
}
}
</script>
</HEAD>
<BODY BGCOLOR="#dddddd" TEXT="#000000" LINK="#0000FF" VLINK="#800080">
<h1 align="center">List</h1>
<p align="center"> </p>
<p align="center">
<?php
echo '<div id="checkbox-container">';
//Create file with headers
system("cmd /C makeit.bat");
//Create html table
echo '<p align="center"> </p>';
echo '<p align="center"> </p>';
echo '<table class="sortable" align="center">';
$row = 0;
$handle = fopen("readylist.txt", "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if ($row == 0) {
// this is the first line of the file
// it contains titles of columns
$num = count($data);
echo "<thead>\n<tr>";
$row++;
for ($c=0; $c < $num; $c++) {
echo "<th align='left' height='75' width='135'>" . $data[$c] . "</th>";
}
echo "<td></td>";
echo "</tr>\n</thead>\n\n<tbody>";
} else {
// this handles the rest of the lines of the file
$num = count($data);
echo "<tr id=Row0$row>";
$row++;
for ($c=0; $c < $num; $c++) {
echo "<td id=Col0$c>" . $data[$c] . "</td>";
}
echo "<td><input type='checkbox' name='Chk$row id=Chk$row' value='Chk$row' onclick='toggle_highlight(this)'></td>";
echo "</tr>\n";
}
}
fclose($handle);
echo "</tbody>\n</table>";
echo '</div>';
?>
</p>
</BODY>
</HTML>
here is the code from the page that answered the persistent checkbox question, this page works for me, but the code from it on my page does not.
<html >
<head>
<meta charset="UTF-8">
<title>CodePen - A Pen by SitePoint</title>
<style>
#checkbox-container{
margin: 10px 5px;
}
#checkbox-container div{
margin-bottom: 5px;
}
#checkbox-container button{
margin-top: 5px;
}
input[type=text] {
padding: .5em .6em;
display: inline-block;
border: 1px solid #ccc;
box-shadow: inset 0 1px 3px #ddd;
border-radius: 4px;
}
</style>
</head>
<body translate="no" >
<input type="text" placeholder="Type something here" />
<div id="checkbox-container">
<div>
<label for="option1">Option 1</label>
<input type="checkbox" id="option1">
</div>
<div>
<label for="option2">Option 2</label>
<input type="checkbox" id="option2">
</div>
<div>
<label for="option3">Option 3</label>
<input type="checkbox" id="option3">
</div>
<button>Check All</button>
</div>
<script src='../../jquery.js'></script>
<script>
var formValues = JSON.parse(localStorage.getItem('formValues')) || {};
var $checkboxes = $('#checkbox-container :checkbox');
var $button = $('#checkbox-container button');
function allChecked() {
return $checkboxes.length === $checkboxes.filter(':checked').length;
}
function updateButtonStatus() {
$button.text(allChecked() ? 'Uncheck all' : 'Check all');
}
function handleButtonClick() {
$checkboxes.prop('checked', allChecked() ? false : true);
}
function updateStorage() {
$checkboxes.each(function () {
formValues[this.id] = this.checked;
});
formValues['buttonText'] = $button.text();
localStorage.setItem('formValues', JSON.stringify(formValues));
}
$button.on('click', function () {
handleButtonClick();
updateButtonStatus();
updateStorage();
});
$checkboxes.on('change', function () {
updateButtonStatus();
updateStorage();
});
$.each(formValues, function (key, value) {
$('#' + key).prop('checked', value);
});
$button.text(formValues['buttonText']);
//# sourceURL=pen.js
</script>
</body>
</html>
Well, it's been a day, and I don't see anything here.
My assumption is that you guys are finding this just as difficult as I am.
I am still working on this and here is my logic.
I will have to get the insidehtml of one of the cells in the row as part of the onclick event, then set a cookie or use session to store the variable based on the row, and then an onload event that reads that session or cookie and checks the appropriate boxes and highlights the appropriate rows.
If anyone has any comments or suggestions, they are entirely welcome.
tia
I am making a Ajax driven live search . But now I want to click the dropdown list to fill the html textbox. How can I modify my codes to include a function where the user can scroll through the results list using the up/down arrow keys. Here is the JavaScript code.
<script type="text/javascript">
function fill(Value) {
$('#name').val(Value);
$('#display').hide();
}
$(document).ready(function() {
$("#name").keyup(function() {
var name = $('#name').val();
if (name == "") {
$("#display").html("");
} else {
$.ajax({
type: "POST",
url: "ajax.php",
data: "name=" + name,
success: function(html) {
$("#display").html(html).show();
}
});
}
});
});
and here is the code in ajax.php page
if(isset($_POST['name'])) {
$name=trim($_POST['name']);
$query=mysqli_query($con,"SELECT * FROM mobile WHERE name LIKE '%$name%' LIMIT 0,5");
echo "<ul>";
while($query2=mysqli_fetch_array($query))
{ ?>
<div class="ajaxcontainer">
<li onclick='fill("<?php echo $query2[' name ']; ?>")'>
<a href="preview.php?id=<?php echo $query2['name']; ?>">
<div class="ajaximage">
<img src="<?php echo $query2['photo'];?>">
</div>
<div class="ajaxh1">
<h1><?php echo $query2['name']; ?></h1>
</div>
</a>
</li>
</div>
<?php } } ?>
good news.. after working 3 hours.. i got the solution to ur problem. Checkout the solution. let me know if you have any problems in this solution.I
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<style type="text/css">
ul{
position: absolute;
top: 5px;
left: 36px;
list-style: none;
}
li{
border: 1px solid grey;
width: 202px;
margin: 0px;
}
input{
width:200px;
}
</style>
<script>
function showHint(str){
if(str=="" || !str){
$("ul").empty();
return;
}
$.ajax({
type: "GET",
url: "gethint.php",
data: "q="+str,
success: function(html) {
var names = html.split(",");
var listItems ="";
var dropDown =$("#dropDown");
dropDown.innerHTML="";
$("ul").empty();
names.forEach(name =>{
var li = document.createElement("li");
li.appendChild(document.createTextNode(name));
dropDown.append(li);
$("li").click(function(){
$("#txt1").val($(this).text());
});
});
}
});
}
</script>
<h3>Start typing a name in the input field below:</h3>
<form action="">
<div style="position:relative">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)">
<ul id="dropDown"></ul>
</div>
</form>
</body>
</html>
This is my php file.
<?php
require("connection.php");
$sql ="SELECT name FROM users";
$a=array();
// OR $a=[];
$result=$conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$a[]=$row["name"];
//echo $row["name"];
}
}
else{
echo "No data to generate suggestions";
}
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
?>
I have a blog system where I use a form to create a blog post. Here's what the form looks like: http://prntscr.com/7wupnn (As you can see, I've made a bit bold and changed the colour).
Here's the source of that form:
<?php
session_start();
include('db_connect.php');
if(!isset($_SESSION['user_id'])){
header('Location: login.php');
exit();
}
if(isset($_POST['submit'])){
$title = $_POST['title'];
$body = $_POST['body'];
$category = $_POST['category'];
$title = $db->real_escape_string($title);
$body = $db->real_escape_string($body);
$user_id = $_SESSION['user_id'];
$date = date('Y-m-d G:i:s');
$body = htmlentities($body);
if($title && $body && $category){
$query = $db->query("INSERT INTO posts (user_id, title, body, category_id, posted) VALUES('$user_id', '$title', '$body', '$category', '$date')");
if($query){
echo '<div style="position:absolute; bottom: 40px; left: 500px; padding: 10px; background: red; box-shadow: 0px 3px 12px 2px #000; color: #fff;">Post Added</div>';
}else{
echo '<div style="position:absolute; bottom: 40px; left: 500px; padding: 10px; background: red; box-shadow: 0px 3px 12px 2px #000; color: #fff;">An unexpected error has occured.</div>';
}
}else{
echo '<div style="position:absolute; bottom: 40px; left: 500px; padding: 10px; background: red; box-shadow: 0px 3px 12px 2px #000; color: #fff;">Please enter all the required information to proceed</div>';
}
}
?>
<div id="mainbox">
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post" enctype="multipart/form-data">
<input type="text" name="title" placeholder="Enter Post Title Here">
<p></p>
<textarea name="body" id="mytextarea" cols=50 rows=10 placeholder="Enter Post Content Here"></textarea>
<script>
CKEDITOR.replace( 'mytextarea' );
</script>
<p></p>
<input type="file" name="upfile">
<select name="category">
<?php
$query = $db->query("SELECT * FROM categories");
while($row = $query->fetch_object()){
echo "<option value='".$row->category_id."'>".$row->category."</option>";
}
?>
</select>
<p></p>
<input type="submit" name="submit" value="Submit">
</form>
</div>
When I click submit, the post is then published onto the blog page - however it's lost all it's style - here's what I mean: http://prntscr.com/7wuq9f - as you can see, the browser is displaying the HTML rather than using it.
Here's the code for he blog page:
<?php
include('blog/db_connect.php');
$record_count = $db->query("SELECT * FROM posts");
$per_page = 2;
$pages = ceil($record_count->num_rows/$per_page);
if(isset($_GET['p']) && is_numeric($_GET['p'])){
$page = $_GET['p'];
}else{
$page = 1;
}
if($page<=0)
$start = 0;
else
$start = $page * $per_page - $per_page;
$prev = $page - 1;
$next = $page + 1;
$query = $db->prepare("SELECT post_id, title, LEFT(body, 100) AS body, category FROM posts INNER JOIN categories ON categories.category_id=posts.category_id order by post_id desc limit $start, $per_page");
$query->execute();
$query->bind_result($post_id, $title, $body, $category);
?>
<div id="mainbox">
<?php
while($query->fetch()):
$html_body = nl2br($body);
$lastspace = strrpos($html_body, ' ');
?>
<h2><?php echo $title?></h2>
<p><?php echo substr($html_body, 0, $lastspace)."<a href='blog/post.php?id=$post_id'>..</a>"?></p>
<p>Category: <?php echo $category?>
<hr />
<p></p>
<?php endwhile?>
<?php
if($prev > 0){
echo "<a href='blog.php?p=$prev'>Previous Page</a>";
}
if($page < $pages){
echo "<a href='blog.php?p=$next'>Next Page</a>";
}
?>
Instructions on how to keep the style of the text when publishing it would be appreciated.