Data from a list php - php

I would you to know how to get data from a list in php.
<h1>Liste livres</h1>
<ul>
<form method="post" action="">
<?php
$liste = $bdd->query("SELECT * FROM livres");
while($l = $liste->fetch()){
?>
<li><input type="hidden" name="isbn" value="<?php echo $l['livre_isbn']; ?>"/>\<?= $l['livre_titre'] ?>\<?= $l['livre_auteur'] ?>\<?= $l['livre_genre'] ?>\<?= $l['dispo'] ?></li>
<button name="empr" type="submit">Emprunter</button>
<?php } ?>
</form>
</ul>
Every time I click on "Emprunter" for any element displayed, he only take the last element of the list in the procedure. How can I make sure it takes the right element?
For information, the element in the list used is $['livre_isbn'].

Put the <form> tag in your while loop :-)

Related

How do I dynamically append something to a variable in PHP?

I have a form like so:
<?php if (isset($_POST['artist'])) {
// do something
} ?>
<form name="admin_on_artist_<?php echo $artist->ID; ?>" action="" method="POST">
<p class="artist-negative">
<label for="artist"><input type="checkbox" name="artist_<?php echo $artist->ID; ?>" id="artist_<?php echo $artist->ID; ?>"> Check this?</label>
</p>
<button type="submit">Update</button>
</form>
On the page in question, this form is shown many times in a foreach loop. However, when I submit any given form, it updates all of the forms, which is not what I want.
How can I append the $artist->ID to $_POST['artist'] so that I get something like:
$_POST['artist_1'] to match the checkbox attributes?
You could pair your foreach that generates the frontend form markup with a foreach that processes the form submission. Something like:
<?php
$regex = '/^artist_([0-9]+)$/'
foreach (array_keys($_POST) as $key) {
if (preg_match($regex,$key,$matches)) {
$artistId = (int)$matches[1];
// do something with $_POST[$key] according to $artistId
}
}
This works for a single field submission or a multiple field submission.
Alternatively, you could do something on the frontend in JS (as #smith suggests in the comments) to ensure the form submission always has the same, well-known keys, populating a hidden form with the current submission. With this approach you would have to add another field to the form that contains the ID.
The solution for this was much simpler than I was able to grasp at first, but basically I just had to do this, the key difference between this and my original question being the first two lines:
<?php $artist_form_id = 'artist_'.$artist->ID;
if (isset($_POST[$artist_form_id])) {
// do something
} ?>
<form name="admin_on_artist_<?php echo $artist->ID; ?>" action="" method="POST">
<p class="artist-negative">
<label for="artist"><input type="checkbox" name="artist_<?php echo $artist->ID; ?>" id="artist_<?php echo $artist->ID; ?>"> Check this?</label>
</p>
<button type="submit">Update</button>
</form>

How to set the number of items in an array based on html form input?

I am working on creating a PHP file and one thing that I'd like to do is have an array (Example 1). From what I understand, and Array is like a list, and I want to also input items on the list (Example 2). But the number of items in the array need to be determined by a number, inputted via a HTML form (Example 3).
Example 1:
<?php
$a=array("red","green");
array_push($a,"blue","yellow");
print_r($a);
?>
</body>
</html>
</code>
Example 2:
<!DOCTYPE html>
<html>
<body>
<?php
$a=array("red","green");
array_push($a,"$_POST["color3"]","$_POST["color4"]");
print_r($a);
?>
</body>
</html>
Example 3.
<ol>
<form action="finished.php" method="post">
<li><input type="text" name="color3"></li>
<li><input type="text" name="color4"></li>
</form>
</ol>
EDIT:
I hope this is all formatted correctly, and you understand the question.
To reiterate: The first page is blank with just a form; single input box, where you type in any number ( X ).
The Second page has the same line repeated over and over (depending on the number X from the previous page), it's line is:
<li><input type="text" name="color Y"></li>
Y should count from 1 up infinitely until X is reached.
The Last page prints it all in a list (array?).
For Example: On the first page we enter the number 3.
On the second page we have 3 boxes for inputting the names of our chosen colors: Red, Blue, Yellow.
On the last page we are shown a list of our three colors: Red, blue and yellow.
Hope this helps.
<ol>
<form action="finished.php" method="post">
<li><input type="text" name="data['color3']"></li>
<li><input type="text" name="data['color4']"></li>
</form>
</ol>
then in the finished.php
$_POST['data'];
print_r($_POST);//print out the whole post
print_r($_POST['data']); //print out only the data array
I think I got it what you want (after reading more than once). Let me know if I understood correctly. Let's assume you're using 3 different files (as you wrote in your question).
file1.php (a simple form with 1 input and 1 submit button):
<form action="file2.php" method="post">
<input type="text" name="amount" placeholder="The amount of elements">
<input type="submit" value="Enter">
</form>
file2.php (check if $_POST and the value is an integer):
if (!empty($_POST['amount'])) {
if (!is_int($_POST['amount'])) {
exit('Not an integer');
}
?>
<form action="file3.php" method="post">
<?php
for ($i = 0; $i < $_POST['amount']; $i++) {
echo '<input type="text" name="colors[]" placeholder="Enter color name"><br>';
}
?>
<input type="submit" value="Done">
</form>
<?php
} else {
exit('Only $_POST method is allowed.');
}
file3.php (get all results and store an array in variable):
if (!empty($_POST)) {
$colors = $_POST['colors'];
foreach ($colors as $color => $value) {
echo '<li>'.$value.'</li>';
}
exit;
} else {
exit('Only $_POST method is allowed.');
}
We can add some more security (like checking if it's not empty, etc.), but I'm adding just basic things.

While loops not printing out first form iteration but printing out other first contents?

Hi I'm echoing a bunch of forms within a while loop(reading out from a database).
But for some reason it doesn't print out the first form but it prints out the first contents and in the rest of the loop it prints the rest of the form and it contents
PHP code
$edit = db::run_query("
SELECT
feature_name, id
FROM
`sp_itemsa_features`
Where
`id` = '556'
",db::return_rows);
while ($row = mysql_fetch_assoc($edit)) {
echo'<form class="feature-box" >
<ul>
<li><span>Feature Name</span> "'.$row['feature_name'].'" </li>';
$query2 = "
SELECT product_id, id FROM sp_itemsa_features_items
WHERE feature_id = '".$row['id']."'
";
$pids = db::run_query($query2,db::return_rows);
while ($row2 = mysql_fetch_assoc($pids)){
echo '<form class = "test" method = "POST">
<li><span>Remote ID</span> <input type = "text" name = "pid" value = "'.$row2['product_id'].'"> </li>
<li><input type="hidden" name="editId" value="'.$row2['id'].'" /></li>
<li><input type="submit" class="submitbtn" name="editsubmit" value="submit edit" /></li></form>';
}
echo '</ul></form>';
}
note all the DB run_query stuff it part of a database class they just connect and query from the database
Your HTML is also invalid:
<ul>
<li>...</li>
<form ...> <--- not valid
a <ul> and <ol> can have have only other lists, <li> or <col> elements as descendants.
Plus, you're embedding forms-in-forms. That is not permitted:
<form><form>...</form></form> <-- illegal html
And largest of all, since you're getting PHP code as part of the output, you really should look at your browser's "view source". It's possible the ENTIRE script is not executing, and you're simply getting all of the PHP code. The <?php ... ?> blocks would be interpreted as illegal/unknown html tags and simply not rendered.

PHP foreach loop, need loop to get data from db, but it is also looping my forms

So I have a categories table in my database and each category has a certain amount of steps assigned to it. I want to have all of the categories displayed as tabs titled with the category name so I need this from the database. I then have a form inside the tabs to insert the amount of steps needed for that category, but this form is looping... I need it inside the foreach to get the category id but without the form looping... Hope that makes sense..
Here is my code:
<?php foreach($categories as $category){ ?>
<div id="<?php echo $category->category ?>" class="tab">
<form id="maxSteps" method="POST" name="maxSteps" action="<?php $PHP_SELF; ?>" enctype="multipart/form-data">
<label for="maxSteps">Amount of steps in form: </label><input style="width:50px;" id="maxSteps" type="text" name="maxSteps" />
<input type="hidden" name="catId" value="<?php echo $category->cat_id; ?>" />
<input type="Submit" value="Go" name="maxStepsSubmit" />
</form>
<table id="amountOfStepsForm">
<?php $maxStepsById = $wpdb->get_results( "SELECT * FROM metal_work_max_steps WHERE cat_id = '$category->cat_id'" ); ?>
<?php foreach($maxStepsById as $maxStep){ ?>
<tr><td id="maxStepsRow<?php echo $maxStep->id; ?>"><?php echo "<p>Amount of steps in form is: <b>".$maxStep->steps."</b>" ?></td><td id="editRow<?php echo $maxStep->id; ?>"><a id="<?php echo $maxStep->id; ?>" class='edit'>Edit</a></td></tr>
<input type="hidden" name="catId" value="<?php echo $category->cat_id; ?>" id="catId<?php echo $maxStep->id; ?>" />
<?php } ?>
</table>
</div>
<?php } ?>
Regards
The best thing you can do is to run only one query and retrieve all your data inside an associative array. Then just loop trough this data structure.
The query can be done using a JOIN statement, in order to retrieve the information regarding the max steps for each category.
1- put the Form tag above the for loop
2- <input type="hidden" name="catId" val... need to have dynamic name: name="catId_<?php echo $category->cat_id;?>"
3- the button Submit label GO, and the colse tag of Form need to be out of the for loop (below)
so all the fields will be in 1 form,
and you will have 1 submit button, if that what you need,
and the field names are not the same, so on submit you can read all of them
these are general comments, i think you need to pay attention to.

Only one value from an hidden input is being displayed

<?php
foreach($_color_swatch as $_inner_option_id){
preg_match_all('/((#?[A-Za-z0-9]+))/', $_option_vals[$_inner_option_id]['internal_label'], $matches);
if ( count($matches[0]) > 0 ) {
$color_value = $matches[1][count($matches[0])-1];
?>
<li>
<input type="hidden" id="fakecolor" value="<?php echo $color_value;?>"/>
<div onclick="alert(document.getElementById('fakecolor').value);">
<img src="<?php echo $color_value;?>.png" /></div>
</li>
<?php
}
}
?>
This works for displaying the images, using the $color_value but i need to pass the value from hidden input to another javascript function.
And when i click on div it displays only one value no matter how many are inside the foreach.
Can anyone give me a little help? Thanks.
This is the output:
<li>
<input type="hidden" id="fakecolor" value="red"/>
<div onclick="alert(document.getElementById('fakecolor').value);"><img src="red.png"/></div>
</li>
<li>
<input type="hidden" id="fakecolor" value="blue"/>
<div onclick="alert(document.getElementById('fakecolor').value);"><img src="blue.png"/></div>
</li>
<li>
<input type="hidden" id="fakecolor" value="white"/>
<div onclick="alert(document.getElementById('fakecolor').value);"><img src="white.png"/></div>
</li>
<li>
<input type="hidden" id="fakecolor" value="green"/>
<div onclick="alert(document.getElementById('fakecolorx').value);"><img src="green.png"/></div>
</li>
But when i click on each of the divs, it displays only the value of the second, blue.
Try something like this:
<?php
$cont = 0;
foreach($_color_swatch as $_inner_option_id){
preg_match_all('/((#?[A-Za-z0-9]+))/', $_option_vals[$_inner_option_id]['internal_label'], $matches);
if ( count($matches[0]) > 0 ) {
$color_value = $matches[1][count($matches[0])-1];
?>
<li>
<input type="hidden" id="fakecolor<?php echo $cont; ?>" value="<?php echo $color_value;?>"/>
<div onclick="alert(document.getElementById('fakecolor<?php echo $cont; ?>').value);">
<img src="<?php echo $color_value;?>.png" /></div>
</li>
<?php
}
$cont = $cont + 1;
}
?>
In this way every input hidden have a different id, the same whit the onclick function.
Saludos ;)
I dont quite understand what you're trying to do, still:
<input type="hidden" id="fakecolor" value="<?php echo $color_value;?>"/>
<div onclick="alert(document.getElementById('fakevalue').value);">
First line: you're using an unique id while looping so you'll get several elements with the same id and you'll always end up with the first one with document.getElementById.
Second line: aren't you supposed to get the value of the hidden field ? (ie #fakecolor and not #fakevalue as you're getting).
You have multiple IDs on the same page which will cause getElementById to fail. Why don't you loop and construct your JavaScript like so:
<div onclick="alert("<?php echo $color_value; ?>");">
If you ever move from just alert you can have whatever JavaScript function with a string parameter to accept the color value.

Categories