Issue with storing values of Multiselect in database - php

Alright I have a hell of a problem right now .
I have a bootstrap multiselect like below which allows me to add or remove groups for an user.
Well it works but there is a bug which remove me 1 additional group each time I click on "Submit"
Example : If the user was in 3 groups( blabla, bleble and blibli) and I press Submit without even touching the groups, it will remove the user from 1 group and he will have only 2 left (blabla and bleble).
Here is the PHP code i used for treatement :
$groupes = $_GET['groupes'];
$idc = $_GET['idc'];
if ($groupes != "null") {
$g = explode(',', $groupes);
for ($i = 0; $i < count($g); $i++) {
$sqlDel = "DELETE FROM appartenir WHERE idc = $idc";
$reqDel = mysqli_query($mysqli, $sqlDel) or die('Erreur SQL !<br/>' . $sqlDel . '<br/>' . mysqli_error($mysqli));
}
for ($i = 0; $i < count($g); $i++) {
$sql1 = "INSERT INTO appartenir(idc,idg) VALUES('$idc', '$g[$i]')";
$req1 = mysqli_query($mysqli, $sql1) or die('Erreur SQL !<br/>' . $sql1 . '<br/>' . mysqli_error($mysqli));
}
}
And the HTMLcode of the select if it helps :
<select id="filtreMultiselectModif" name="groupes[]" multiple="multiple">
<?php
while ($data3 = mysqli_fetch_array($req3)) { // Remplissage du SELECT
$idg = $data3['idg'];
$intitule = $data3['intitule'];
?>
<option value="<?php echo $idg ?>" selected><?php echo $intitule ?></option>
<?php } ?>
<?php
while ($data2 = mysqli_fetch_array($req2)) { // Remplissage du SELECT
$idg = $data2['idg'];
$intitule = $data2['intitule'];
?>
<option value="<?php echo $idg ?>"><?php echo $intitule ?></option>
<?php } ?>
</select>
I don't think putting the jquery code will be useful
Any help will be appreciated !

Related

Wanna try some looping for tag <option></option>

Here, i'am had some case that i thought that are uniq for me.
this the problem, i want to looping some tag
3 times. The loop is work, but when it was input to database...
just 1 loop that worked.
Here the Screenshot,
The value of loop
Result of loop
<td>
<label for="baris">Baris</label>
<select name="baris">
<option value="">--</option>
<?php
for ($i2=A; $i2 < F; $i2++) {
echo "<option name='".$i2."'>".$i2."</option>";
}
?>
</select>
</td>
<td>
<label for="kolom">Kolom</label>
<select name="kolom">
<?php
for ($i3=1; $i3 <= 10; $i3++) {
echo '<option name="'.$i3.'">'.$i3.'</option>';
}
?>
</select>
</td>
also this code for input to database
<?php
if(isset($_POST['masukan'])){
$nama = htmlspecialchars($_POST['nama']);
$email = htmlspecialchars($_POST['email']);
$jk = htmlspecialchars($_POST['jk']);
$notlp = htmlspecialchars($_POST['notlp']);
$queryinput = mysqli_query($link, "UPDATE tb_customer
SET nama='$nama',
email='$email',
notlp='$notlp',
jk='$jk'
WHERE id_cust='$id_cust1'
");
$querytampil = mysqli_query($link, "SELECT * FROM tb_customer WHERE id_cust ORDER by id_cust desc limit 1");
$dcus = mysqli_fetch_assoc($querytampil);
$id_cust = $dcus['id_cust'];
$querytampil2 = mysqli_query($link, "SELECT max(num_ticket)AS num FROM tb_ticket");
$dnumti = mysqli_fetch_assoc($querytampil2);
$num_ticket = $dnumti['num'];
$hasil = $num_ticket + 1;
for ($i5= 1; $i5 <= $p; $i5++) {
$baris = htmlspecialchars($_POST['baris']);
$kolom = htmlspecialchars($_POST['kolom']);
if($queryinput){
$id_flight = $data['id_flight'];
$queryinput2 = mysqli_query($link, "INSERT INTO tb_ticket VALUES('','$id_cust','$id_flight','$hasil','','','','','$id_dest','$id_ori', '$baris', '$kolom')");
if ($queryinput2) {
$querytampil3 = mysqli_query($link, "SELECT * FROM tb_ticket order by num_ticket desc limit 1");
$dtick = mysqli_fetch_assoc($querytampil3);
$nt = $dtick['num_ticket'];
echo "<script>alert('Succes.')</script>";
echo '<script>window.location="pembayaran.php?num_ticket='.$nt.'&&id_cust='.$id_cust.'"</script>';
}else{
echo "<script>alert('Your data cannot send.')</script>";
}
}else{
echo "<script>alert('Your data cannot send, please check your input data.')</script>";
}
}
}
?>
Bad engslish sorry*
If I got this correct; it's because you are not setting your html variables as an array.
The first changes you need to make are within your view page..
<select name="baris"> -> <select name="baris[]">
<select name="kolom"> -> <select name="kolom[]">
This sets your $_POST['baris'] and $_POST['kolom'] as arrays.
Since you're already looping...
for ($i5= 1; $i5 <= $p; $i5++) {
$baris = htmlspecialchars($_POST['baris']);
$kolom = htmlspecialchars($_POST['kolom']);
This stuff now needs to access the relevant array... And becomes...
for ($i5= 1; $i5 <= $p; $i5++) {
$baris = htmlspecialchars($_POST['baris'][$i5]);
$kolom = htmlspecialchars($_POST['kolom'][$i5]);

Show all data from mysql column by "ALL" word

I have listbox just like this
<select id="brand">
<option value="All">All</option>
<option value="Acer">Acer</option>
<option value="Alcatel">Alcatel</option>
</select>
And when i choose "Acer" then it is fine works (also Alcatel). But how can I add "all" option to select all brands to show.I wrote following PHP code.But it is not works.How can I create php code for "All" word
$dbClass = new Database();
$extraQuery = "";
$subcategories = json_decode($_POST['subcategories']);
if (!empty($subcategories)) {
for ($i = 0; $i < sizeof($subcategories); $i++) {
for ($j = 0; $j < sizeof($subcategories[$i]); $j++) {
if ($i == 0 && $j == 0) {
$stmt = $dbClass::Connect()->prepare("SELECT * FROM user_posts WHERE brand=:brand");
$stmt->execute(array(":brand" => $subcategories[$i][$j]));
if ($stmt->rowCount() > 0) {
$first = "brand";
if ($subcategories[$i][$j] === "All") {
$stmt = $dbClass::Connect()->prepare("SELECT * FROM user_posts WHERE $first like '%'");
$stmt->execute();
$first = $stmt;
}
$extraQuery = "WHERE (" . $extraQuery . $first . " = " . "'" . $subcategories[$i][$j] . "'";
}
}
}
}
}
$first mean there has more columns i have and want set them "All" word
You can set all value to nothing :
<select id="brand">
<option value="">All</option>
<option value="Acer">Acer</option>
<option value="Alcatel">Alcatel</option>
</select>
Then you can add a where clause in you query only if brand is not empty :
$sql = 'SELECT * FROM user_posts';
$bind = array();
if(!empty($brand)){
$sql .= ' WHERE brand = :brand';
$bind[':brand'] = $brand;
}
$stmt = $dbClass::Connect()->prepare($sql);
$stmt->execute($bind);
Some tuning will be needed to suit your need

PHP MySQL form selection return

I am struggling to get this code to work, what I want from it is to show the item (that is already in the database) to be selected in the selection form.
<label>Server Ports:</label>
<select multiple class="form-control" name="select[]">
<?php
// Get Server Information
$query = "SELECT port_no FROM _servers WHERE (server_id = '$servid') ";
$result = mysql_query($query) or die ('Unable to run query:'.mysql_error());
while($row = mysql_fetch_assoc($result)){
$no = $row['port_no'];
}
$query = "SELECT id, name, port_no, unique_id FROM ports ORDER BY name ASC";
$result = mysql_query($query) or die ('Unable to run query:'.mysql_error());
while($row = mysql_fetch_assoc($result))
{
$port_no = $row['port_no'];
$port_name = $row['name'];
$p_unique = $row['unique_id'];
}
?>
<option value="<?php echo $p_unique;?>"
<?php
if ($p_unique == $no) {
$check = 'selected';
} else {
$check = '';
}
echo $check;
?>
>
<?php
echo $row['name'];
?>
(
<?php
echo $row['port_no'];
?>
)</option>
<?php
}
?>
</select>
Are you sure your test must be if ($p_unique == $no) {} and not if ($port_no == $no) {} ?
If yes, try to checks your variables values :
Do a var_dump() of $no :
var_dump($no);
In your while() loop, you can also check values of $p_unique and $no like that :
var_dump($p_unique.'/'.$no);
Also, here is a simplest way to test for selected :
<option value="<?php echo $p_unique;?>" <?php if ($p_unique == $no) echo 'selected="selected"'; ?>><?php echo $row['name'] ;?> (<?php echo $row['port_no'] ;?>)</option>

How to make <option selected="selected"> set by MySQL and PHP?

How to make <option selected="selected"> set by MySQL and PHP?
My code:
echo '<select>';
$tempholder = array();
$rs = mysql_query("SELECT * FROM id ORDER BY year");
$nr = mysql_num_rows($rs);
for ($i=0; $i<$nr; $i++){
$r = mysql_fetch_array($rs);
//if($year==$r["year"]){ $selected=' selected="selected"'; }//doesn't work so
if (!in_array($r['year'], $tempholder)){
$tempholder[$i] = $r['year'];
echo "<option>".$r["year"]."</option>";//<option$selected>...
}
}
unset($tempholder);
echo '</select>';
Try this one:
echo '<select>';
$tempholder = array();
$rs = mysql_query("SELECT * FROM id ORDER BY year");
$nr = mysql_num_rows($rs);
for ($i=0; $i<$nr; $i++){
$r = mysql_fetch_array($rs);
if (!in_array($r['year'], $tempholder)){
$tempholder[$i] = $r['year'];
echo "<option".(($year==$r["year"])? ' selected="selected"' : '').">".$r["year"]."</option>";
}
}
unset($tempholder);
echo '</select>';
It doesn't saves the state in a variable which you have to overwrite.
And I think the real error was the single equal sign in $year=$r["year"] and not wihtin the rest of the code.
In addition to fixing the =/== gotcha, you can save yourself the array lookup and make the code simpler by asking the database to return each year only once in the query:
<select>
<?php $result= mysql_query('SELECT DISTINCT year FROM id ORDER BY year'); ?>
<?php while($row= mysql_fetch_assoc($result)) { ?>
<option <?php if ($row['year']==$year) { ?>selected="selected"<?php } ?>>
<?php echo htmlspecialchars($row['year']); ?>
</option>
<?php } ?>
</select>
(You may not need htmlspecialchars() assuming that's a numeric year, but it's good practice always to HTML-escape any plain text you include in an HTML template. You can define a function with a shorter name to do the echo htmlspecialchars to cut down on typing.
)
You must define $selected everytime, and you were using the assignment operator instead of the comparison:
echo '<select>';
$tempholder = array();
$rs = mysql_query("SELECT * FROM id ORDER BY year");
$nr = mysql_num_rows($rs);
for ($i = 0; $i < $nr; $i++){
if($year == $r["year"]) { //not $year = $r["year"]
$selected=' selected="selected"';
}
else {
$selected = "";
}
$r = mysql_fetch_array($rs);
if (!in_array($r['year'], $tempholder)){
$tempholder[$i] = $r['year'];
echo "<option$selected>" . $r["year"] . "</option>";
}
}
unset($tempholder);
echo '</select>';
Adding a new answer here for posterity, since the old code, which while correct at the time (actually mysqli did exist, but many hosts didn't support PHP 5), is unfortunately using deprecated code. Instead of using mysql_ extensions, here's a way to handle it using an object oriented approach which will work with mysqli_ connections:
Here's the database connection
$conn = new mysqli($host, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Assuming that the $year variable is coming from a form (though it could be used from GET or SESSION or wherever)
$year = $_POST['year'];
Here's the query for the option button (I have it broken out into different rows to make it a little easier to read):
$result=$conn->query($sql);
while($row = $result->fetch_assoc()) {
if ($row['year']==$year) {
$selected = 'selected="selected"';
}
else {
$selected = '';
}
echo '<option value="'.$row['year'].'" '. $selected . '>"'
. $row['year'] .'</option>';
}

php - auto select drop down menu based on parameters in browser link

If in the browser I have parameters like:
http://localhost/specials.php?year=2009&make=honda&model=civic
and the dropdown looks something like this:
<select name="year">
<?php
$query = mysql_query("select distinct year from tbl_content where year = '$year'");
while($row = mysql_fetch_assoc($query)) {
echo "<option value=\"{$row['year']}\">{$row['year']}</option>";
}
?>
</select>
Now what I'm trying to do is show select when the dropdown options value is equal to the parameter year in the browser URL.
I tried this:
<select name="year">
<?php
$query = mysql_query("select * from tbl_year
while($row = mysql_fetch_assoc($query)) {
#=============================
if(isset($_GET['year'])) {
$year = (int)$_GET['year'];
if($year == $row['year'] { $selected = "selected"; }
else { $selected = "";
}
echo "<option value=\"{$row['year']}\" {$selected}>{$row['year']}</option>";
}
?>
</select>
Maybe try "selected='selected'" to make it valid xml.
<select name="year">
<?php
$selectedYear = NULL;
if(isset($_GET['year']))
$selectedYear = (int)$_GET['year'];
$query = mysql_query('SELECT year FROM tbl_year GROUP BY year ORDER BY year ASC');
while($row = mysql_fetch_assoc($query)) {
echo '<option value="' . htmlspecialchars($row['year']) . '"';
if($selectedYear === (int)$row['year']) {
echo ' selected="selected"';
}
echo '>' . htmlspecialchars($row['year']) . '</option>";
}
?>
</select>
Fell free to separate functionality!
<?php
function selectList($name,$values,$labels=null,$selected=null){
if($labels==null) $labels=&$values;
$data="<select name='$name'>";
foreach($values as $k=>$v){
$selected=($v==$selected)?'selected="selected"':false;
$data.="<option value='$v' $selected>".htmlspecialchars($labels[$k])."</option>";
}
$data.="</select>";
return $data;
}
$select=isset($_REQUEST['year'])?(int) $_REQUEST['year']:null;
$query=mysql_query("SELECT DISTINCT `year` FROM `tbl_year` ORDER BY `year`");
while(($row=mysql_fetch_assoc($query))!==false){
$values[]=$row['year'];
}
echo selectList("year",$values,null,$select);
?>

Categories