How to change the option text in php? - php

I tried to build an admin page. The admin will fill a form to add new product in the database and display it in the shop website. The problem is when I tried to select a gender from the dropbox, the new product doesn't add in the product table in the database as you can see below: (I want to select gender such as Boys)
The Admin Page and database result:
The code I used:
$host = "";
$userMS = "";
$passwordMS = "";
$connection = mysql_connect($host,$userMS,$passwordMS) or die("Couldn't connect:".mysql_error());
$database = "projectDataBase";
$db = mysql_select_db($database,$connection) or die("Couldn't select database");
if (isset($_POST['sAddProduct']))
{
addNewProduct();
}else if(isset($_POST['delete']))
{
$Product_ID=$_POST['Product_ID'];
$mysqlquery="delete from Product where Product_ID= ".$Product_ID."";
mysql_query($mysqlquery);
echo "Deleted successfully";
echo("<FORM><INPUT Type='button' VALUE='Back' onClick='history.go(-1);return true;'></FORM>");
}else{
showForm();
}
// add new product
function addNewProduct()
{
$ProductName = $_POST['Product_Name'];
$ProductPrice = $_POST['Price'];
$Gender = $_POST['Gender_ID'];
//database query to add product
$insertStringProduct = "INSERT into Product(Product_Name, Price,Gender_ID)
VALUE('$ProductName', '$ProductPrice', '$Gender')";
$result = mysql_query($insertStringProduct);
echo ("<p1>Product added Successfully</p1>");
echo("<FORM><INPUT Type='button' VALUE='Back' onClick='history.go(-1);return true;'></FORM>");
}
//function for the form page
function showForm()
{
//First form for adding new product
$self = htmlentities($_SERVER['PHP_SELF']);
echo("<form action = '$self' method='POST'>
<fieldset>
<legend>Adding New Product</legend>
Product Name: <input name='Product_Name' type='text' size = '40'>
<br /><br />
Price: <input name='Price' type='text' size = '20'><br><br />
Gender:
<select name='Gender_Description'>
<option value = '%'> <-- select--></option>");
$dbQuary = " SELECT DISTINCT Gender_Description from Gender";
$result = mysql_query($dbQuary);
while($row = mysql_fetch_row($result)){
echo("<option value ='$row[0]'> $row[0]</option>");
}
echo("
</select>
<br/><br/>
<input type='submit' name='sAddProduct' value = 'Add'/>
<input type='reset' value='Clear' />
</fieldset>
</form>");
}
The result ( nothing added)
However, when I change the code to
Gender:
<select name='Gender_ID'>
<option value = '%'> <-- select--></option>");
$dbQuary = " SELECT DISTINCT Gender_ID from Gender";
$result = mysql_query($dbQuary);
It's working
Can anyone help me with this?

In addNewProduct you are expecting $_POST['Gender_ID'] to be set. So of course, <select name='Gender_Description'> would not work, because Gender_Description != Gender_ID. That's also why it does work when you change it.
I'm assuming what you want to achive is to display the gender description, and it still to work. For that, you need both the id and the description:
$dbQuary = " SELECT DISTINCT Gender_ID, Gender_Description from Gender";
$result = mysql_query($dbQuary);
while($row = mysql_fetch_row($result)){
echo("<option value ='$row[0]'> $row[1]</option>");
}
Security
Your code is extremely unsafe. You are using mysql_* which is deprecated since 2013, and you are not sanitizing the input in any way, so your code is open to SQL injection (which is possibly in all kinds of queries; insert, update, delete, etc, and allows for data leaks, DOS, and possibly code execution and deletion/changing of data). The preferred way to prevent this are prepared statements (either using mysqli_* or PDO). They are not difficult to use, and the resulting code is also nicer.

You are not concatenating values as it should
Change
echo("<option value ='$row[0]'> $row[0]</option>");
to
echo("<option value =". '$row[0]' . "> ". $row[0]. "</option>");
OR
echo("<option value ='{$row[0]}'> {$row[0]}</option>");
EDIT:
Change your While-loop
while($row = mysql_fetch_array($result,MYSQL_BOTH)) {
echo("<option value ='{$row['gender_id']}'> {$row['gender_description']}</option>");
}
This will generate a Select list showing the Gender Description and and values will be numeric(of database)

Related

Using data in <select> options in MySQL query

I would like to delete a row from an MySQL database. The row that I'd like to delete is displayed in a box, with each being obtained via a loop and SELECT statement.
I've already got the rows in the database being displayed accordingly; however, I'd like a button that once pressed, would delete the selected option from the database.
Here is my current code:
<form action="" method="post">
<label>Patient Name:</label>
<br><br>
<select name="patient" id="patient">
<?php
$conn = new mysqli("localhost", "root", "", "as2");
$result = $conn->query("SELECT patientID, patientName, address FROM patient ORDER BY patientName ASC");
while ($row = $result->fetch_assoc()){
$patientName = $row['patientName'];
$address = $row['address'];
echo "<option value=\"patient\">" .$patientName. ", ".$address."</option>";
}
?>
</select>
<input type="submit" name="delete" value="Delete Record">
</form>
How would I go about making the "Delete Record" button delete the selected option from the database?
first record (patientID) in a string
$patientID = $row['patientID'];
then Add $patientIDto (option value) so it become :
echo "<option value=".$patientID.">" .$patientName. ", ".$address."</option>";
then add this code After everything (ofc outside the "while" loop) :
<?php
$selected_patient = $_POST['patient'];
if( $_SERVER['REQUEST_METHOD'] === 'POST'
&& isset($_POST['delete']) && isset($_POST['patient']) ) {
if( !empty($_POST['patient']) ){
$patient_ID = mysql_real_escape_string($selected_patient);
if ( $conn->query("DELETE FROM patient WHERE patientID={$patient_ID}") )
echo "user has been deleted successfully";
else
echo "Error deleting";
}
}
?>
now you'r good to go , after click delete button refresh your page and Boom! , the user will Disappears
and if you want a real time Action u can use (Ajax)
Try this
while ($row = $result->fetch_assoc()){
$patientName = $row['patientName'];
$address = $row['address'];
$patientID = $row['patientID']; //get patient id
echo "<option value=\"$patientID\">" .$patientName. ", ".$address."</option>"; // change in option value
}
Now on form submit, you will get patient id in $_POST['patient'] , can write your delete query.
Hope this will hope.

Get value form same table

I have dropdown menu with 3 values.
and here is my table (table name is Sms)
What I want to do? Example : If I choose 2,49 and press submit, then I get sonum value.
This is my form
<div class="col_12" style="margin-top:100px;">
<div class="col_6">
<label for="asukoht">Vali Hind</label>
<form class="vertical" method="GET">
<select name="hind">
<option value="1">-- Vali --</option>
<?php
// Tegin dropdown menüü, kust saab valida komponendi, mille alla see pilt läheb
$andmed = mysql_query("SELECT * FROM Sms");
// Dropdown menüü
while($rida = mysql_fetch_array($andmed)){
echo '<option value="'.$rida['id'] . '">'.utf8_encode($rida['hind'] ). '</option>';
}
?>
<input type="submit" name="add" id="add">
</form>
I tried something like this
if(mysql_query("DESCRIBE `Sms`")) {
$sql = "SELECT sonum FROM `Sms`";
echo $sql;
}
I think it should be pretty easy, but I'm looking for a solution and I didnt found it.
Thank you for helping !
You need to work on SQL and Loop.
Based on your code:
if(mysql_query("DESCRIBE `Sms`")) {
$sql = "SELECT sonum FROM `Sms`";
echo $sql;
}
First we do change the query including $_GET parameter.
So this:
$sql = "SELECT sonum FROM `Sms`";
Will become:
$sql = "SELECT sonum FROM `Sms` WHERE id = ".$_GET['hind'];
It will be better if you check that the var exist and is setted with something like:
if(isset($_GET['hind']) && is_numeric(trim($_GET['hind']){//Code here}
But it is off-topic.
Now let's change echo $sql; with a loop, we need to loop and fetch the data.
while($result = mysql_fetch_array($sql)){
echo '<option value="'.$result ['id'] . '">'.utf8_encode($result ['hind'] ). '</option>';
}
I've only changed what i know, you know your system ^_^
You should do:
$sql = "SELECT sonum FROM Sms WHERE id = ".$_GET['hind'];
Then do :
echo mysql_query($sql);
$sql = "SELECT sonum FROM Sms WHERE id = ".$_GET['hind'];
while($rida = mysql_fetch_array($sql)){
echo '<option value="'.$rida['id'] . '">'.utf8_encode($rida['hind'] ). '</option>';
}
Do not use MYSQL queries...try MySQLi or PDO with prepared statement.

Set amounts in database using php + form

In my database users have a balance, im trying to set up a form that allows them to transfer amounts to each other. So for the from user it would - out of their current balance and update it to the new balance ( existing - amount transferred ) and for the receiver it would update ( existing + amount received ).
Heres my code below but its not updating any of the information:
<?php
if (isset($_POST['submit'])) {
$fromuser = $_POST['fromuser'];
$touser = $_POST['touser'];
$amount = $_POST['amount'];
$balanceto = mysql_query("SELECT `money` FROM `users` WHERE username = '$touser'");
$res1 = mysql_fetch_array($balanceto);
$balancefrom = mysql_query("SELECT `money` FROM `users` WHERE username = '$fromuser'");
$res2 = mysql_fetch_array($balancefrom);
$newmoney1 = ($res1['money'] + $_POST['amount']);
$newmoney2 = ($res2['money'] - $_POST['amount']);
$result1 = mysql_query("UPDATE `users` SET `money`='$newmoney1' WHERE username = '$touser'");
$result2 = mysql_query("UPDATE `users` SET `money`='$newmoney2' WHERE username = '$fromuser'");
}
?>
<form class="reg-page" role="form" action="" method="post">
<center>
Please note: Transfering funds is done at your own risk, please make sure you transfer the funds to the right person.<br><br>
<?php
$query = "SELECT username FROM users";
$result = mysql_query($query) or die(mysql_error());
$dropdown = "<div class='row'><div class='col-sm-6'><label>Transfer $ To<span class='color-red'> *</span></label><select name='touser' class='form-control margin-bottom-20'>";
while($row = mysql_fetch_assoc($result)) {
$dropdown .= "\r\n<option value='{$row['username']}'>{$row['username']}</option>";
}
$dropdown .= "\r\n</select></div><div class='col-sm-6'>
<label>Amount $<span class='color-red'> *</span></label>
<input type='text' name='amount' class='form-control margin-bottom-20'>
</div></div>";
echo $dropdown;
?>
<input type="hidden" value="<?php echo $user_data['username']; ?>" name="fromuser">
<button type="submit" class="btn-u">Transfer</button>
</center>
</form>
All help much appreciated.
$_POST does not contain submit because you never put a NAME tag on the submit button.
Instead of:
<button type="submit" class="btn-u">Transfer</button>
You need:
<button type="submit" class="btn-u" name="submit">Transfer</button>
See here:
How do I post button value to PHP?
On further reflection it's probably a good idea to talk about some of the problems here, let's start with this one:
$balanceto = mysql_query("SELECT `money` FROM `users` WHERE username = '$touser'");
$res1 = mysql_fetch_array($balanceto);
$balancefrom = mysql_query("SELECT `money` FROM `users` WHERE username = '$fromuser'");
$res2 = mysql_fetch_array($balancefrom);
This is duplicated code, you can move this into a function to avoid copying and pasting, which is good practice, and you can use that function in other places in your code when you need to get the balance. Formatting the structure correctly helps in the event that your table changes, and you need to update the SQL. Without this in a single place, you are going to climb all over your code to find all the changes and update them.
<input type="hidden" value="<?php echo $user_data['username']; ?>" name="fromuser">
This is very bad practice, as it makes it easy for someone to slip an extra variable into the header and submit whatever user they want to your code, transferring money out of any other account that they want. Since this page already has access to this variable:
$user_data['username']
You should be using this in the IF statement at the top, instead of submitting it along with the form.
<input type='text' name='amount' class='form-control margin-bottom-20'>
This is another problem. You are asking for an amount, but creating a text field. A better example of this would be:
<input type='number' name='amount' class='form-control margin-bottom-20'>
Again though, these are easily modifiable post values, you have to make sure to check again on the server to make sure you didn't get fooled:
if(!(isNumeric($_POST['amount']) || $_POST['amount'] == 0 || $_POST['amount'] == ''))
The code above checks to make sure you have a numeric value, and that it is not 0 or blank, both of which would be invalid inputs. If either of those values is submitted, then it errors out and sends the user back to the form without processing the update.
Later on in your code, you start a PHP Tag to create the drop down:
<?php
$query = "SELECT username FROM users";
$result = mysql_query($query) or die(mysql_error());
$dropdown = "<div class='row'><div class='col-sm-6'><label>Transfer $ To<span class='color-red'> *</span></label><select name='touser' class='form-control margin-bottom-20'>";
Assigning all of this to the $dropdown variable is completely wasted if you aren't going to use that drop down again (and it seems you are not). I can see that you wrapped it in PHP so you can loop over the options to print them out, but you can do that just as easily with a smaller PHP tag with a loop inside it, like this:
<select name='touser' class='form-control margin-bottom-20'>
<option value="null">Not Selected</option>
<?php
// Loop over all our usernames...
while($row = mysql_fetch_assoc($result)) {
// If we're not the current user...
if($row['username'] != $user_data['username']) {
// Add a drop down option!
echo "<option value='" . $row['username'] . "'>" . $row['username'] . "</option>";
}
}
?>
</select>
Note that this option ALSO includes a default "null" value for the select menu, and filters out the existing user (you can't transfer money to yourself, at least in this example). The null value is necessary because without it your code would automatically select the first user on the drop down list.
This would be my implementation of the same set of code here:
<?php
// If our submit is set...
if (isset($_POST['submit'])) {
// Get the balance for the from user
$fromBalance = getBalance($user_data['username']);
// Get the balance for the to user
$toBalance = getBalance($_POST['touser']);
// Get our new amounts, but don't do anything yet!
$newmoney1 = $toBalance + $_POST['amount'];
$newmoney2 = $fromBalance - $_POST['amount'];
// Check to make sure we have a valid amount
if(!(isNumeric($_POST['amount']) || $_POST['amount'] == 0 || $_POST['amount'] == '')) {
// Or error out!
echo 'ERROR: Bad amount Specified!';
// Check to make sure we have two valid users
} elseif($user_data['username'] == $_POST['touser']) {
// Or error out!
echo 'ERROR: Cannot transfer money to yourself!';
// Check to make sure sufficient funds are available
} elseif($newmoney2 < 0) {
// Or error out!
echo 'ERROR: Insufficient funds!';
// Check for default user selection...
} elseif($_POST['touser'] === 'null') {
// Or Error Out
echo 'ERROR: No username selected!';
// Otherwise we are good...
} else {
// So we call our update functions.
updateMoney($user_data['username'], $newmoney2);
updateMoney($_POST['touser'], $newmoney1);
// Send a success message
echo 'Transfer completed successfully, thank you!<br /><br />';
}
}
/** updateMoney()
*
* This function will take a user name and an amount and update their balance.
* Created to re-use code instead of copy and paste.
*
* #arg $user string
* #arg $amount integer
*/
function updateMoney($user, $amount) {
// Update our database table for this user with this amount
$result1 = mysql_query("UPDATE `users` SET `money`='$amount' WHERE username = '$user'");
}
/** getBalance()
*
* This function will return a balance for a given username.
* Created to re-use code instead of copy and paste.
*
* #arg $user string
* #return $amount integer
*/
function getBalance($user) {
// Execute query to get the result
$result1 = mysql_query("UPDATE `users` SET `money`='$amount' WHERE username = '$user'");
// Assign the result to a value
$res1 = mysql_fetch_array($balanceto);
// Return only the value we care about
return $res1['money'];
}
// Set our query for getting usernames from the DB
$query = "SELECT username FROM users";
// Get the usernames!
$result = mysql_query($query) or die(mysql_error());
?>
<form class="reg-page" role="form" action="" method="post">
<center>
Please note: Transfering funds is done at your own risk, please make sure you transfer the funds to the right person.
<br>
<br>
<div class='row'>
<div class='col-sm-6'>
<label>Transfer $ To<span class='color-red'> *</span></label>
<select name='touser' class='form-control margin-bottom-20'>
<option value="null">Not Selected</option>
<?php
// Loop over all our usernames...
while($row = mysql_fetch_assoc($result)) {
// If we're not the current user...
if($row['username'] != $user_data['username']) {
// Add a drop down option!
echo "<option value='" . $row['username'] . "'>" . $row['username'] . "</option>";
}
}
?>
</select>
</div>
<div class='col-sm-6'>
<label>Amount $<span class='color-red'> *</span></label>
<input type='number' name='amount' class='form-control margin-bottom-20'>
</div>
</div>
<button type="submit" class="btn-u" name="submit">Transfer</button>
</center>
</form>
But you STILL need to go fix the code so that you are NOT using MySQL and switch to MySQLi or PDO so that you can do prepared statements and actually protect yourself from MySQL injection attacks.
See here for more details:
https://wikis.oracle.com/display/mysql/Converting+to+MySQLi
You have posting the form with nameless button and trying to access via $_POST['submit']
<button type="submit" class="btn-u">Transfer</button>
name is missing. Add and try
<button type="submit" name="submit" class="btn-u">Transfer</button>
I think the button is missing tag 'name'. Try add this on your button:
<button type="submit" class="btn-u" name='submit'>Transfer</button>
To optimize your script I suggest do this:
if (isset($_POST['submit'])) {
$fromuser = $_POST['fromuser'];
$touser = $_POST['touser'];
$amount = $_POST['amount'];
$result1 = mysql_query("UPDATE `users` SET `money`= `money` + '$amount' WHERE username = '$touser'");
$result2 = mysql_query("UPDATE `users` SET `money`= `money` - '$amount' WHERE username = '$fromuser'");
}
So, you will eliminate two steps of processing and two hits on database.
start transaction
INSERT INTO power (sender, receiver, amount) VALUES ('$sender', '$receiver', '$amount')
UPDATE users SET power=power-$amount WHERE user_id='$sender'
UPDATE users SET power=power+$amount WHERE user_id='$receiver'
Submit button missing the name tag. use Transfer
Nothing glaringly wrong with the code, I'm assuming this is fake money.
Probably a malformed sql statement, try echoing the attempted sql before hand.
make sure all the queries work for a test example.

Issue deleting rows in SQL of type varchar

I am trying to create a form that will delete a row in a table based on the attribute a user selects from a drop down list of options. For some reason the first option, (attemptid) which is an int, works, but the other three (which are varchar) do not. The error handling I have set up to debug the script is returning 1 or true, but the row in question is not deleted.
HELP! I have tried everything but am only just learning PHP so imagine I am missing something quite simple.
require_once("settings.php");
$conn = #mysqli_connect($host, $user, $pass, $db);
if ($conn) {
?>
<form method="post" action="delete_attempts.php" name="delete_attempts" id="delete_attempts" >
<label for="deleteby">
<p>Select an option to delete results by:</p>
</label>
<select name="deleteby">
<option value="attemptid">Attempt ID</option>
<option value="firstname">First Name</option>
<option value="lastname">Last Name</option>
<option value="studentid">Student ID</option>
</select>
<p></p>
<input type="text" name="delvalue" placeholder="Value">
<div>
<input type="submit" value="Delete Record" id="submit" />
</div>
</form>
<?php
if (isset($_POST["delvalue"])) {
// get value from form
$delValue = trim($_POST["delvalue"]);
echo $delValue;
// queries to delete record
$queryAttemptId = "DELETE FROM quizattempts WHERE attemptid = '$delValue'";
$queryFirstName = "DELETE FROM quizattempts WHERE firstname = '$delValue'";
$queryLastName = "DELETE FROM quizattempts WHERE lastname = '$delValue'";
$queryStudentId = "DELETE FROM quizattempts WHERE studentid = '$delValue'";
//select which value to search for
if ($_POST["deleteby"] = "attemptid") {
// pass query to database
$result = mysqli_query($conn, $queryAttemptId);
} // end delete attemptid
else if ($_POST["deleteby"] = "firstname") {
// pass query to database
$result = mysqli_query($conn, $queryFirstName);
} // end delete firstname
else if ($_POST["deleteby"] = "lastname") {
// pass query to database
$result = mysqli_query($conn, $queryLastName);
} // end delete lastname
else if ($_POST["deleteby"] = "studentid") {
// pass query to database
$result = mysqli_query($conn, $queryStudentId);
} // end delete student id
echo "this is the result $result";
// if query is successful are found
if ($result) {
echo "<p>Delete operation successful</p>";
} // end if result found
else {
// if no record is found in DB
echo "<p>No records found</p>";
} // end if no result found
} //isset($_POST["attemptid"])
} //$conn
?>
if ($_POST["deleteby"] = "attemptid") {
That should be ==. Your code as written will assign "attemptid" to $_POST["deleteby"] and then return the same value... which is always true. So your other else ifs are never even checked.
Also, your code as written is vulnerable to SQL injection. You're already using mysqli; you should strongly consider using prepared statements.

Issue with getting values of checkboxes checked in HTML form in PHP

I have a HTML form that I build using php like this:
<div class="modal-body">
<?php
$getW = "SELECT personID, firstName, lastName FROM person";
$wResult = mysql_query($getW, $database);
print("<form action='actions/editPeopleTask.php'><pre>");
while ($row = mysql_fetch_row($wResult))
{
$personID = $row[0];
$personName = $row[1] . " " . $row[2];
$assignedQ = "SELECT * FROM table WHERE personID = '$personID'";
if (mysql_num_rows(mysql_query($assignedQ, $database)) > 0)
{
print("<input type='checkbox' checked='checked' name='person[]' value=$personID /> $personName<br/><br/>");
}
else
print("<input type='checkbox' name='person[]' id='person' value=$personID /> $personName<br/><br/>");
}
print("<input type='submit'/ name='submit' value='submit'></br></pre></form>")
?>
</div>
There is a loop that runs through this each time to add these inputs to my form. The $personID is the id of the current person that I got from my database and $personName is the name of the person. The line at the top:
if (mysql_num_rows(mysql_query($assignedQ, $database)) > 0)
is just to check if the person already existed in another table, so I can determine if their checkbox should be checked already or not.
The form works as it should, but then (when I submit) I go to another php file and try to get the results like so:
$personList = $_POST['person'];
echo count($personList);
But there is never anything in the list, no matter how many checkboxes I check.
From all the stuff online that I have seen, this should work, but it doesn't.

Categories