I have phpbb forum and I wanted to add a field in the registration page...the modification was to enable the user to choose their role .. for example to be a moderator .. or to be a normal member or .. I am actually making the forum a bit private and I am grouping users in groups so they have a restricted access to some forums. Anyways I have the html template file and I want to get the dropdown menu list from a php file code
here is my code of the php
<?php
include '/blah/config.php';
$con = mysql_connect($dbhost, $dbuser, $dbpasswd);
if(!$con)
{
die("Couldn't Connect: ".mysql.error());
}
mysql_select_db($dbname, $con);
$result = mysql_query("SELECT group_name FROM phpbb_groups");
$array = array();
while($row = mysql_fetch_array($result))
{
$array[] = $row[0];
}
mysql_close($con);
foreach( $array as $group_name)
{
echo $group_name."</br>"; // I want to put this value in the dropdown list in the html file
}
?>
here is the part of the html code that I want to edit
<dt><label>GroupID:</label></dt>
<dd><select name="group_id" id="group_id"" tabindex="7" class="autowidth">I want to get the data from php in here</select></dd>
PS: the template file is HTML file and can't be renamed to php
Okay, sorry about the last answer, didnt read your PS there...
Here's a jQuery solution, uses JSON as an output from your PHP file then an asynchronous request to fill in the dropdown.
PHP Code
// The rest of your code, then output your $array this way
header("Content-type: application/json");
$array = array("banana", "apple", "eggroll");
echo json_encode($array);
die;
Your HTML (example)
Make sure you add jquery into your HEAD if you dont already have it.
<dt><label>GroupID:</label></dt>
<dd><select name="group_id" id="group_id"" tabindex="7" class="autowidth"></select></dd>
<script>
$(document).ready(function() {
$.get('sefesf.php', {"q":"1"}, function(data) {
if(data.length > 0)
{
for(var i = 0; i < data.length; i ++)
{
$('select#group_id').append('<option>' + data[i] + '</option>');
}
}
});
});
</script>
Be sure to change sefesf.php to your php file with the json output and {"q":"1"} to {} if you dont need any GET parameters sent.
Related
I have one file 1.2MB and in it, there are 36k+ lines of text and probably growing. The problem is that I want to display all the lines from input.txt but since there are too many lines I get out with a browser crash...What I have tried so far is:
<?php
$handle = fopen("input.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
echo '<li class="list-group-item d-flex justify-content-between align-items-center">'.$line.'</li>';
}
fclose($handle);
} else {
echo 'error';
}
?>
This code works for files that are about 40KB approx 1400lines anything more will result in a crash...
After that I thought if I load that file to db and then conn with php and get data from base I will be able to display all lines, but again I was wrong
<?php
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ime_pjesme FROM pjesme";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<li class="list-group-item d-flex justify-content-between align-items-center">'. $row["ime_pjesme"].'</li>';
}
} else {
echo "0 results";
}
$conn->close();
?>
So my question is is there any way/method I could use to get those lines displayed in browser or is there way to load it and then display 50 by 50 etc?
Yes, there is a way to display the file a page at a time.
There are many libraries that will do it nicely for you, but to understand the mechanisms, here's how to do it with just the jQuery library and some PHP.
Simply put, you need two files. The first will display the page counter/selector and the area where the rows will appear. Say that you want 50 rows at a time:
$pages = floor(($rownumber + 50 - 1)/ 50);
print "<ul class=\"pageselect\">";
for ($i = 0; $i < $pages; $i++) {
$p = $i + 1;
print "<li data-page=\"{$p}\">Page {$p}</li>";
}
print "</ul>";
You organize the CSS so that the LI elements are all nice, centered and horizontal. Then you use e.g. jQuery to attach an event handler to the clicking on one of those LI's by delegating to the parent UL, in Javascript:
$('ul.pageselect').on('click', 'li', function() {
var wanted = $(this).attr('data-page');
$.post('/path/to/page_load.php', { page: wanted })
.then(reply => {
// "reply" is the object returned by the loader PHP.
$('#lines').empty();
for (var l = 0; l < reply.lines.length; l++) {
$('#lines').append($('<p>').text(reply.lines[l]));
}
});
});
The delegate function issues an AJAX POST call to the second PHP file, and expect a JSON reply (called reply here) to be processed.
The above will kill the contents of a DIV such as <div id="lines"></div> and fill it with as many P's as there are lines in the loader reply.
The loader receives a parameter which is the page number, translates it to an absolute line number, runs the select and returns everything in JSON format:
$from = (((int)$_POST['page'])-1) * 50;
if ($from < 0) { $from = 0; }
// Run a SELECT with OFFSET {$from},50 to fetch at most 50 rows
$reply = [
'total' => $total, // use SQL_CALC_FOUND_ROWS to get the total number
'lines' => [ ]
];
while ($rs->fetch(PDO::PDO_FETCH_ASSOC) as $line) {
$reply['lines'] = "This line is {$line['text']}.";
}
header('Content-Type: application/json; charset=UTF8');
// Return JSON encoding of $reply to the caller.
exit(json_encode($reply));
You will find the browser tools invaluable to inspect what's going on with the AJAX calls. The "loader" file you will be able to recycle later with most of the niftier libraries.
This block of PHP code prints out some information from a file in the directory, but I want the information printed out by echo to be used inside the HTML below it. Any help how to do this? Am I even asking this question right? Thanks.
if(array_pop($words) == "fulltrajectory.xyz") {
$DIR = explode("/",htmlspecialchars($_GET["name"]));
$truncatedDIR = array_pop($DIR);
$truncatedDIR2 = ''.implode("/",$DIR);
$conffile = fopen("/var/www/scmods/fileviewer/".$truncatedDIR2."/conf.txt",'r');
$line = trim(fgets($conffile));
while(!feof($conffile)) {
$words = preg_split('/\s+/',$line);
if(strcmp($words[0],"FROZENATOMS") == 0) {
print_r($words);
$frozen = implode(",", array_slice(preg_split('/\s+/',$line), 1));
}
$line = trim(fgets($conffile));
}
echo $frozen . "<br>";
}
?>
The above code prints out some information using an echo. The information printed out in that echo I want in the HTML code below where it has $PRINTHERE. How do I get it to do that? Thanks.
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno=[$PRINTHERE]; halos on;", "frozen on")
You just need to make sure that your file is a php file..
Then you can use html tags with php scripts, no need to add it using JS.
It's as simple as this:
<div>
<?php echo $PRINTHERE; ?>
</div>
Do remember that PHP is server-side and JS is client-side. But if you really want to do that, you can pass a php variable like this:
<script>
var print = <?php echo $PRINTHERE; ?>;
$("#btns").html(Jmol.jmolButton(jmolApplet0, "select atomno="+print+"; halos on;", "frozen on"));
</script>
I'm doing a project for an exam. I'm stuck with that and I hope someone of you could help me (I'm italian, so sorry for my bad english!).
I have to query an existing database stored in phpmyadmin with a PHP script. Then, the query result need to be parsed with a jquery script and printed to an HTML page.
Here is the PHP script:
<?php
$con = mysql_connect('localhost', 'root', '');
if (!$con) {
die('Errore di connessione: ' . mysql_error());
}
mysql_select_db("progetto_lpw", $con);
$sql="SELECT denominazione FROM farmacia";
$result = mysql_query($sql) or die(mysql_error());
$num=mysql_numrows($result);
while($row = mysql_fetch_array($result)){
print json_encode($row['denominazione']);
print "<br />";
}
?>
I've already tested the PHP script calling it via browser and it works.
Then, I parse the result with this jquery script (the use of this combination is a requirement of the project):
$("#button").click(function(){
$.getJSON('json.php', function(data) {
$.each(data, function(index,value){
$("#xx").append("<p>"+value+"</p>")
})
})
})
Here is the problem: when I open the HTML page and I click the button on firefox, consolle says "no element found" referring to PHP script.
"xx" is the id of the div in which elements are printed.
Where is the error?
Thanks to everyone.
Replace below code
while ($row = mysql_fetch_array($result)) {
print json_encode($row['denominazione']);
print "<br />";
}
With below code and try
$rows = array();
while ($row = mysql_fetch_array($result)) {
$rows[] = $row['denominazione'];
}
header('Content-type: application/json');
echo json_encode($rows);
HTML
<button id="button">Fetch JSON</button>
<div id="xx"></div>
JS
$("#button").click(function() {
$.getJSON('json.php', function(data) {
$.each(data, function(index, value) {
$("#xx").append("<p>" + value + "</p>")
});
});
});
Response from json.php should be in below format
["AGGERI","ALCHEMICA 1961"]
The reason your code isn't working is that it's producing output like this:
"foo"<br />
"bar"<br />
That's not valid JSON. To be valid, you have to not have the HTML <br /> in there (this is JSON, not HTML), and you have to have commas between the elements you want to return.
json_encode will handle formatting the array correctly for you.
jsFiddle Demo with post request to send and get json output
'print' works differently then 'echo'. At least i am sending JSON packages with echo from php.
Can you replace it ?
// in php
echo json_encode($row['denominazione']);
// in jquery script, best to place "<br />" tag here
$("#xx").append("<p>"+value+"</p><br />")
Hi so I need to populate an array in flash with information from php. My php code is :
<?php
$db = mysql_connect("localhost","root","");
if (!$db) {
die("Database connection failed miserably: " . mysql_error());
}
$db_select = mysql_select_db("profileofperson",$db);
if (!$db_select) {
die("Database selection also failed miserably: " . mysql_error());
}
?>
<html>
<head>
<title>mySQLtestfile</title>
</head>
<body>
<?php
//Step4
$result = mysql_query("SELECT * FROM catalogue", $db);
if (!$result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo $row[" Name"]." ".$row["age"]." ".$row["Allergies"]." ".$row["height"]." ".$row["weight"]."<br />";
}
?>
</body>
</html>
which at present is displaying information from a database. How do i get flash to populate into an array?
Make your document xml, not html, start the document like this:
<?php
header("Content-type: text/xml");
echo chr(60).chr(63).'xml version="1.0" encoding="utf-8" '.chr(63).chr(62);
This just adds a header tag so the browser/flash recognises the document as XML (similar to !DOCTYPE with HTML) : <?xml version="1.0" encoding="UTF-8"?>
Then, query as you are doing, but echo the results in a valid XML format:
echo "<people>";//Create the parent node
while ($row = mysql_fetch_array($result)) {
echo "<person>";//Open child node, add values:
echo "<name>".$row[" Name"]."</name>";
echo "<age>".$row["age"]."</age>";
echo "<allergies>".$row["Allergies"]."</allergies>";
echo "<height>".$row["height"]."</height>";
echo "<weight>".$row["weight"]."</weight>";
echo "</person>";//Close child node
};
echo "</people>";//Close the parent node
?>
I've just written this out off the top of my head so may not be perfect, but it should be easy enough for you to check that it's generating a valid XML document (just load the page in a browser, get an XML viewer plugin to find out more if it's going wrong) and adjust if not, there are millions of tutorials on generating XML pages from PHP.
Then, use the URLLoader class in your flash application to access it:
var loader:URLLoader = new URLLoader();
//The loader class
var urlRQ:URLRequest = new URLRequest('yoursite/yourpage');
//The URL request
loader.dataFormat = URLLoaderDataFormat.TEXT;
//Use this for xml
urlRQ.method = URLRequestMethod.POST;
//Set method type (normally post)
loader.load(urlRQ);
loader.addEventListener(Event.COMPLETE,loadedData);
Then, have loadedData parse the XML:
function loadedData(e:Event):void {
var people:XML = XML(e.target.data);//Cast this var as XML to access
//people should represent top-level ie <people>;
for each(var person:XML in people.person){//Iterate over member nodes called 'person';
trace(person.age);//XML object node names can be referenced
//directly with dot notation!
trace(person.name);//etc...
}
}
One last thing, the mysql_ functions are deprecated in PHP, I found this out recently, use SQLi or PDO instead in future!
Hope this helps, as I say I've written it off the top of my head and it's better that you experiment with it, but if you do get stuck leave a comment and I'll have a look!
I have a mysql database with a table containing PATH's to images.
I want to load al the images to a TileList. Now i have this in PHP:
<?PHP
mysql_connect("localhost", "root", "root");
mysql_select_db("prototipo");
$result = mysql_query("select entretenimiento_id, e_nombre, e_imagen from entretenimiento");
echo "<?xml version=\"1.0\" ?><entretenimiento>";
while($row = mysql_fetch_assoc($result))
{
echo "<e_nombre>" . $row["e_nombre"] . "</e_nombre>";
echo "<e_imagen>" . $row["e_imagen"] . "</e_imagen>";
}
echo "</entretenimiento>";
?>
This is supposed to fetch me the PATH of the image, the name so it goes on the label of the tile that displays the image, and brings me also the id so i can launch another query when that image is clicked on.
All this is set into a dynamically created XML.
Now my question.... How do i load this??? What to do o AS3?? I already have the AS3 for the tilelist, i only need to load this dynamically created XML from PHP to it.
Thanks in advance. And sorry if i messed up on english, its not my main language. Im South American.
I have a partial answer:
var path:String = "http://localhost/entretenimiento.php";
xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, onLoadComplete);
xmlLoader.load(new URLRequest(path));
function onLoadComplete(e:Event):void {
var xmlData:XML = new XML(e.target.data);
//trace(xmlData);
for (var i:int=0; i<xmlData.*.length(); i++)
{
myTileList.addItem({label:xmlData.e_nombre[i], source:xmlData.e_imagen[i]});
//trace(xmlData.e_nombre[i]);
}
}
Althought this shows me the images and the titles on the tiles, i also get two more tiles that are empty, and in the trace they are shown as "undefined". Any thoughts to why is this?
Here is a sample code that should works :
var xmlLoader:URLLoader = new URLLoader();
xmlLoader.addEventListener(Event.COMPLETE, showXML);
// change the path of your php file
xmlLoader.load(new URLRequest("your-file.php"));
function showXML(e:Event):void
{
var entretenimiento:XML = new XML(e.target.data);
// for each row :
for (var x:XML in entretenimiento.loc)
{
// Change the name of your tilelist
myTileList.addItem({label:x.e_nombre, source:x.e_imagen});
}
}