How to make a dynamic select box with php and mySQL - php

I have a table that prints out all of the users from my table. Next to each user is a select box and a update button. The problem I am having is that the script only reads from the last select box. How can I make the select box dynamic so the script knows which row the select box is from?
code for the select box:
<select name="level" >
<option value="basic" SELECTED>Basic</option>
<option value="premium">Premium</option>
<option value="platinum">Platinum</option>
</select>
<button type="submit" name="update" value="<?php echo $row['id'] ?>">Update</button>
Code in another script that comes into effect when the submit button is pressed:
if ( isset( $_POST['update'] ) ) {
//Get the ID of the account that will be updated
$userID = $_POST['update'];
//Get the level that the admin wishes to change to
$level= $_POST['level'];
//Connect to the DB
mysql_connect("localhost", "xxxx", "xxxx")or die("Cannot connect to database");
mysql_select_db("xxxx")or die("Database cannot be selected or it doesnt exist");
//Updates the users access level
mysql_query("UPDATE users SET level='$level' WHERE id='$userID' ");

Just looking at the html, you are overwriting your select box values as they all have the same name.
The easiest solution would be to convert the name of your select box in an array:
<select name="level[<?php echo $row['id']; ?>]" >
No you can access them server-side as:
$_POST['level'][$userID]
You also need to switch to PDO / mysqli and prepared statements with bound variables to avoid your sql injection problem.

You can use jquery for it. Try this,
$(document).ready(function(){
var values = [];
$('select[name=level]').each(function() {
values[] = $(this).val();
});
$('button[name=update]').val(values);
});
The reason it is only reading the last row, is that $row['id'] contains only the last row from the iterated resultset.

Use this:
<input type="hidden" name="userid[]" value="#THEUSERID"/>
<select name="level[]" >
<option value="basic" SELECTED>Basic</option>
<option value="premium">Premium</option>
<option value="platinum">Platinum</option>
</select>
if ( isset( $_POST['update'] ) ) {
foreach($_POST['userid'] as $k=>$userID){
//Get the level that the admin wishes to change to
$level= $_POST['level'][$k];
//Connect to the DB
mysql_connect("localhost", "xxxx", "xxxx")or die("Cannot connect to database");
mysql_select_db("xxxx")or die("Database cannot be selected or it doesnt exist");
//Updates the users access level
mysql_query("UPDATE users SET level='$level' WHERE id='$userID' ");
}
}

Related

if statement in dropdown dependent on database values and user login

My question is about a drop-down list which is dependent on the database values which has been assigned to the user which is logged in. I have used a session variable to identify the user logged in.
I would like one drop-down list to display 3 options if the user logged in has a contact ID of 1 OR 2. If the user logged in has a contact ID of 3, then a drop-down list displays with only 2 values.
My code is below which connects to the database and fetches data from a query. If the query values are not empty the first drop-down displays with 2 values, and if the query values are empty, the second drop-down displays with 3 values.
<?php $connect = mysqli_connect('localhost', 'dm459', 'dm459',
'dm459_kiamycontacts'); //This is my connection to the database
$query = "SELECT * FROM employee WHERE contactID = 3 AND
employeeUsername = '" .$_SESSION['User'] . "' LIMIT 1";
//This is the query to the database
$result1 = mysqli_query($connect, $query); ?>
<select id="dropdown">
<?php $row1 = mysqli_fetch_array($result1);
if(!empty($row1)) { ?>
<option class="select" value="0">Kia Academy</option>
<option class="select" value="1">
Dealer Development</option> <?php }
elseif (empty($row1)) { ?>
<option class="select" value="0">Kia Academy</option>
<option class="select" value="1">
Dealer Development</option>
<option class="select" value="2">Dealership</option>
<?php } ?>
</select>
Using contact ID, you could do this:
if(3 == $row1['contactID']) {
// display 2 options
} elseif(2 == $row1['contactID'] || 1 == $row1['contactID']) {
// display 3 options
}

value of options loaded from db in dropdown list

I used the below code to get the datas or options in my dropdown list from mysql db. also it works fine, but my problem is when i select a particular option from this dropdown list, on submission no value or empty value is saving for that for field. simply i can see the option name, but value is seems like this
value=" ";
actually, value is what i see as option name.
<strong> Select Data </strong>
<select name="data1">
<option value=""> NONE </option>
<?php
//Mysql db connection
$con = mysqli_connect("localhost", "my_user", "my_password", "my_db");
//Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Perform queries
$rs = mysqli_query($con, "SELECT DISTINCT relation FROM relation_names");
if ($rs && mysqli_num_rows($rs)) {
while ($rd = mysqli_fetch_object($rs)) {
echo("<option value='$rd->id'>$rd->relation</option>");
}
}
mysqli_close($con);
?>
</select>
add id in query too
$rs = mysqli_query($con,"SELECT DISTINCT relation,id FROM relation_names");
Then only
$rd->id
will populate correct value
If you want relation as value then do like below:
echo("<option value='$rd->relation'>$rd->relation</option>");

How can I hide some option in HTML from mysql

In php:
$query ="SELECT rent FROM mydatabase WHERE rent= '$rent'";
$rs=mysqli_query($connect,$query);
if(!$rs)
{echo "<script type ='text/javascript'>alert('Cannot connect to database')</script>";
}
else
{ if(mysqli_num_rows($rs) != 0)
{die("<script type ='text/javascript'>alert('The selected room are not available')</script>");}
}
$sql = "INSERT INTO mydatabase(title,first_name,last_name,dob,email,id,password,rent) VALUES('$title','$first_name','$last_name','$dob','$email','$id','$password','$rent')";
mysqli_query($connect,$sql);
$_SESSION['first_name'] = $first_name;
$_SESSION['rent'] = $rent;
header("location: database.php");
In html:
<select name = "rent">
<option></option>
<option name= "rent" value="A1">A1</option>>
<option name= "rent" value="A10">A10</option>
<option name= "rent" value="A3">A3</option>
<option name= "rent" value="A4">A4</option>
<option name= "rent" value="A5">A5</option>
<option name= "rent" value="A15">A15</option>
<option name= "rent" value="A20">A20</option>
<option name= "rent" value="A8">A8</option>
<option name= "rent" value="A6">A6</option>
<option name= "rent" value="A12">A12</option>
</select>
Here,I want to set unique for rent value. For example, if customer had selected rent value 'A1' again he cannot select the same value. The problem is I also want to set the empty option for customer which does not want to select any option and store their data in database. But the empty option () cannot be entered two time. So what the thing can I give to overcome this. Ps. I am totally amateur and my English is not so good. Thank You :)
I think the best solution for your problem is you need to create your selection dynamically from your database, I mean get what rent didn't take or has been taken by users from your database.
i.e after user loaded the page that selection fills data from database not put it like static. for this, you can create one more table, or just simply add one more field to determines the rent, I called "IsTaken" it returns 1 for Yes, or 0 for not taken.
after user took then update "IsTaken" from 0 to 1 it means it's taken by the user, or after removed you can update from 1 to 0.
for each new record that you or your users insert, add a query to update that field. also for removing each record.
for the update:
update table t1 set rname = 1 where 'your condition to update only this record'
for the delete:
delete from t1 where 'your condition to delete only this record'
please see my solution and let me know if your problem is solved or not.
the following code is just shown selection query.
See this:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "stackoverflow";
$conn = new mysqli($servername, $username, $password, $dbname);
//SELECT those record that not taken, be default i set that field to 0
$sql = "SELECT rname FROM t1 where istaken = 0";
$result = mysqli_query($conn,$sql);
?>
<form action= "" method= "post">
<select name = "rent">
<?php
if ($result->num_rows > 0) {
//fill options with data returns from our query..
while($row = $result->fetch_assoc()) {
echo "<option name=".$row['rname'].">" . $row['rname'] . "</option>";
}
} else {
//if there is no record...
echo "<option name='None'>None</option>";
}
?>
</select>
</form>
<?php
$conn->close();
?>
.
.
.
I am sorry if I have any grammar or spelling error, hope you understand what I am did here.

Mysql php select Columns after selecting from dropdown

I need help with a thing regarding mysql and php.
I have the following dropdown:
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
And a database with all car models.
I need to echo a SELECT from my database based on the value selected from the dropdown.
So if the user in the website selects Volvo he will recieve selection from my mysql database with the following info:
Volvo S30
Volvo S60
Volvo S90
etc.
EDIT
The select would be :
SELECT Imagename, Imageurl FROM pics WHERE Carmaker=Volvo
But i don`t know how to make the SELECT be conditioned by the users selected option.
I will try to give you a quick help.
First you have to set the name attribute at html select.
<select name="type">
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Mercedes</option>
<option value="4">Audi</option>
</select>
Then in the file that form redirects you:
$connection = mysqli_connect('localhost', 'root', 'your_password', 'your_database');
mysqli_set_charset($connection, 'utf8');
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
$car_type = (int)$_POST['type']; //Code for user input validation and sanitization
$query = "SELECT Imagename, Imageurl FROM pics WHERE Carmaker = '$car_type';";
$result = mysqli_query($connection, $query);
if(!$result) {
die("SQL Error: " . mysqli_error($connection);
}
//Then you can make a loop to take the data one by one
while ($row = mysqli_fetch_array($result)) {
echo '<p>'.$row['Imagename'].' '.$row['Imageurl'].'</p>';
}
For start try to use queries using mysqli_* functions (not mysql_*). Then try to learn PDO or something similar. Also it is very important to read some tutorials explaining server side user input validation and sanitization.

Select box is generated by JavaScript but value is not passed on form submit

I've got a second select box which is created using Javascript when the user selects a value from the first select box. The JS runs a PHP file which queries a MYSQL database for the relevent items depending on the first selection.
The problem I'm having is that the value for the item the user selects in the second box is not passed in the header when the form is submitted.
Does anyone have any ideas how to get the value and pass it in the header?
Thanks.
This is the PHP for the second select box:
<?php
$cxn = mysqli_connect("localhost", "root", "root", "db") or die("Couldn't connect");
$choice = $_GET['choice'];
$query = "SELECT ID, Model FROM models WHERE MakeID ='$choice'";
$result = mysqli_query($cxn, $query) or die("Couldn't execute query");
echo "
<select id='model' name='model'>
<option value='0'>Model (any)</option>";
while ($row = $result->fetch_object()) {
echo "
<option value='$row->ID'>$row->Model</option> \n
";
}
echo "
</select> ";
?>
After creating select field you must append it to your form.
<script>document.getElementById("MyForm").appendChild("select_field_id");</script>

Categories