I am trying to display my images in a for loop in the form tag using PHP but it does not seem to work. I have also tried doing a return statement but nothing still appears.
<?php
$data = array("images/architecture-57e8d34a48_640.jpg",
"images/gateway-arch-57e2d64548_640.jpg",
"images/horseshoe-bend-57e6d6434f_640.jpg",
"images/lake-irene-57e6d24a4d_640.jpg",
"images/silhouette-57e8d5444e_640.jpg");
function displayCheckboxes(){
for ($i=0; $i<count($data); $i++) {
echo "<img src='".$data[$i] . "<br>";
}
}
?>
<body>
<main id ="main">
<form id="pics" action="process.php" method="get">
<label>Name: </label>
<?php echo displayCheckboxes();?>
</form>
</main>
</body>
Maybe Like This:
<?php
$data = array("images/architecture-57e8d34a48_640.jpg",
"images/gateway-arch-57e2d64548_640.jpg",
"images/horseshoe-bend-57e6d6434f_640.jpg",
"images/lake-irene-57e6d24a4d_640.jpg",
"images/silhouette-57e8d5444e_640.jpg");
function displayCheckboxes(){
global $data;
for ($i=0; $i<count($data); $i++) {
echo "<img src='".$data[$i]."'>" . "<br>";
}
}
displayCheckboxes();
?>
function displayCheckboxes($img_array){
foreach($img_array as $img) {
echo "<img src='".$img."'>'" . "<br>";
}
}
and
echo displayCheckboxes($data);
There is several errors with your function :
- $data is not inside the function
- .jpg is already in the image name.
this should work,call the function with $data
$data = array("images/architecture-57e8d34a48_640.jpg",
"images/gateway-arch-57e2d64548_640.jpg",
"images/horseshoe-bend-57e6d6434f_640.jpg",
"images/lake-irene-57e6d24a4d_640.jpg",
"images/silhouette-57e8d5444e_640.jpg");
/* Write your displayCheckboxes() function here */
displayCheckboxes($data);
function displayCheckboxes($data){
for ($i=0; $i<count($data); $i++) {
echo "<img src='".$data[$i]."'.jpg>'" . "<br>";
}
}
?>
<?php
$data = array(
"images/architecture-57e8d34a48_640.jpg",
"images/gateway-arch-57e2d64548_640.jpg",
"images/horseshoe-bend-57e6d6434f_640.jpg",
"images/lake-irene-57e6d24a4d_640.jpg",
"images/silhouette-57e8d5444e_640.jpg"
);
?>
<body>
<main id ="main">
<form id="pics" action="process.php" method="get">
<label>Name: </label>
<?php foreach($data as $image): ?>
<img src="<?= $image; ?>"></br>
<?php endforeach; ?>
</form>
</main>
</body>
This is an alternative way. Looks much cleaner and readable. And I actually don't think we need a function for printing HTML.
I would say NEVER put HTML inside PHP echo unless it is compulsory. The reason I am stating this is if you put HTML inside PHP, the code becomes easily messy. It becomes hard to understand the logic unless you are the one who coded. Particularly, if you are working with some designers or in future, they will have a hard time making even little changes.
Even I think using <?= than <?php echo is better.
You are trying to give an extension ".jpg" of the images that you previously gave to it in the path of images in the array "$data".
For exemple:We will take the first element in the array $data with index = 0 "$data[0]" (images/architecture-57e8d34a48_640.jpg):
In PHP looks like -> echo "<img src='".$data[0]."jpg'>" . "<br>";
,but in HTML looks like -> <img src='images/architecture-57e8d34a48_640.jpg.jpg'>
You shold have to delete the extension ".jpg" from your echo to seem like:
echo "<img src='".$data[$i]."'>" . "<br>";
Related
I have a problem. I checked tons of good answers and tried them. Some helped me a lot but I still can't solve my problem completely. Can someone please help me?
I have one text file with following lines:
123456789, c
123456790, c
123456791, c
123456792, d
I read and parse this text file using a PHP script:
$myusers = array();
$my_txt = file_get_contents('C:\xampp\htdocs\net\net1\conStats.txt');
$rows = explode("\n",$my_txt);
foreach($rows as $row => $data){
$row_data = explode(',',$data);
array_push($myusers,$row_data);
}
I can reach to the result of this php script with JS code below:
var userConStats = <?php echo json_encode( $myusers ) ?>;
for ( i = 0; i < userConStats.length-1; i++){
document.getElementById(userConStats[i][0]).innerHTML = userConStats[i][1];
}
with this; I filled the necessary html table for the first time. Everything is perfect.
The problem starts when I want this PHP to read text file every second and refresh the table elements according to the changes in the text file. PHP parse the text file only once and the changes in the text file won't change anything on the browser.
Maybe my approach to the problem was wrong I am not sure.
Any help will be appreciated. Thank you!
Complete code can be found below:
<?php
require 'connectionNetIndex2.php';
include 'txtPHP.php';
include 'userConStatUpdater.php';
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>2-NetIndex</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.js"></script>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
<body>
<h1>MY_TEST</h1>
<select name="OperationalMode">
<option value="">Normal</option>
<?php while($opMode = mysqli_fetch_assoc($opModes)) { ?>
<option value="<?php echo $opMode["operational_mode"]; ?>"><?php echo $opMode["operational_mode"]; ?></option>
<?php } ?>
</select>
<?php if(isset($Users)): ?>
<table>
<tr>
<td>IMSI</td>
<td>Connection Status</td>
<td>Profile</td>
</tr>
<?php foreach($Users as $user): ?>
<tr>
<td value="<?php echo $user["u_id"]; ?>"><?php echo $user["imsi"]; ?></td>
<td id="<?php echo $user['imsi'];?>" class="conStats"></td>
<td><form action="" method="POST">
<select id="profiles" name="Profiles" onchange="valueChanged()">
<option value="<?php echo $user["p_id"]; ?>"><?php echo $user["profile_name"]; ?></option>
<?php foreach($profiles as $PR): ?>
<option name="" value="<?php echo $PR["p_id"]; ?>"><?php echo $PR["profile_name"]; ?></option>
<?php endforeach; ?>
</select>
<input name="uid" type="hidden" value="<?php echo $user["u_id"]; ?>">
<!--<input type="submit" value="save">-->
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<script type="text/javascript">
function conStatUpdater(){
<?php
$myusers = array();
$my_txt = file_get_contents('C:\xampp\htdocs\net\net1\conStats.txt');
$rows = explode("\n",$my_txt);
foreach($rows as $row => $data){
$row_data = explode(',',$data);
array_push($myusers,$row_data);
json_encode( $myusers ) ;
}
?>
// pass PHP array to JavaScript array
//Dont refresh the elements.
var userConStats = <?php echo json_encode( $myusers ) ?>;
//test is function working every second?
//test result : YES
console.log(userConStats[0][1]);
for ( i = 0; i < userConStats.length-1; i++){
document.getElementById(userConStats[i][0]).innerHTML = userConStats[i][1];
}
}
setInterval(conStatUpdater, 1000);
</script>
</body>
</html>
Like you've realized, PHP can't update an HTML page after it's been generated (unless you reload the page). You can only do that with JavaScript. In order to get the data every second, you'd need to use ajax (https://www.w3schools.com/xml/ajax_intro.asp) to make asynchronous calls every second to your PHP page to get the data. So you'd need something like this:
PHP:
$myusers = array();
$my_txt = file_get_contents('C:\xampp\htdocs\net\net1\conStats.txt');
$rows = explode("\n",$my_txt);
foreach($rows as $row => $data){
$row_data = explode(',',$data);
array_push($myusers,$row_data);
}
print json_encode($myusers);
Your JavaScript code:
function updatePage(userConStats) {
for ( i = 0; i < userConStats.length-1; i++){
document.getElementById(userConStats[i][0]).innerHTML = userConStats[i][1];
}
}
var secondPerRequest = 1;
setInterval(function() {
$.ajax({
url: "<your php page>",
success: function(result) {
var resultAsObject = JSON.parse(result);
updatePage(resultAsObject);
}
});
}, secondsPerRequest * 1000);
Note that I used jQuery to do the ajax call because it's simpler that way. If you don't want to use jQuery, you can find info on how to do ajax in vanilla JS here: How to make an AJAX call without jQuery?
the <?php ... ?> block script inside your conStatUpdater() javascript function will not re-executed on the server-side because it is already parsed and will only yield the same result.
what you need is an AJAX function that will call your php script, in which that php script will re-executed on server-side and respond you with an updated values on your text files.
I want to make the delete option appear when the image is hover.i dont know how to do it.so guys please help me?my view is like this:
<?php include('inc/header.php');?>
<div class="main">
<?php
foreach ($view as $row) {
echo "<div class='grow'>";
echo "<img src='".base_url()."images/".$row->image."' >";
echo "</div>";
}//end for each
?>
</div>
<?php include('inc/footer.php');?>
My image already hovers but dont know how to embed the delete option within the image.
Add a delete div -
<?php include('inc/header.php');?>
<div class="main">
<?php
foreach ($view as $row) {
echo "<div class='grow'>";
echo "<div class='delete'><a href='#'>delete</a></div>";
echo "<img src='".base_url()."images/".$row->image."' >";
echo "</div>";
}//end for each
?>
</div>
<?php include('inc/footer.php');?>
Then in script write a code to show/hide delete div -
$('.grow').hover(function () {
$(this).find('.delete').show();
},
function () {
$(this).find('.delete').hide();
})
I've been able to get my arrays working to echo text from a database in HTML. Fine. However, I now want to send this text to another page onClick (JQuery or JavaScript). So here is what I already have (I know it's not sending anything, but this is not the problem right now) :
PHP
$h = "SELECT * FROM table";
$h=$pdo->prepare($h);
$h->execute();
$i=1;
while ($row = $h->fetch()) {
$text[$i] = $row['content'];
$id[$i] = $row['id'];
$i++;
}
HTML
<h1 id="<?php echo $id[0]; ?>" onClick="edit(this)"><?php echo $text[0]; ?>
</h1>
<h2 id="<?php echo $id[1]; ?>" onClick="edit(this)"><?php echo $text[1]; ?></h2>
<p id="<?php echo $id[2]; ?>" onClick="edit(this)"><?php echo $text[2]; ?></p>
JavaScript
function edit(element) {
alert(element.id);
}
So, this gives me the "id" of the content in the database. However, I'd like to know if there is a way to get this information without having the "id" in the HTML tags, a way to click on the text and have the number that is inside the square brackets.
Example : you click on the text inside the "h1" tag and a pop up tells you what is the number in <?php echo $text[2]; ?>. In this case, I would like the number 2 to show up in the alert box, without using id="<?php echo $id[2]; ?>".
I have a project in which I am displaying a button tag in a while loop. On every button click I want to display an alert box with the respective UserId. Here is my code:
<?php
$data = mysql_query("Select RegisterId,FName,Image1 from Information where RegisterID='$profileMonth1'") or die(mysql_error());
while ($dis1 = mysql_fetch_array($data)) {
?>
<div id="demo1" value="<?php echo "$RegisterId" ?>">
<button onClick="validate()">Show Interest</button>
</div>
<?php } ?>
Here is my validate function:
function validate1(id2)
{
// var id2;
id2 = document.getElementById('demo2').getAttribute('value');
alert(id2);
}
But it is always showing me last user id .. whereas i want to display userid for every user on everyclick.
Can someone help?
Here man, the function you were calling was undefined validate1, also you don't need to get any arguments on your function declaration, since you are not passing any arguments when you invoke it.
<?php
$data = mysql_query("Select RegisterId,FName,Image1 from Information where RegisterID='$profileMonth1'") or die(mysql_error());
while ($dis1 = mysql_fetch_array($data)) {
?>
<div id="demo" value="<?php echo "$RegisterId" ?>">
<button onClick="validate()">Show Interest</button>
</div>
JS
function validate(){
var id2 = document.getElementById('demo').getAttribute('value');
alert(id2);
}
try this in your code
HTML:
<button onClick="validate('<?php echo $RegisterId; ?>')">Show Interest</button>
Javascript:
function validate(id2)
{
alert(id2);
}
Your code needs some modifications.
Firstly, you have made a provision to send id to javascript function, but, you are not passing id to it.
PHP
<?php
$data = mysql_query("Select RegisterId,FName,Image1 from Information where RegisterID='$profileMonth1'") or die(mysql_error());
while ($dis1 = mysql_fetch_array($data)) {
?>
<div id="demo1" value="<?php echo $dis1['RegisterId'];?>">
<button onClick="validate('<?php echo $dis1['RegisterId'];?>')">Show Interest</button>
</div>
<?php } ?>
Javascript:
function validate1(id2) {
// var id2;
//id2 = document.getElementById('demo2').getAttribute('value');
alert(id2);
}
With this code, your clicks shouldn't even return the last id. Your javascript function is not looking good.
This should work;
<?php
$data = mysql_query("Select RegisterId,FName,Image1 from Information where RegisterID='$profileMonth1'") or die(mysql_error());
while ($dis1 = mysql_fetch_array($data)) {
?>
<!-- removed id attribute, as they're unique, you can't set it to every div.
If you really need id attribute, you can set one by using your RegisterId (e.g. id="demo-<?php echo $RegisterId; ?>)
And moved value attribute to button tag, it's much more useful in it. -->
<div>
<button onClick="validate(this)" value="<?php echo "$RegisterId" ?>">Show Interest</button>
</div>
<?php } ?>
Javascript
function validate(element){
alert(element.value)
}
This way, you can use it in other stuff much easier.
Other users have had similar problems about when they're looping rows of buttons but it's always because they accidentally reused the same Id or value. I'm experiencing the same problem, but all of my buttons are unique.
AJAX request
<script>
$(document).ready(function(){
$("#friendadd").submit(function(){
alert("checkpoint");
$.ajax({
type:"POST",
url:"getuser.php"
});
})
});
</script>
PHP and form
<form id="friendadd">
<?php
for($i=0; $i<$ctk->rowCount(); $i++){
echo "<img src='".$ctk_values[$i][6]."' alt='Blank' style='width:64px;height:64px'>";//PP, Later add clickable profile
echo "<th rowspan='3'>Attributes</th>";
echo "<tr> ".$ctk_values[$i][0]."</tr>";//UN
echo "<tr> ".$ctk_values[$i][1]."</tr>";//UL
echo "<tr> ".$ctk_values[$i][5]."</tr>";//UA
?>
<input type="submit" id="friend<?php echo $i;?>"><!--pass in this.value-->
</form>
<?php
}//Ends for loop
}
}
?>
Explanation: When I type in a username into the search box, it returns me three different users named rikesh1, rikesh2, and rikesh3. Each of them have a button next to them, with values friend0, friend1, friend2, respectively. When I click on the friend0 button, it successfully calls and updates the database. When I click the friend1 button, nothing happens. This is different from other users in that my buttons have unique Ids. Thanks for any and all help, I think this is a very fixable problem but after searching Stack, I'm still not sure what's happening.
<form id="friendadd">
<?php
for($i=0; $i<$ctk->rowCount(); $i++){
echo "<img src='".$ctk_values[$i][6]."' alt='Blank' style='width:64px;height:64px'>";//PP, Later add clickable profile
echo "<th rowspan='3'>Attributes</th>";
echo "<tr> ".$ctk_values[$i][0]."</tr>";//UN
echo "<tr> ".$ctk_values[$i][1]."</tr>";//UL
echo "<tr> ".$ctk_values[$i][5]."</tr>";//UA
?>
<input type="submit" id="friend<?php echo $i;?>"><!--pass in this.value-->
<?php
}//Ends for loop
?>
</form>
<?php
}
}
?>
Use this code instead.
The other one ends the form tag at the first loop.