This is my form where I send rating information to my textfile.txt.
<form name="Star" id="Star">
<div id="rating-area" class="shadow">
<img src="star-icon.png" id="thumb1" data-value="1" />
<img src="star-icon.png" id="thumb2" data-value="2" />
<img src="star-icon.png" id="thumb3" data-value="3" />
<img src="star-icon.png" id="thumb4" data-value="4" />
<img src="star-icon.png" id="thumb5" data-value="5" />
</div>
</form>
<script>
jQuery('div#rating-area img').click(function(e){
var val = jQuery(this).data('value') ;
console.log(val) ;
jQuery.post('post.php',{ Star : val },function(data,status){
console.log('data:'+data+'/status'+status) ;
}) ;
}) ;
</script>
And this is my php call:
<?php
$file = file("textfile.txt");
$file_content = file_get_contents("textfile.txt");
$file_content_separated_by_dash = explode("-", $file_content);
echo "Number of votes in file: " . count($file_content_separated_by_dash) . "<br>";
$sum = 0;
foreach ($file_content_separated_by_dash as $vote) {
$sum = $sum + $vote;
}
echo "Total: " . $sum;
?>
I don't seems to get the hang of this. When I run the progress to count number of votes in the textfile.txt I do only get the first vote as the total sum. No matter if I reload the page or not. It's still that very first vote that shows up. I've checked the textfile.txt. It updates itself whenever the "star-rating" is "onclick".
As well the "number of votes". To see how many times someone has clicked on it. It stays on 1 through the whole time.
What have I missed?
Im still quite a newbie with php. So if I forget any necassary information please tell me and I will try to update the post with that info.
Your textfile content doesn't match with code.
Numbers in textfile must be separated with - to work the current code..
If you cant modify your Textfile insertion then change the reading code like this
<?php
$file = file("textfile.txt");
$file_content = file_get_contents("textfile.txt");
$file_content_separated_by_dash = str_split($file_content);
echo "Number of votes in file: " . count($file_content_separated_by_dash) . "<br>";
$sum = 0;
foreach ($file_content_separated_by_dash as $vote) {
$sum = $sum + intval($vote);
}
echo "Total: " . $sum;
?>
Can you post your textfile.txt file? Code seems okay, need to check how data is being saved in text file.
Your file doesn't have -, it has only numbers.
so you can Use this code
$numbers = file_get_contents("textfile.txt");
$count = strlen($numbers);
echo 'Total votes'.$count;
for($i = 0; $i < count; $i++) {
echo $numbers[$i] . '<br />';
}
Related
This div act as a button. Whenever I click one, the page goes to the page name "teacherinfo.php". The "Sample" text is used as the name of the teacher. The problem is when I click the "Sample2" the Sample text appear on the "teacherinfo.php" page.
Here is the script for going to "teacherinfo.php":
<?php
while ($row = mysqli_fetch_array($query)) {
echo '<div class="announcementSlider" id="click">
<img src="pictures/blank photo.png" class="teacherpic"><br>
<span name="LastName">'.$row['LastName'].'</span><br>
<span>'.$row['Grade'].' - </span>
<span>'.$row['Section'].'</span>
</div>';
}
?>
<script type="text/javascript">
var a = document.getElementsByClassName("announcementSlider");
for (i=0; i<a.length; i++) {
a[i].onclick = function () {
location.href = "teacherinfo.php";
};
}
</script>
Code for displaying the text in "teacherinfo.php":
<div class="leftForm hide-on-med-and-down">
<img src="pictures/default-avatar-250x250.png">
<p class="name"><?php echo $name3; ?></p>
<p class="section"><?php echo $grade3; ?>-<?php echo $section; ?></p>
</div>
Code for retrieving data in database:
$sql3 = mysqli_query($db,"select * from teacherinfo");
$row3 = mysqli_fetch_array($sql3,MYSQLI_ASSOC);
$name3 = $row3['LastName'];
$grade3 = $row3['Grade'];
$section3 = $row3['Section'];
I want to use the "'.$row['LastName'].'" as a where clause in mysqli_query($db,"select * from teacherinfo"). How can I do that? or is there another solution to this issue?
First of all, I don't understand why you use javascript when you can use simple a tag with correct href:
<?php
while ($row = mysqli_fetch_array($query)) {
echo '<a class="announcementSlider" href="teacherinfo.php?id=' . $row['id'] . '">
<img src="pictures/blank photo.png" class="teacherpic"><br>
<span name="LastName">'.$row['LastName'].'</span><br>
<span>'.$row['Grade'].' - </span>
<span>'.$row['Section'].'</span>
</a>';
}
?>
Here, I suppose that every teacher in your mysql-table has some unique id field.
On teacherinfo.php you access id as $_GET['id'] and create a query like (here I skip security part, but $_GET['id'] can be forged and therefore contain some insecure data, you have to check it):
sql3 = mysqli_query($db,"select * from teacherinfo where id = " . $_GET['id']);
$row3 = mysqli_fetch_array($sql3,MYSQLI_ASSOC);
$name3 = $row3['LastName'];
$grade3 = $row3['Grade'];
$section3 = $row3['Section'];
I'm making a quiz website, for that questions and answers will be fetched from database and using PHP and MySQL.
I've stored the options in one single column using JSON.(Stored as string array) Question is displaying correctly but options couldn't; I've written them in similar manner.
quiz.php
echo '
<div id="ques_block">
<br>
<p id="ques"></p>
';
for($i=0; $i<$_SESSION["opt_size"]; $i++)
echo '<p class="opt" id="opt'.$i.'"></p>';
echo '
<div id="nav-for"><img src="next.png" alt="Next =>"></div>
</div>
';
next.php will be called using AJAX when NEXT is clicked.
next.php
$sql = "SELECT QUESTION, ANSWER, OPTIONS FROM user_quiz WHERE CUST_NO=$cust_no AND QUES_NO=$new_ques_no;";
$res = mysqli_query($conn, $sql) or die("bad Query: $sql");
if(mysqli_num_rows($res)==0)
echo "END";
else
{
$row = mysqli_fetch_assoc($res);
$ques = $row["QUESTION"];
$opts = $row["OPTIONS"];
$opt = json_decode($opts);
$resRows = sizeof($opt);
echo '
<script type="text/javascript">
document.getElementById("ques").innerHTML="'.$ques.'";
</script>
';
for($i=0; $i<$resRows; $i++)
echo '<script type="text/javascript">
document.getElementById("opt'.$i.'").innerHTML = "'.$opt[$i].'";
</script>
';
}
Edited:
#ADyson I'll try your method, Thanks,
BTW This is AJAX code as requested:
$(document).ready(function(){
$("#nav-for").click(function(){
$.post("nextQues.php",
{custNo: $("#custNo").val(), quesNo: $("#quesNo").val()},
function(data){
$("#ques").html(data);
}
);
});
});
I want to tranform a php array of string into html. My php and html code are in the same page.
I have $myvar that hold my array of string. I pass $myvar with POST and insert it to $ba.
My code needs to print on html page 3 line (in while loop).
But when I pass the $be, it writes me error message: "Notice: Undefined index: myvar" (in php code)
What do I need to repair so that my code prints to my screen all the 3 lines that I get from php?
my code:(php)
foreach ($docres as $key=>$filename) {
$counter = 0;
$file = $filename +1;
$handle = fopen($dir."/".$file.'.txt',"r");
if($handle)
{
while($counter < 3)
{
$myvar[]=fgets($handle);
$counter++;
}
}
}
$ba = implode("", $myvar);
my html code:
<form action="" method="POST">
<center>
<h1> My Search Engine </h1>
<input type = 'text' size='90' value='' name = 'search' > <br>
<input type = 'submit' name = 'submit' value = 'Search source code'>
</center>
</form >
<p> <?php echo $ba ?> </p>
Simply echo the mysql query on a function and call it on HTML as follows:
UPDATE: 3rd column will be an image wich route are stored on database, and 4th col will be an image eich only the name was stored on database (because we know the full route) as example:
<?php
function printOnHtml(){
include ("connection.php");
$sql = "SELECT * FROM foo;"
if ($result = connection()->query($sql)){
$rs = $result->fetch_array(MYSQLI_NUM);
while ($rs[0] != ''){
echo "first column: ".$rs[0]." second column: ".$rs[1]." image with full route on database: <img src='".$rs[2]."' alt=''> <br> if only the img name is stored cuz we know the route: <img src='img_route/".$rs[3]."' alt=''>";
$rs = $result->fetch_array(MYSQLI_NUM);
}
}
}
Then on HTML
<html>
blablabla
<body>
blablabla
<?php
printOnHtml();
?>
blablabla
</body>
</html>
Note that it have to be a .php file to call the php function (for example index.php)
I paste the connection php script i use in order if you need it:
<?php
function connection(){
if($mysqli = new MySQLi("localhost","user","password","database_name")) echo "OK"; else echo "KO";
mysqli_set_charset($mysqli, "utf8");
return $mysqli;
}
?>
i did it with mysqli fetch array, but you can do the same using fetch assoc if you want.
UPDATE2: If you stubborness makes you follow using a txt to store data (wich, if increase will fail when you get a some thousands line txt), modify this on your code:
$myvar='';
foreach ($docres as $key=>$filename) {
$counter = 0;
$file = $filename +1;
$handle = fopen($dir."/".$file.'.txt',"r");
if($handle)
{
while($counter < 3)
{
if(isset($myvar)){
$myvar=fgets($handle);
}
$counter++;
}
}
}
and i'm supposing that you declared $dir, $file and other vars properly.
You NEVER have to use vars without declaring it (as NULL at least). You only can do this if you ensured 100% that this var will get a value at this point.
You have to convert the array to string in a correct way using implode and <br> as a separator
Then just print it using php tags (as you are using both at the same page ) you can access the variable direct and print it using <?= $ba ?> or <?php echo $ba ; ?>
Code will be :
<?php
foreach ($docres as $key=>$filename) {
$counter = 0;
$file = $filename +1;
$handle = fopen($dir."/".$file.'.txt',"r");
if($handle)
{
while($counter < 3)
{
$myvar[]=fgets($handle);
$counter++;
}
}
}
$ba = implode("<br>", $myvar);
?>
<form action="" method="POST">
<center>
<h1> My Search Engine </h1>
<input type = 'text' size='90' value='' name = 'search' > <br>
<input type = 'submit' name = 'submit' value = 'Search source code'>
</center>
</form >
<p id="deatiles"> <?= $ba ?> </p>
I have a 'display all' functionality on my site. Currently there are 7 sub-folders that are iterated through to display categories. (Empty folders are not shown, and more sub-folders may be added).
I don't want to set a limit [of images] per page, i just want to show all of the images for each folder on a different page.
Despite extensive googling and experimenting, the best i could come up with was a number of html pages being displayed, all appended one to the other, on one long page. (ugh!) I've been at it now since last night so i'm a bit fed up.
I have stripped back my displayall.php to it's basic functionality. Here's what it looks like at the moment (with no pagination):
<!doctype html>
<html>
<head>
<meta charset='utf-8'>
<link rel='stylesheet' type='text/css' href='css/bootstrap_combined.css'>
<link rel='stylesheet' type='text/css' href='css/style.css'>";
<title>Gallery Display</title>
</head>
<body>
<div id="wrapper">
<header>
<h1>The Ultimate Gallery Compiler</h1>
<div id='menu'><a class='head' href='index.html'>Upload Photo</a> <a class='head' href='gallery.html'>Browse Gallery</a></div>
</header>
<!---end header-->
<div id='content'>
<h2>Gallery: All Images</h2>
<?php
//$pages = isset($_GET['page'])?intval($_GET['page']-1):0; //get page
//$pageno = $_REQUEST['page'];
//compile an associative array
$subfolder= array('Fashion/LifeStyle'=>'1', 'Music/Video'=>'2','Sport/Leisure'=>'3','Electronics/Technology'=>'4','Pets/Animals'=>'5','Health/Beauty'=>'6','Other'=>'7' );
$carray=count($subfolder);
// iterate through the sub directories, and count them
$files = "images/*/*";
$sub=0;
foreach(glob($files) as $file)
{
$sub++; //total number of images
}
foreach ($subfolder as $subf=>$value)
{
$folder = "images/".$value."/";
$link = 'displayall.php?'.$value;
$mykey= $subf;
$counter = 0;
// Open the appropriate subfolder, and display its contents.
if ($dir = opendir($folder)) {
$images = array();
while (false !== ($file = readdir($dir))) {
if ($file != "." && $file != "..") {
$counter++;
$images[] = $file;
}
}
closedir($dir);
}
//don't show empty categories
if ($counter!== 0){
echo "<input type='hidden' id='current_page'/>";
echo "<input type='hidden' id='show_per_page' />";
echo "<h3>Category: ".$mykey."</h3><br>"; //display heading
echo "<h4>There are " .$sub. " photos in the <a href='gallery.html'>Gallery</a> to date</h4>"; //display total overall
echo '<div id="multi">';
foreach($images as $image) {
echo '<span class="gallery"><img src="';
echo $folder.$image;
echo '" alt="" width="200" height="auto" /></span>'; //show images
}
echo '</div>';
//$num= $pages +1;
echo "<br><strong>".$counter. " photos</strong><br>"; //display total per category
echo "<span id='pageNo'>Page Number: ".$value."</span><br>";
echo "Next";
echo "<br><br><hr><br>"; //put space and a line between the categories
};
//$pageno++;
}
?>
<footer>
<p class='foot'>© Copyright 2015-2016 MMA2 Rachel Gallen, Ysabel Pheifer and Rebecca Merrigan.</p>
</footer>
</div>
</body>
</html>
(It can be viewed here)
Any help on the pagination would be appreciated. All the tutorials seem to be either mysql related or dealing with a single array. V frustrating!
(open to php, jquery, javascript or bootstrap solutions!)
Thanks and happy chrimbo
Rachel
edit: former edit removed
Your page is looping through all the subfolders, it looks like an attempt was made to only display subfolder being specified by the querystring parameter page. This can be accomplished with a minor edit to your PHP:
<?php
$pages = isset($_GET['page'])?intval($_GET['page']):1; //get page
//$pageno = $_REQUEST['page'];
//compile an associative array
$subfolder= array('Fashion/LifeStyle'=>'1', 'Music/Video'=>'2','Sport/Leisure'=>'3','Electronics/Technology'=>'4','Pets/Animals'=>'5','Health/Beauty'=>'6','Other'=>'7' );
$carray=count($subfolder);
// iterate through the sub directories, and count them
$files = "images/*/*";
$sub=0;
foreach(glob($files) as $file)
{
$sub++; //total number of images
}
$value = $pages;
$folder = "images/".$value."/";
$link = 'displayall.php?page='.$value + 1;
//$mykey= $subf;
$arrayKeys = array_keys($subfolder);
$mykey = $arrayKeys[$value];
$counter = 0;
// Open the appropriate subfolder, and display its contents.
if ($dir = opendir($folder)) {
$images = array();
while (false !== ($file = readdir($dir))) {
if ($file != "." && $file != "..") {
$counter++;
$images[] = $file;
}
}
closedir($dir);
}
//don't show empty categories
if ($counter!== 0){
echo "<input type='hidden' id='current_page'/>";
echo "<input type='hidden' id='show_per_page' />";
echo "<h3>Category: ".$mykey."</h3><br>"; //display heading
echo "<h4>There are " .$sub. " photos in the <a href='gallery.html'>Gallery</a> to date</h4>"; //display total overall
echo '<div id="multi">';
foreach($images as $image) {
echo '<span class="gallery"><img src="';
echo $folder.$image;
echo '" alt="" width="200" height="auto" /></span>'; //show images
}
echo '</div>';
//$num= $pages +1;
echo "<br><strong>".$counter. " photos</strong><br>"; //display total per category
echo "<span id='pageNo'>Page Number: ".$value."</span><br>";
echo "Next";
echo "<br><br><hr><br>"; //put space and a line between the categories
};
//$pageno++;
?>
Summary of Changes:
I un-commented the $pages variable so it pulls from the query string parameter.
It also looks like you tried to send that query string via the $link variable, but the format was not correct. I updated that to $link = 'displayall.php?page='.$value + 1;
Finally, I removed the for loop and set $value to the current $page parameter so only one subfolder would be shown on a page.
Changes Made After Edit #1
The ternary operation on $pages was setting the value to 0, resulting in the error when looking for /images/0/. Changed to $pages = isset($_GET['page'])?intval($_GET['page']):1;
Added an array to handle the keys from the associative array, since the querystring is using integer values instead of category names.
$arrayKeys = array_keys($subfolder);
$mykey = $arrayKeys[$value];
You might want take a long hard look at passing string values instead of integer values to $page. It'll make for better SEO, better folder names, and removes the need to have an associative array to map the integers to a category name and back again.
Final Notes:
This certainly has room for expansion, you might consider error checking to make sure the value is inbounds and the folder is valid. Previous and next links, and quick navigation to a specific page number might also be useful.
Hope that helps!
I'm currently busy with a ticketsystem. A headline will be displayed. When the headline has over 40 characters, the headline will be cut and the '...' will be added. Now, when I try to link the headlines to its messages, it won't create a link. I'm using Ajax to do this without a page refresh, but no links are being created, which means that the full ticket wont be openend. I've tried several things but I cant get it to work. I'm also not that familiar with it :')
This is my piece of JS:
//Show ticket
function showTicket(id) {
$.ajax({url:"readTicket.php?ticket_id=" + id});
}
This is the piece of code supposed to link the headlines:
<?php echo '<a id="showTicketNow" onclick="showTicket('.$stt["ticket_id"].')">' ?>
<?php if(strlen($stt['subject']) > 40) $stt['subject'] = substr($stt['subject'], 0, 40).'...';
echo $stt['subject'] ?>
<?php echo '</a>' ?>
This is my readTicket.php
$user_id = $_SESSION['user_id'];
$ticket_id = mysqli_real_escape_string($mysqli, $_GET['ticket_id']);
$getTicketInfo = mysqli_query($mysqli,"SELECT * FROM tickets WHERE ticket_id = '$ticket_id' AND user_id = '$user_id'");
while ($row=mysqli_fetch_array($getTicketInfo)) {
$subject = $row['subject'];
$message = $row['message'];
}
echo '<div class="showTicket display subject">'.stripslashes($subject).'</div>
<div class="showTicket display message">'.stripslashes($message).'</div>';
Thanks in advance..
Try this, you were missing all of the syntax goodness.
echo'<a id="showTicketNow" onclick="showTicket('.$stt["ticket_id"].')">';
if(strlen($stt['subject']) > 40){
$stt['subject'] = substr($stt['subject'], 0, 40).'...';
}
echo $stt['subject'];
echo '</a>';
You need to specify href attribute of <a> tag, something like this:
<?php echo '<a href="javascript:void(0);" id="showTicketNow" onclick="showTicket('.$stt["ticket_id"].')">' ?>