I have this code and i want to display genres table (ID, name) from my database with checkboxes and this works. Then i want to put old values from genres that become from another book_genre(ID,ID_book, ID_genre) table where i keep ids old and this didn't work. In that while i put all genres from my table and then in that input i want to check where is my old genre from my book_genre table and this not work because my loop through 4 times in genres (1.Action, 2. Thriller, SF, Comedy) and in the book_genre he found 2 values (2,3). At first loop check 1Action with 2 and i want to check 1 Action but without nothing from book_genre and i don't know how... .
$id_book = $_GET['id'];
$qr_genres_old = 'SELECT genres.name,book_genre.ID_genre,book_genre.ID
FROM genres
INNER JOIN book_genre
ON book_genre.ID_genre = genres.ID
WHERE ID_book = "'. $id_book .'"
ORDER BY ID_genre ASC';
$res_genre_old = mysql_query($qr_genres_old);
$qr_select_genres = 'SELECT * FROM genres';
$res_select_genre = mysql_query($qr_select_genres);
while( $row_genre_new = mysql_fetch_assoc($res_select_genre) ){
$row_genre_old = mysql_fetch_assoc($res_genre_old);
?>
<div>
<input type="checkbox" name="ID_gen<? echo $id=$row_genre_new['ID']; ?>"
value="1" <? if($row_genre_old['ID_genre']==$row_genre_new['ID'] ) echo 'checked="checked"'; ?> />
<? echo $row_genre_new['name']; ?>
</div>
Related
I have a problem with checkboxes.
I have some project they you can filter at categories.
So the problem is when you want edit a project that automatic the correct category are checked.
here you see a project but the categories are empty
In mine databank I use is a combo table - one to insert my categories and one for the project and there I have a combo table from.
Here you see my code for display the checkboxes and select for editing so now I looking for some help, for checked the correctly checkbox that belongs to that project.
<div id="categoriefilter">
<?php
$sql = "SELECT * FROM `categories` ORDER BY `id` ASC";
$cats = DB::getResult($sql);
foreach($cats as $cat){
?>
<label>
<input name="cat[]" type="checkbox" value="<?php echo $cat['id']; ?>" >
<?php echo $cat['categorienaam']; ?>
</label>
<?php
}
?>
</div>
If I understand your question correctly. You need 3 tables here
Table1 : projects id, name, ...
Table2: categories id, name, ...
Table3: projects_categories project_id, category_id, ...
The third table is needed to store the categories which are selected for projects
And inside your project page
You need to do the followings:
Select your project by its id
Select categories
Select categories related to the project ( from Table3 )
Here is example ( this is not a working code, just a showcase )
// your project
$project = DB::getResult("SELECT * FROM project WHERE id = :id "); // <== id here
// list of categories
$categories = DB::getResult("SELECT * FROM categories ");
// list of categories for this project
$project_categories = DB::getResult("SELECT category_id FROM projects_categories WHERE project_id = :project_id ");
$project_categories = (array) $project_categories; // in case DB::getResult is not array
<?php
foreach($categories as $category) :
?>
<label>
<input name="cat[]"
<?php if(in_array($category['id'], $project_categories)) echo 'checked="checked"'; ?>
type="checkbox" value="<?= $category['id']; ?>" >
<?php echo $category['name']; ?>
</label>
<?php endforeach; ?>
I'm not down voter. If you knew your problem, you probably mightn't post the question.
You don't include the details code. However for the part as far as I'm understanding,
You should run database UPDATE query inside foreach loop. You don't need to keep the html input inside the loop.
<?php
// check if checkbox is checked
if (!empty($_POST['cat'])){
foreach($_POST['cat'] as $cat){
// run update query here
$sql = "UPDATE `categories` SET `categorienaam` = $whatever WHERE `id` = $cat";
$result = DB::getResult($sql);
}
}
?>
<label>
<input name="cat[]" type="checkbox" value="<?php echo $RowOfApplicableSelectQuery['id']; ?>" >
</label>
$RowOfApplicableSelectQuery comes from the query that you are using to fetch and display your record primarily.
I hope it gives you a clue about what are you looking for.
I have a list of items: userID, pagoID, cursoID.
(Note: I'm testing the concept at the moment, didn't add any safety check yet).
The list is generated programatically, where I retrieve from the database the userID and the pagoID. I added a text input field beside each row for the admin to manually add the cursoID.
I've made a while loop in order to make the list:
while($x=mysqli_fetch_array($mostrarPagos)){
echo $x['pagoID'];
echo $x['userID'];
echo '<input name="verificarPago['.$x['pagoID'].']" type="text">';
};
I've added a submit button, and when it is submitted, the loop should insert into the database a new record with those three pieces of information. The problem is that I don't know how to retrieve the userID as $x['userID'] will live only inside the while loop that creates the table.
So I've tried putting the userId into an input text, and set it as a readonly field. And then do a foreach loop inside another foreach loop.
while($x=mysqli_fetch_array($mostrarPagos)){
echo $x['pagoID'];
echo '<input name="userID['.$x['userID'].']" value="'.$x['userID'].'" type="text">';
echo '<input name="verificarPago['.$x['pagoID'].']" type="text">';
};
if(isset($_POST['submit'])) {
$verificar = $_POST['verificarPago'];
foreach ($verificar as $pago => $curso) {
$userID = $_POST['userID'];
foreach ($userID as $usuario) {
$verificarPago = "INSERT pagosVerificados SET userID = '$usuario', pagoID = '$pago', cursoID = '$curso'";
$cargarPago = mysqli_query($conectar, $verificarPago);
}
if ($verificarPago && $cargarPago) {
}
}
There are two rows in the table with this information (the cursoID is taken from what I type into the input field):
userID. 17 pagoID. 4 cursoID. 18
userID. 18 pagoID. 5 cursoID. 15
The result when I hit submit is this one:
userID. 17 pagoID. 4 cursoID. 18
userID. 18 pagoID. 4 cursoID. 18
userID. 17 pagoID. 5 cursoID. 15
userID. 18 pagoID. 5 cursoID. 15
This is my query:
SELECT DISTINCT pagos.pagoID, pagos.userID, pagos.pagoMonto, pagos.pagoFecha,
pagos.pagoMedioUtilizado, pagos.pagoCuentaOrigen, pagos.pagoSucursal,
pagos.pagoCodigo,
usuarios.userID, usuarios.userEmail,
GROUP_CONCAT(DISTINCT cursos.nombreCurso, ' cid:', cursosUsuarios.cursoID ORDER BY cursosUsuarios.cursoID SEPARATOR '<br>') AS 'cursos'
FROM pagos LEFT JOIN usuarios
ON pagos.userID = usuarios.userID
LEFT JOIN cursosUsuarios
ON usuarios.userID = cursosUsuarios.userID
LEFT JOIN cursos
ON cursosUsuarios.cursoID = cursos.cursoID
AND cursos.estadoCurso = 'abierto'
JOIN pagosVerificados
WHERE pagos.pagoID NOT IN (SELECT pagoID FROM pagosVerificados)
GROUP BY pagos.pagoID
If You need answer to question so do this:
$alreadyHave = array();
while($x=mysqli_fetch_array($mostrarPagos)){
if(in_array($x['pagoID'].'-'.$x['cursoID'], $alreadyHave)) {
continue;
}
echo $x['pagoID'];
echo '<input name="userID['.$x['userID'].']" value="'.$x['userID'].'"type="text">';
echo '<input name="verificarPago['.$x['pagoID'].']" type="text">';
};
BUT technically it's better to have already unique data before iteration, so just put to the end of Your SELECT query: GROUP BY pagoID, cursoID
ALSO sanitize Your INSERT to database (to not to get downvotes by bug-sensitive developers because of Your sql-injectable code) (:
$verificarPago = "INSERT pagosVerificados SET ";
$verificarPago.= " userID = ".(int)$usuario;
$verificarPago.= ", pagoID = ".(int)$pago;
$verificarPago.= ", cursoID = ".(int)$curso;
At first, you can put userID in a hidden input if you don't want to display it (which was your first design choice)
<input type="hidden" id='userID' value="<? echo $x['pagoID'];?>"/>
I'm not sure about double entry but why not using one foreach only and using index for each input like you did for verificarPago
maybe you can replace
echo '<input name="userID['.$x['userID'].']" value="'.$x['userID'].'" type="text">
by
echo '<input name="userID['.$x['pagoID'].']" value="'.$x['userID'].'" type="text">
and then
$userID = $_POST['userID'];
//foreach ($userID as $usuario) {
$verificarPago = "INSERT pagosVerificados SET userID = '$userID[$pago]', pagoID = '$pago', cursoID = '$curso'";
(did not test)
good luck
I am trying to create checkbox with preselected values which comes from my database (Genres). For example, if this movie has 3 different genres: comedy, romance and action (in the database), these genres will be preselected (have default value) checkboxes. The problem is that i need all the checkboxes (genres) which I get from the following SQL-query:
$sql = 'SELECT Movie.* FROM Movie WHERE Movie.id = ?';
and default values (ticked checkboxes) which I get from the following SQL-query:
$sql = 'SELECT Genre.name FROM (Genre JOIN Movie2Genre ON Movie2Genre.idGenre = Genre.id) JOIN Movie ON Movie2Genre.idMovie = Movie.id WHERE Movie.id = ?';
If you have a solution or any simpler method I would love to hear you out. If you find anything here unclear, please tell me and I will do my best correct/add necessary information.
(PS: My if-statement is not working as I want it to do)
<?php
foreach ($allGenre as $val){
foreach ($aktivGenre as $act) {
if ($act==$val) {
$active = "checked";
}else {
$active = "";
}
}
echo "<input type='checkbox' name='{$val["name"]}' value='{$val["name"]}'".$active." >{$val["name"]}"; //$active="selected" when
}
?>
I have 3 SQL tables, "artists", "tracks" and "tracks_artists" (=linking table, because one track can have multiple artists, I'm restricted to use a linking table).
I now have an "edit page" where I want to show 4 selects where you can choose an arists, but with the track's artists already selected. So if an track has 2 artists, I want the first 2 selects to display the previously selected artists (alongside with all the others artists in my database) and the other 2 selects just to show all the artists in the select (with nobody selected).
I'm now using this, but this only works when the track has just one artist:
<select name="edit_artist">
<?php
$query_artist = "SELECT * FROM artists";
$result_artist = mysql_query($query_artist) or die(mysql_error());
while ($row_artist = mysql_fetch_array($result_artist)) {?>
<?php
$query_ta = "SELECT artistID FROM tracks_artists WHERE trackID = $trackID";
$result_ta = mysql_query($query_ta);
while ($row_ta = mysql_fetch_array($result_ta)){
if($row_ta[0]==$row_artist[artistID]){$selected = "selected='selected'";}
else {$selected ="";}
}
?>
<option value="<?php echo $row_artist[artistID]?>" <?php echo $selected;?>><?php echo $row_artist[name];?></option>
<?php }?>
</select>
You need to use the multiple attribute on your select
<select name="edit_artist" multiple="multiple">
If you want to submit this you'll need to make the edit_artist name an array using brackets
<select name="edit_artist[]" multiple="multiple">
I have an edit page that gets populated when accessed. The input values work fine, but I'm having a hard time ticking the category checkboxes. I get the information from two tables. One that displays all the categories and the other one that gets the categories associated with the item.
The following code doesn't work because the second while statement finishes its loop in the first round. Is there an appropriate way to do this?
<?php $check_cats = mysql_query("SELECT * FROM item_categories WHERE itemid = '$itemid'") or die(mysql_error()); ?>
<?php $result = mysql_query("SELECT * FROM categories ORDER BY cname") or die(mysql_error()); ?>
<?php while($row = mysql_fetch_array( $result )) { ?>
<input type="checkbox" id="<?php echo $row['cname']; ?>" name="cat[]" value="<?php echo $row['id']; ?>"
<?php while($check_cat_rows = mysql_fetch_array( $check_cats )) {
if ($check_cat_rows['catid'] == $row['id']) {
echo 'checked="yes"';
}
}
} ?>
My Two tables:
TABLE `item_categories`
`id`
`itemid`
`catid`
TABLE `categories`
`id`
`cname`
Your basic structure could use improvement. Rather than two separate queries, and two nested loops, you could be using a single query which JOINS to the two tables together. Part of the joined data would be the "checked" flag, which you can check for within the loop and output the appropriate html.
SELECT ..., categories.id AS checked
FROM item_categories
LEFT JOIN categories
ON (item_categories.catid = categories.id)
and then while looping:
while($row = mysql_fetch_assoc()) {
$flag = ($row['checked') ? ' checked="yes"' : ''
...
}
Your whole thing is structured incorrectly, you can't assume the two results will line up perfectly, and your loops are wrong. Try this:
SELECT *,
(case when id IN
(SELECT catid FROM item_categories WHERE itemid = '$itemid')
then 1 else 0 end) checked
FROM categories ORDER BY cname
Now you just run the one query and have a nice little $row['checked'] to use!
SELECT *,
(case when categories.id IS NOT NULL
then 1 else 0 end) checked
FROM item_categories
LEFT JOIN categories
ON (item_categories.catid = categories.id)
WHERE itemid = '$itemid'
Improved based on hybrid between marc B and mine... Only efficiency difference is that the query handles testing the validity of categories.id instead of the php
I don't really understand your question, but you want the check box to be checked when the page loads? In that case you have to add "checked" to the tag
<input type="checkbox" name="option2" value="Butter" checked>
Something like this?
<?php
$query = <<<query
SELECT
c.id,
c.cname,
ifnull(ic.catid, '', 'checked="yes"') as checked
FROM
categories c
LEFT JOIN item_categories ic
ON ic.itemid = '$itemid'
AND ic.catid = c.id
ORDER BY
c.cname
query;
$result = mysql_query($query) or die(mysql_error());
while ($row = mysql_fetch_array($result)) { ?>
<input type="checkbox" id="<?=$row['cname'];?>" name="cat[]" value="<?=$row['id'];?>" <?=$row['checked'];?>>
<?
}
?>