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
}
?>
Related
I'm trying to re-write this code so that the drop down menu is alphabetized:
$activeProjectDropdown.="<option value=''>Select Project</option>";
$getInfo = "SELECT id, customer, job_name, haul_info
FROM dispatch_jobs
WHERE (:mydate BETWEEN delivery_date AND delivery_date_end)
ORDER BY customer, job_name";
$result=DB::run($getInfo, ['mydate' => $myDate]);
while($row=$result->fetch(PDO::FETCH_BOTH)) {
if(!empty($row['haul_info'])) {
$haulinfo = "($row[haul_info])";
}else{
$haulinfo = "";
}
if($checkit == $row['id']){
$woot = 'selected=selected';
}else{
$woot = '';
}
$customerName = pdo_getName('name', 'customer', "$row[customer]");
$activeProjectDropdown.="<option value='$row[customer]|$row[id]' $woot>$customerName $haulinfo</option>\n";
}
In this code the query returns some rows from the database where customer is a numeric code which isn't in any kind of alphabetical order. Further down in the code a function called pdo_getName is called which takes a column of name table of customer and the id from $row['customer'] and queries the database, returning the stringified name of the customer. Because the name isn't being retrieved until later on down the loop I'm having trouble figuring out a way that I can alphabetize the $activeProjectDropdown. I've tried putting the $customerName and drop down code into an associative array, then sort that by $customerName and concat everything into a string, but that didn't work because there are duplicate keys. Down that same path, I could potentially have a nested array but I figure there must an easier solution I'm missing. Thanks for the help!
write a JOIN query and get all the data in one query then you can sort on the customers name as I think you are asking to do.
This will improve performance as well as simplify the code.
$getInfo = "SELECT dj.id, dj.customer, dj.job_name, dj.haul_info
c.name
FROM dispatch_jobs dj
LEFT JOIN customer c ON c.id = dj.customer
WHERE (:mydate BETWEEN dj.delivery_date AND dj.delivery_date_end)
ORDER BY c.name, dj.job_name";
$result=DB::run($getInfo, ['mydate' => $myDate]);
while($row=$result->fetch(PDO::FETCH_BOTH)) {
if(!empty($row['haul_info'])) {
$haulinfo = "($row[haul_info])";
}else{
$haulinfo = "";
}
if($checkit == $row['id']){
$woot = 'selected=selected';
}else{
$woot = '';
}
$activeProjectDropdown.="<option value='$row[customer]|$row[id]' $woot>$row[name] $haulinfo</option>\n";
}
Try this:
SELECT ... ORDER BY customer ASC, job_name
This sorts everything by costumer (ascending) first, and then by job_name (ascending, which is the default) whenever the costumer fields for two or more rows are equal.
more info here
I want to make a search with checkboxes. It works when the checkboxes are selected but does not show anything when unchecked. I want to show all the data from database when the checkbox is unchecked
$single = isset($_REQUEST['single']) ? 'Single' : '';
$married = isset($_REQUEST['married']) ? 'Married' : '';
SELECT *
FROM $users_table
WHERE (civil_status = '$single' OR civil_status = '$married')
<input type="checkbox" name = "single">
<label class="label-for-checkbox" >Single</label>
<input type="checkbox" name = "married">
<label class="label-for-checkbox" >Married</label>
In the database there is a column named 'civil status' which has ENUM value 'Single', 'Married'.
There are 2 checkboxes married and single. When I select married checkbox only list of people who are married displays. When I select single only list of single people displays. When both are selected it displays both results. But, when both of them are unchecked I want to show all married and single people.
You need to attach your query on form submit :
$query = "SELECT * FROM `table_name'";
if(isset($_POST['single']))
$query .= "where 'relationship_status' = 'S' or";
if(isset($_POST['married']))
$query .= "where 'relationship_status' = 'M'";
If there are more conditions you can attach condition like above.
Manage the or and and accordingly according as per your requirement.
You would want to use a way to build your sql with and without the various options. An easiest way is to use an array with implode():
$opts = [];
if(isset($_REQUEST['single']))
$opts[] = "civil_status = 'Single'";
if(isset($_REQUEST['married']))
$opts[] = "civil_status = 'Married'";
$sql = "SELECT * FROM {$users_table}";
if(!empty($opts))
$sql .= " WHERE (".implode(" OR ", $opts).")";
If you have nothing selected, it will then write:
SELECT * FROM {$users_table}
If you have one thing selected, it would write:
SELECT * FROM {$users_table} WHERE (civil_status = 'Married')
If both are selected:
SELECT * FROM {$users_table} WHERE (civil_status = 'Married' OR civil_status = 'Single')
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'm using a mixture of php and mysql to do the following query and I'm sure there must be a way to do it in just SQL. I've stripped out some of the code and left enough that you should be able to see what I'm trying to accomplish.
Any help would be much appreciated!
SELECT result_id FROM categories
WHERE name = "conventional"
foreach ( $results as $row ){
$query = "
DELETE FROM categories
WHERE result_id = $row->result_id && (name = 'va' OR name = 'fha' OR name = 'usda' OR name = 'other')
";
$this->db($query);
}
EDIT: From the answers I've received so far, I don't think I've explained this well enough. the columns in this table are id, result_id, name
There are multiple entries that share the same result_id as they relate to entries in the "results" table. So I'm trying to find the result_id's of entries with the name "conventional" so I can find all the entries with the same result_id and delete them if their names are "va", "fha", "usda" or "other"
DELETE FROM categories
WHERE name IN ("va", "fha", "usda", "other")
AND result_id IN (
SELECT result_id FROM categories
WHERE name = 'conventional'
)
You want to avoid delete query in loop and here is how to do it:
SELECT result_id FROM categories
WHERE name = "conventional"
// Now build csv of ids
$arx = array();
foreach ( $results as $row ) {
$arx[] = $row->result_id;
}
if(!empty($arx)) {
$arx_1 = implode(',', $arx);
$query = "DELETE FROM categories
WHERE result_id in ({$arx_1}) AND (name = 'va' OR name = 'fha' OR name = 'usda' OR name = 'other')";
$this->db($query);
}
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'];?>>
<?
}
?>