get data from xampp sql server using html and php - javascript

I'm a complete beginner in php and I am working on a front end project where I have to create a hangman game based on 12 island names stored in a mysql xampp server . I have to get a random island from the database as an unordered string displayed in my html and guess which island it is . I have no idea how to implement this using php since I am a complete beginner but I have watched tutorials about how to send data from html forms to an sql server with php . I guess this is kinf of the opposite task .
I have written complete html css and js code about displaying my hangman game and I use a simple word to be displayed randomly via javascript and when you fill the spaces a submit button appears .
function hangman(){
var island = "Santorini"; //the given word that is supposed to be found
var t = document.createTextNode(shuffleWord(island))
document.getElementById("hidden-word").appendChild(t);
createSpaces(island);
const inputLists = document.querySelectorAll("input");
document.querySelectorAll("input").forEach(el => {
el.addEventListener('input', evt => {
const showButton = [...inputLists].filter(ip => ip.value.trim() !== '').length === inputLists.length;
document.getElementById('submitbtn').style.display = showButton ? 'block' : 'none';
});
});
}
function shuffleWord (word){
var shuffledWord = '';
word = word.split('');
while (word.length > 0) {
shuffledWord += word.splice(word.length * Math.random() << 0, 1);
}
return shuffledWord;
}
function createSpaces(text){
for(var i=0;i<text.length;i++){
var space = document.createElement("input");
space.setAttribute("class" , "dash");
document.getElementById("hangman-container").appendChild(space);
}
}
.transparent-box{
border:none;
position:absolute;
top:10%;
left:15%;
background-color:black;
height:500px;
width:70%;
opacity: 0.6;
}
.transparent-box p{
color:white;
text-align:center;
}
.transparent-box h1{
color:white;
position: relative;
text-align:center;
font-size:20px;
top:30px;
}
#hangman-container{
position: relative;
width:auto;
top:30%;
left:0%;
background-color: transparent;
display: flex;
flex-direction: row;
justify-content: space-evenly;
}
.dash{
margin:0;
padding:20px;
align-items: flex-start;
width:4%;
border:none;
border-radius: 5%;
background-color: turquoise;
color:red;
font-size:40px;
}
.dash:focus{
opacity:0.8;
}
#submitbtn{
display: none;
position: absolute;
top:200%;
left:80%;
float:right;
}
<body onload=hangman()>
<div class="transparent-box" id="t-box">
<p>Play here </p>
<h1 id="hidden-word">The word is : </h1>
<form id="hangman-container" method="POST">
<button type="submit" class="hide" id="submitbtn">Submit</button>
</form>
</div>
</body>
The problem is how to use php to get a random island name from my database and display it instead of sending a string via javascript .
I would appreciate your help with this . Thank you in advance .

First create a table:
CREATE TABLE islands(
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL
);
Insert the islands names there (add as many as you wish in place of the ...):
INSERT INTO islands(name) VALUES
("Santorini"),("Tassos"),...;
Now the following SELECT query will fetch one random island name from the DB:
SELECT name
FROM islands
ORDER BY RAND()
LIMIT 1;
In PHP you can execute the query like this:
// replace the words in uppercase with your actual credentials!
$link = #mysqli_connect('localhost','USERNAME','PASSWORD','DBNAME');
if(!$link){
echo 'Error connecting to the DB';
exit;
}
$sql = "SELECT name FROM islands ORDER BY RAND() LIMIT 1";
$result = #mysqli_query($link, $sql);
if(!$result){
echo 'There is an issue with the database';
exit;
}
$row = #mysqli_fetch_assoc($result);
// This will give you the random island name (if they are inserted properly)
echo $row['name']??'No islands are inserted in the database yet';
Now to shuffle it, we can use str_shuffle() function. Finally your code may start to look like this:
<body onload=hangman()>
<div class="transparent-box" id="t-box">
<p>Play here </p>
<h1 id="hidden-word">The word is :
<?php
// replace the words in uppercase with your actual credentials!
$link = #mysqli_connect('localhost','USERNAME','PASSWORD','DBNAME');
if(!$link){
echo 'Error connecting to the DB';
exit;
}
$sql = "SELECT name FROM islands ORDER BY RAND() LIMIT 1";
$result = #mysqli_query($link, $sql);
if(!$result){
echo 'There is an issue with the database';
exit;
}
$row = #mysqli_fetch_assoc($result);
echo str_shuffle($row['name']);
?>
</h1>
<form id="hangman-container" method="POST">
<button type="submit" class="hide" id="submitbtn">Submit</button>
</form>
</div>
</body>
Now you will need to adjust your JavaScript code of course.

Related

How to stop <li> elements from overlapping? [duplicate]

This question already has answers here:
Is there ever any reason to use padding-top and padding-bottom for inline elements?
(1 answer)
Padding for Inline Elements
(3 answers)
Closed 4 years ago.
This is my code
ul li{
display:inline;
}
li {
padding: 10px;
border: 1px solid brown;
margin-right: 5px;
position: relative;
background-color: Bisque ;
}
<div class="fr_station">
<span id="route">
<?php
// print_r($route);
$pLine = 0;
$cLine = 0;
echo "<ul>";
foreach ($route as $value) {
$result = mysqli_query($conn,'select station,line,stnCode from stn_name where stnCode='.$value.' LIMIT 1') or die(mysqli_error());
$res = mysqli_fetch_array($result);
echo "<li>".$res['station']."</li>";
//echo str_repeat(" ", 3);
if (!isset($previous)) {
$previous = $source;
$present = $source;
} else {
$current = $value;
$d_result = mysqli_query($conn,'SELECT * FROM alt_station_data WHERE stnCode ='.$previous.' AND nei='.$current.' LIMIT 1');
$d_res = mysqli_fetch_array($d_result);
$tot_dist += $d_res['dis'];
$previous = $value;
echo "</tr>";
$floored = floor($tot_dist);
}
}
echo "</ul>";
echo "</span>";
echo "<br>";
echo "</div>";
When I am printing the elements then the elements from 2nd line is overlapping with the ones on the first line and so on at the end of the line it is printing half content on one line and remaining content on next line.
Try this:
li {
display: inline-block;
}
By using inline each li behaves like a word so doesn’t have it’s own ‘box’. inline-block lets them sit side-by-side but gives each one it’s own ‘box’.
If you need even more control then start looking at flex-box: https://css-tricks.com/snippets/css/a-guide-to-flexbox/ and https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Flexible_Box_Layout but don’t forget you will need flex-wrap: wrap
On a side note, with your example it would be easier if you just provide the outputted HTML without the php code as that’s not required. :)

Insert Icon inside Javascript - PHP dropdown

I have a dropdown menu geneated by php and javascript. The code is the below one:
<script type="text/javascript">
$(document).ready(function() {
<?php $query = "sp_region_info 0";
$select_region_query = sqlsrv_query($con, $query);
while ($row = sqlsrv_fetch_array($select_region_query)) {
$region_id = $row['region_id'];
$region_name = $row['region_name'];
$result_array[]= $region_name;
}
$json_array = json_encode($result_array);
?>
var country = <?php echo $json_array; ?>;
$("#region").select2({
data: country
});
});
</script>
<div class="input-group col-sm-3 search">
<label class="bd-form-label">Destination</label>
<select id="country"></select>
</div>
It is working properly I can search and use it as dropdown.
I was wonder whats the way to display next to results an icon?
e.g
That's my result: https://i.stack.imgur.com/b2FhA.png
And I need to display my Icon next to Destination title:
https://i.stack.imgur.com/Bq0Z0.png
I tried by adding <i class="fa fa-map-marker"></i> inside my div but doesnt work..
Any thoughts ?
You can't use <i> tag in select option, instead you can use unicode:
while ($row = sqlsrv_fetch_array($select_region_query)) {
$region_id = $row['region_id'];
$region_name = $row['region_name'] . ' ';
$result_array[]= $region_name;
}
and use this css:
.select2-results__option {
font-family: 'FontAwesome', 'Tahoma'
}
Example
OR a simpler solution is using pseudo element:
.select2-results__option::after {
content: "\f041";
font-family: FontAwesome;
}
Example
Add the <i> within your while loop like this:
while ($row = sqlsrv_fetch_array($select_region_query)) {
$region_id = $row['region_id'];
$region_name = $row['region_name'].'';
$result_array[]= $region_name;
}
you can do it just using css, for example:
.select2-results__option:after {
content: '\F041';
font-family: FontAwesome;
font-size: 20px;
color: pink;
}
Thats work for me)

Retrieving id error from jQuery and PHP Chat

I have some problems on the retrieving id from php on mysql, somewhat, for what I found out, is that the id is saving somewhere (eg: something like a cache) where it saves it and create a loop when I don't ask for a loop.
For example
you can see the chat windows. Where it shows the user you are talking and the list of user which are online. (Like facebook)
The problem here is that when I toggle where it says "Nuno Monteiro" chat message. it hides it, and goes to the id "1" in this case but if I click on "Joane" and do that the id it will show as "1" and after "2".
And when I go back to "Nuno" I can not toggle and hide again but it gives me the id as "1" then "2" then "1" again "2" like that.
What I want is to pick just the current id from the function callID(id) and just select that one.
Here below you have the code:
dashboard.php:
<div class="chat-data" id="chat-data" style="display:none;">
<?php
for ($i = 0; $i < count($result); $i++) {
if($result[$i]['online'] == 0) {
echo "<span onclick='callID(".$result[$i]['id'].");' class='user-btn".$result[$i]['id']."' style='padding: 7px; display:inline-block; position: relative; border-bottom: 1px solid #ccc; width: 100%; cursor: pointer;'><span class='offline'></span> ".$result[$i]['firstname']." ".$result[$i]['lastname']."</span>";
} else {
echo "<span onclick='callID(".$result[$i]['id'].");' class='user-btn".$result[$i]['id']."' style='padding: 7px; display:inline-block; position: relative; border-bottom: 1px solid #ccc; width: 100%; cursor: pointer;'><span class='online'></span> ".$result[$i]['firstname']." ".$result[$i]['lastname']."</span>";
}
}
?>
</div>
This is the part from the chat(1) window.
The part of "Nuno Monteiro" window is also from dashboard.php, which is the following code:
<div class="chat-user" style="display: none;">
<div class='user-title'>
<span class="titles"></span>
<span class='pull-right remove_field'>X</span>
</div>
<div class="chat-time">
<div class="msg_data" id="msg_data">
<div class="friend_pic pull-left">
<img src="<?php echo $domain; ?>resources/img/babox_logo.png" data-toggle="tooltip" data-placement="bottom" title="Nuno Monteiro" />
</div>
<div class="friend">
<span>Hey There are you ok?</span>
</div>
<div class="your_pic pull-right">
<img src="<?php echo $domain; ?>resources/img/babox_logo.png" data-toggle="tooltip" data-placement="bottom" title="You" />
</div>
<div class="you">
<span>I am fine!</span>
</div>
</div>
<div class="msg_box" id="msg_box">
<textarea id="chatbox"></textarea>
</div>
</div>
</div>
The $domain variable is where I get my website name so I don't need to change it in every code I have and change it only there.
That is picking up results from $db = new DbManager(); and the variable $result will execute the select by doing: $result = $db->execute_select($sql)
The $sql variable is: "SELECT * FROM users";
Then we going pass through our jQuery function (which I mention above):
function callID(id) {
$(".chat-time").prop("id",id);
$(".chat-user").hide();
$(".remove_field").click(function() {
$(".chat-user").hide();
});
$.post('callID.php', {id : id }, function(rID) {
// nothing on here
$(".user-title").click(function(e) {
$('#' + rID).toggle();
e.preventDefault();
alert(rID);
});
if(id == rID) {
$(".chat-user").show();
$(".user-title span.titles").html($(".user-btn" + rID).text());
} else {
$(".chat-user").hide();
}
});
}
this is part from my general.js script.
Then the script will go pick the information to the callID.php:
<?php
include('application/database/dbmanager.php');
$db = new DbManager();
$sql = "SELECT id FROM users WHERE id='".$_POST['id']."'";
$db->execute_select($sql);
echo $_POST['id'];
?>
What I wanted to happen is that when I toggle in the online user chat on each username, go pick only the id of that user, so later I can save the messages in database and pick it up.

Checking if searched item exists in database - PHP won't output anything but will still add item to the database

I'm learning PHP and am looking to solve my PHP, JS and SQL issue.
If necessary, to ensure you understand exactly what the issue is, you may need you to set up the HTML, CSS, PHP and JS to work with your SQL database. I ask of your time only if you have it.
As you can probably tell, I have a search bar. The user types their interest into the search bar and it adds that interest to the database. If their interest exists in the database (as in someone else has the same interest) it uses an if statement to say so. However, for some reason it will not do anything if an interest is found (not even that test alert). It will however insert something into the database (in this case the number of other existing interests) which is very strange. I have inserted comments in the PHP file to explain what is happening and where the issue is.
Here is the PHP, JS, CSS and HTML respectively:
<?php
error_reporting(E_ALL ^ E_NOTICE);//TO REMOVE THE ANNOYING KEYWORD ERRORS
function connect() {
return new PDO('mysql:host=localhost;dbname=mysite', 'username', 'pw', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
//GET THE USERS IP
if(!empty($_SERVER['HTTP_CLIENT_IP'])){
$ip=$_SERVER['HTTP_CLIENT_IP'];
}
elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
$ip=$_SERVER['HTTP_X_FORWARDED_FOR'];
}
else{
$ip=$_SERVER['REMOTE_ADDR'];
}
$pdo = connect();
//OUTPUT THE SEARCHBAR SUGGESTIONS (OBTAIN SUGGESTIONS FROM DATABASE)
$testing = '%'.$_POST['keyword'].'%';
$sql = "SELECT * FROM interests WHERE interestName LIKE (:testing) ORDER BY id ASC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->bindParam(':testing', $testing, PDO::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach ($list as $rs) {
$interestName = str_replace($_POST['keyword'], '<b>'.$_POST['keyword'].'</b>', $rs['interestName']);
$interestlist = '<li onclick="set_item(\''.str_replace("'", "\'", $rs['interestName']).'\')">'.$interestName.'</li>';
if (strlen($_POST['keyword']) > 0){
echo $interestlist; //THIS IS THE SUGGESTION BAR OUTPUT WITH THE SUGGESTIONS
}
}
//EVERYTHING ABOVE THIS WORKS.. THIS IS THE ISSUE HOWEVER:
if(isset($_POST['counter'])=="counter"){
//INSERT THE INTEREST INTO THE DATABASE, WITH THE USER'S IP.
$interestid=$_POST['interestinput'];
$insertion = "INSERT INTO users (ipaddress, interest)
VALUES ('$ip', '$interestid')";
$pdo->query($insertion);
//INSERTION WORKS. NOW I WANT TO CHECK IF INTEREST EXISTS. IF IT DOES EXIST, PRINT 'Users exist!':
$item ="SELECT * FROM `users` WHERE interest LIKE '$interestid'";
$result = $pdo->query($item)->fetchAll();
$counted = count($result); //COUNT NUMBER OF RESULTS, THEN INSERT IT AS A TEST.
$insertion = "INSERT INTO users (ipaddress, interest)
VALUES ('$ip', '$counted')";
if (count($result) > 1) {
$pdo->query($insertion); //TEST IF IT WORKS -- THIS INSERTS THE TOTAL NUMBER OF SAME INTERESTS. IT WORKS!
//BUT..
echo ("Users exist!"); //THIS DOES NOTHING? <--------- THE ISSUE
echo "<script> alert('Test'); </script>"; //THIS ALSO DOES NOTHING (as a test)
}
}
?>
//THIS FUNCTION IS CALLED WHEN THE USER HITS ENTER:
function enterPressed(e, field) {
if (e.keyCode == 13) {
var tb = document.getElementById("searchbox");
if (field.value.length > 0) {
document.getElementById('searching').style.display='block';
document.getElementById('searchdisappear').style.display='none';
$.ajax({
type: 'POST',
url: './php/phprefresh.php',
data: {interestinput: field.value, counter: "counter"},
});
}
}
}
//THIS FUNCTION GIVES INTEREST SUGGESTIONS (PULLED FROM THE DATABASE):
function autocomplet() {
var workchecker = 0
var min_length = 1;
var keyword = $('#searchbox').val();
if (keyword.length == min_length) {
$.ajax({
url: './php/phprefresh.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#interest_list_id').show();
$('#interest_list_id').html(data);
}
});
} else {
$('#interest_list_id').hide();
}
}
//THIS FUNCTION SETS THE SUGGESTION INTO THE SEARCH BOX WHEN CLICKED
function set_item(item) {
$('#searchbox').val(item);
$('#interest_list_id').hide();
}
/*Input*/
input.interestsearch {
margin: auto;
margin-top: 30px;
width: 540px;
height: 30px;
font-size: 22px;
display: block;
padding: 2px 2px 2px 8px;
outline: none;
}
.input_container {
padding: auto;
margin: auto;
margin-top: -10px;
width: 520px;
display: block;
outline: none;
font-size: 20px;
}
.input_container ul {
list-style: none;
border-radius: 15px;
padding: 5px;
color: black;
}
.input_container ul li:hover {
border: 1px solid black;
border-radius: 15px;
cursor: pointer;
width: 500px
}
<!DOCTYPE html>
<html lang = "en">
<head>
<title>Testsite</title>
<link rel="stylesheet" type="text/css" href="./css/main.css">
<script src ="./js/search.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
</head>
<body">
<!-- SEARCH BAR -->
<div id="searchdisappear" style="display:block;">
<center><h1> INTEREST SEARCH </h1></center>
<input class="interestsearch" id="searchbox" maxlength="200" type="text" title="Search for an interest" onkeyup="autocomplet();" autocomplete="off" onkeypress="enterPressed(event, searchbox);" placeholder="Search for an interest.."/>
<div class="input_container">
<ul id="interest_list_id"></ul>
</div>
</div>
<!-- CONNECTING PEOPLE WITH SAME INTEREST-->
<div id="searching" style="display:none;">
<center> <p>Finding people..</p></center>
</div>
</html>
Do not hesitate to ask any questions about the code. I am happy to answer anything!
I really appreciate anyone's time. It has been driving me crazy for far too long.
Add a
<div id="response"></div>
to your HTML which will display the result then add a success: argument in the enterPressed function. ie.
function enterPressed(e, field) {
if (e.keyCode == 13) {
var tb = document.getElementById("searchbox");
if (field.value.length > 0) {
document.getElementById('searching').style.display='block';
document.getElementById('searchdisappear').style.display='none';
$.ajax({
type: 'POST',
url: './php/phprefresh.php',
data: {interestinput: field.value, counter: "counter"},
success: function() {
$("#response").html("<p>User Exists</p>");
}
});
}
}
}
If you want to display echo text (in HTML form) from phprefresh.php change the success: to
success: function(data) {
$("#response").html(data);
}

Pass info from text input through jquery in to php, which returns json, need to parse the return

I am getting a return of undefined. I don't even know what to do. So lost...
html
<!DOCTYPE html>
<html>
<head>
<!--Jquery CDN-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<!--Local files attached-->
<script type="text/javascript" src="CountryList.js"></script>
<link rel="stylesheet" type="text/css" href="CountryList.css" />
</head>
<body>
<div id="wrapper">
<!--Header-->
<h1>Country Information</h1>
<!--input box-->
<form>
<label for="countryInput">Input Country Name : </label>
<input type="text" id="countryInput"></input>
</form>
<br>
<br>
<!--Containing divs for lists-->
<div id="wrapper2">
<!--countries will load here-->
<div id="countryList">
Countries:
<div id="actualList">
</div>
</div>
<!--country info will load here-->
<div id="countryInfo">
Country Info:
<div id="actualInfo">
</div>
</div>
</div>
</div>
</body>
<div id="footer">
<!--Link to page-->
</div>
</html>
css
body{
margin-top:3%;
background-color:white;
text-align:center;
}
h1 {
}
h2 {
font-size:14pt;
}
#header {
color:white;
text-align:center;
padding:5px;
}
#footer {
color:white;
text-align:center;
padding:5px;
}
#countryList {
text-align:center;
overflow:auto;
width: 10%;
height: 400px;
border: 1px solid black;
display: inline-block;
float:left;
margin-left:20%;
}
#countryInfo {
text-align:center;
overflow:auto;
width: 49%;
height: 400px;
margin-right: 20%;
border: 1px solid black;
display: inline-block;
float:right;
}
button {
margin-left:15px;
margin-top:10px;
padding:5px;
margin-bottom:10px;
}
Javascript:
$(document).ready( function(){
var fieldInput = "";
var countrylist = "";
var countryinfo = "";
var countryjson = "getCountryListAsJSON.php";
$( "#countryInput" ).keyup(function( event ) {
fieldInput = $(this).val();
// show that something is loading
$('#actualList').html("<b>Loading response...</b>");
$.ajax({
type: 'GET',
url: countryjson,
data: fieldInput,
dataType: "json"
})
.success(function(data){
alert("success");
countrylist =data;
console.log(countrylist[1]);
$('#actualList').html(countrylist);
})
.done(function(data){
})
.fail(function() {
// just in case posting your form failed
$('#actualList').html("Failed to find countries.");
});
});
$( "#countryInput" ).focus(function() {
$("#countryInput").val("");
$("#actualInfo").html("");
$("#actualList").html("");
fieldInput="";
});
});;
the php script that was provided
<?php
// Name: getCountryListAsJSON.php
// Desc: Gets a sorted list of country names from the world DB which
// begin with the specified letters
// Params: country - beginning string of letters to match
// Outputs: JSON encoded array of country names (strings)
//get argument if provided
if(isset($_GET['country']))
$country = $_GET['country'];
else
$country = "no country specified!"; //will match nothing
//connect to database
$con = mysqli_connect("localhost", "worlddemo", "worldpass", "world")
or die("Some error occurred during connection " . mysqli_error($con));
//run query
$query = "SELECT * FROM country WHERE Name LIKE '$country%' ORDER BY name";
$results = mysqli_query($con, $query);
//build an array of strings (country names) from results
$countryList = array();
while($row = mysqli_fetch_array($results))
{
$countryList[] = htmlentities($row['Name'], ENT_COMPAT, 'UTF-8');
//note: special characters caused problems, hence htmlentities
}
//finish up
mysqli_close($con);
echo json_encode($countryList);
?>
I only get it returned as an undefined.
So I am trying to pass whatever is put in the text input to php.
For each key it is supposed to return a list of countries from a Database (hosted on my localhost xampp)
Im not sure whether its a problem with my teachers PHP or if I am just missing something in my code. I have been trying to just get it to write out in the console to see if I am getting a proper return, but the only thing that seems to be happening is it is returning undefined.
link to the world db http://downloads.mysql.com/docs/world.sql.zip
Access "getCountryListAsJSON.php" file directly from your browser (http://your-server/getCountryListAsJSON.php) and see what happens. If its all ok on the server side, you should see something like this on the page: ["country1", "country2", "country3", ... ]
Another thing you can try is change your success callback to something like this:
.success(function(data){
//alert("success");
var countrylist = data;
var html = "";
for( var i in countryList ){
html += countryList[i];
}
$('#actualList').html(html);
})

Categories

Resources