Show all data from mysql column by "ALL" word - php

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

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]);

Issue with storing values of Multiselect in database

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 !

How to display certain rows from mysql with variable sent via HTML form

I'm trying to get certain data which meets the criteria from the database using AND condition with user searchable HTML form which sends the data to the search.
Code:
<?php
$conn = new mysqli('localhost', 'user', 'pass', 'db');
if ($conn->connect_error) die($conn->connect_error);
$conn->set_charset("utf8");
if (isset($_POST['Kohderyhmä']) &&
isset($_POST['Näytön aste']) &&
isset($_POST['Vaikutusten vahvuus']) &&
isset($_POST['Käyttökelpoisuus']) &&
isset($_POST['text']))
{
$Kohderyhmä = get_post($conn, 'Kohderyhmä');
$Näytön_aste = get_post($conn, 'Näytön aste');
$Vaikutusten_vahvuus = get_post($conn, 'Vaikutusten vahvuus');
$Käyttökelpoisuus = get_post($conn, 'Käyttökelpoisuus');
$text = get_post($conn, 'text');
$query = "SELECT * FROM `tietokanta`
WHERE Kohderyhmä='$Kohderyhmä' AND `Näytön aste`='$Näytön_aste' AND `Vaikutusten vahvuus`='$Vaikutusten_vahvuus' AND `Käyttökelpoisuus: luokka`='$Käyttökelpoisuus'";
}
$results = $conn->query($query);
if (!$results) die ("Database access failed: " . $conn->error);
$rows = $results->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$results->data_seek($j);
$row = $results->fetch_array(MYSQLI_ASSOC);
echo '<h3>' . $row['Nimi'] . '</h3><br />';
echo '' . $row['Kokonaisarvio'] . '<br />';
echo '' . $row['Kuvaus'] . '<br /><br />';
}
?>
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
<b>Kohderyhmä</b><br />
<select name="Kohderyhmä" style="width: 150px;">
<option value="Kaikki">Kaikki</option>
<option value="Pikkulapset">Pikkulapset</option>
<option value="Alle kouluikäiset">Alle kouluikäiset</option>
<option value="Alakouluikäiset">Alakouluikäiset</option>
<option value="Nuoret">Nuoret</option>
<option value="Perheet">Perheet</option>
<option value="Vanhemmat">Vanhemmat</option>
<option value="Työntekijät">Työntekijät</option>
</select>
<br />
<b>Näytön aste</b>
<select name="Näytön aste" style="width: 150px;">
<option value="Kaikki">Kaikki</option>
<option value="Vahva">Vahva</option>
<option value="Kohtalainen">Kohtalainen</option>
<option value="Heikko">Heikko</option>
<option value="Ei riittävää näyttöä">Ei riittävää näyttöä</option>
<option value="Ei arvioitu">Ei arvioitu</option>
</select>
<br />
<b>Vaikutusten vahvuus</b>
<select name="Vaikutusten vahvuus" style="width: 150px;">
<option value="Kaikki">Kaikki</option>
<option value="Vahva">Vahva</option>
<option value="Kohtalainen">Kohtalainen</option>
<option value="Heikko">Heikko</option>
<option value="Ei vaikutusta">Ei vaikutusta</option>
<option value="Ei arvioitu">Ei arvioitu</option>
</select>
<br />
<b>Käyttökelpoisuus</b>
<select name="Käyttökelpoisuus" style="width: 150px;">
<option value="Kaikki">Kaikki</option>
<option value="Vahva">Vahva</option>
<option value="Kohtalainen">Kohtalainen</option>
<option value="Heikko">Heikko</option>
<option value="Ei käyttökelpoinen">Ei käyttökelpoinen</option>
<option value="Ei arvioitu">Ei arvioitu</option>
</select>
<br />
<br />
Haku: <input type="text" name="text" />
<input type="submit" value="Hae" />
</form>
I haven't used PHP to contact database before so the PHP code is very messy.
I don't understand any more than the very basics from PHP, I haven't used variables or objects or anything complex before.
HTML form:
variable1
variable2
variable3
variable4
variable5
--->
PHP script:
select * from db
where variable1 and variable2 and variable3 and variable4
--->
display results matching the criteria
Current code causes this error message in error_log:
PHP Warning: mysqli::query(): Empty query in /home/user/public_html/folder/script.php on line 23
I have already tried over 15 different variations of variables and sql query in total and nothing has worked..
If we shorten your if (isset($_POST ... something you can clearly see. This instruction
$results = $conn->query($query);
is always executed, regardless of whether isset returns true or not.
if (isset($_POST['Kohderyhmä']) &&
...)
{
$Kohderyhmä = get_post($conn, 'Kohderyhmä');
...
$query = "SELECT * FROM `tietokanta`...."
}
$results = $conn->query($query);
So if only one field has not been filled out correctly, the error is always the same :
PHP Warning: mysqli::query(): Empty query in ....
This makes it difficult to determine where the fault really comes from.
Place the curly bracket } behind database logic.
if (isset($_POST['Kohderyhmä']) &&
...)
{
$Kohderyhmä = get_post($conn, 'Kohderyhmä');
...
$query = "SELECT * FROM `tietokanta`...."
$results = $conn->query($query);
if (!$results) die ("Database access failed: " . $conn->error);
$rows = $results->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$results->data_seek($j);
$row = $results->fetch_array(MYSQLI_ASSOC);
....
}
}
?>
create a short test program to test only the database. Set only really necessary data fields in the query
test.php
<?php
$conn = new mysqli('localhost', 'user', 'pass', 'db');
if ($conn->connect_error) die($conn->connect_error);
$conn->set_charset("utf8");
$Kohderyhmä = "KohderyTest"; // replace with really existing values
$query = "SELECT * FROM `tietokanta` WHERE Kohderyhmä='".$Kohderyhmä."' ";
$results = $conn->query($query);
if (!$results) die ("Database access failed: " . $conn->error);
while ($row = $results->fetch_assoc()) {
echo "<h3>" . $row['Nimi'] . "</h3><br />";
echo $row['Kohderyhmä'] ."<br /><br />";
}
$results->free();
?>
Add hardcoded variables $Näytön_aste = "reallyExistingValue"; , add query data field for data field and watch when it starts to stutter.
Also we can not see your function get_post()
If you mean the Wordpress function get_post(), your call to the function is wrong.
I can well imagine that the failure from the function get_post() comes.
And you always false or empty values assigns.
$Kohderyhmä = get_post($conn, 'Kohderyhmä');
assign it direct.
$post = $_POST;
if (isset($post['Kohderyhmä']) &&
...)
{
$Kohderyhmä = $post['Kohderyhmä'];
...
Also you are using all select fields from the <form>, in the query.
4 Select's with 8,6,6,6 options means
8x6x6x6 == 1728
1728 possibilities are you shure you have one datarecord where all values matches.
WHERE Ko...='$Ko...' AND `Näy...`='$Näy...' AND `Vai...`='$Vai...' AND `Käy...`='$Käy...'";
WHERE All four Datafields must match to get a result !!!!!!!!!!!!!
You have to find a combination where all four values simultaneously exist.
UPDATE
OP new question :
If you want empty or some named values stop searching for a value in
database.
required every single variable to be found in the database which it
didn't find because I couldn't set the variable and there is no value
for "Kaikki" in the database, the word "Kaikki" means all choices
below that choice in the HTML form and for that I need some PHP
Here comes the new test.php
1) don't do $post['Näytön aste']; In the form the name is
<select name="Näytön aste" style="...">.
This will translated by submit to
$post['Näytön_aste']; look at the underscore _
This must be done with all select name with spaces in the name !!
2) That was the reason why you get not all $_POST[....] values !
OK ?
3) replace in your form
<form action="<?php $_SERVER['PHP_SELF']; ?>" method="POST">
with
<form action="testNew.php" method="POST">
testNew.php
<?php
$conn = new mysqli('localhost', 'user', 'pass', 'db');
if ($conn->connect_error) die($conn->connect_error);
$conn->set_charset("utf8");
$post = $_POST;
if (isset($post['Kohderyhmä']) &&
isset($post['Näytön_aste']) &&
isset($post['Vaikutusten_vahvuus']) &&
isset($post['Käyttökelpoisuus']))
{
$Kohderyhmä = $post['Kohderyhmä'];
$Näytön_aste = $post['Näytön_aste'];
$Vaikutusten_vahvuus = $post['Vaikutusten_vahvuus'];
$Käyttökelpoisuus = $post['Käyttökelpoisuus'];
} else { die ("No valid values"); }
$count = 0;
$and = "";
$query = "";
if (!empty($Kohderyhmä) && $Kohderyhmä !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Kohderyhmä`= '".$Kohderyhmä."'";
}
if (!empty($Näytön_aste) && $Näytön_aste !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Näytön aste`= '".$Näytön_aste."'";
}
if (!empty($Vaikutusten_vahvuus) && $Vaikutusten_vahvuus !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Vaikutusten vahvuus`= '".$Vaikutusten_vahvuus."'";
}
if (!empty($Käyttökelpoisuus) && $Käyttökelpoisuus !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Käyttökelpoisuus: luokka`= '".$Käyttökelpoisuus."'";
}
if ($count > 0) {
$query = "SELECT * FROM `tietokanta` WHERE ".$query;
} else {
$query = "SELECT * FROM `tietokanta`";
}
echo $query;
if ($results = $conn->query($query)) {
while ($row = $results->fetch_assoc()) {
echo "<h3>" . $row['Nimi'] . "</h3><br />";
echo $row['Kohderyhmä'] ."<br /><br />";
}
} else {
echo "with your choices no records were found";
}
$results->free();
?>
$query = "SELECT * FROM `tietokanta`
WHERE Kohderyhmä='{$Kohderyhmä}' AND `Näytön aste`='{$Näytön_aste}' AND `Vaikutusten vahvuus`='{$Vaikutusten_vahvuus}' AND `Käyttökelpoisuus: luokka`='{$Käyttökelpoisuus}'";
Replace your query with this, and try.

Why can't I create a dropdown list with variables?

I'm trying to create a dropdown list with all the values that i have inside my table, but I can't do it, the select box stay blank.
My PHP code, I'm calling a function
Job category
<select>
<?php
function category($category_id, $category_name){
echo "<option value='".$category_name."'>".$category_name."</option>";
}
?>
</select>
And my function
function selectcategory(){
connect();
$category = ("SELECT * FROM job_categories");
$val = DB_array($category, 'a+');
$ii = count($val);
$ii = $ii - 1;
for ($i = 0; $i <= $ii; $i++) {
$category_id = $val[$i]['category_id'];
$category_name = $val[$i]['category_name'];
category($category_id, $category_name);
}
}
Assuming the flow of your code , that 2nd part executes first , i.e. connection is made , data is fetched and you are calling category() , it will execute
function category($category_id, $category_name){
echo "<option value='".$category_name."'>".$category_name."</option>";
}
$ii times and you are returning to the calling function .
So that's why < select > does not populate the data because it is interpreted after running the above code.
<select>
<?php
$result = category($category_id, $category_name);
foreach($result as $key => $value){
echo "<option value='".$key."'>".$value."</option>";
}
?>
</select>
$sql = mysql_query("SELECT * FROM job_categories");
$result = mysql_db_query($dbname, $sql) or die("Failed Query of " . $sql);
while ($row = mysql_fetch_row($result)){
echo "<option value='".$row["category_id"]."'>".$row["category_name"]."</option>"; // the value should be id
}

fetching option values from mysql

I new to php and mysql.
I wrote the function below:
function catOption() {
$maincatfunc_query = mysql_query("SELECT * FROM mainCats ORDER BY id ") or die(mysql_error());
$funcCat = array();
while ($mainCatFunc = mysql_fetch_array($maincatfunc_query)) {
for ($i = 0; $i < count($maincatfunc_query); $i++) {
$funcCat[$i] = '<option value="'.$maincatfunc_sorgu['mainCatID'].'">' . $maincatfunc_sorgu['name'] . '</option>';
}
}
for ($i = 0; $i < count($maincatfunc_query); $i++) {
return $funcCat[$i];
}
}
I want to fetch "all" value from mysql database and fill it in a dropdown. So i wrote a function like this. But it does not work.
And i don't think count() function doesn't really work in this conditions. How can i get the max count of mysql array ?.
or besides can i do this without using a function ?. I've googled it for a long time but i can't find any usefull info.
Thanks !
You should use like below: [returns array]
function catOption()
{
$query = mysql_query("SELECT * FROM mainCats ORDER BY id ") or die(mysql_error());
$arrCat = array();
while ($row = mysql_fetch_array($query)) {
$arrCat[] = '<option value="'. $row['mainCatID'].'">'. $row['name'].'</option>';
}
return $arrCat;
}
Or this one [returns string]
function catOption()
{
$query = mysql_query("SELECT * FROM mainCats ORDER BY id ") or die(mysql_error());
$arrCat = "";
while ($row = mysql_fetch_array($query)) {
$arrCat .= '<option value="'. $row['mainCatID'].'">'. $row['name'].'</option>';
}
return $arrCat;
}
You should try this,
function catOption() {
$maincatfunc_query = mysql_query("SELECT * FROM mainCats ORDER BY id ") or die(mysql_error());
while ($mainCatFunc = mysql_fetch_array($maincatfunc_query)) {
$funcCat .= '<option value="'.$mainCatFunc['mainCatID'].'">' . $mainCatFunc['name'] . '</option>';
}
return $funcCat;
}
Use like this :
$dropDownData = catOption();
put it into HTML
<select><?php echo $dropDownData; ?></select>

Categories