Can't get option value from form - php

I can't get the option value from my form to pass it to my action codes.
Form :
<select required name ="class" class="form-control">
<option value="NULL">-select class-</option>
<?php
$link2 = query("select * from td_class");
while ($list = mysql_fetch_array($link2)) {
?>
<option value="<?php echo $list['class'] ?>"><?php echo $list['class']; ?></option>
<?php } ?>
<option value="Alumni">Alumni</option>
</select>
I wanted to use it to check the class capacity in my class table, if the class is at full capacity it will throw an error otherwise the student data will be successfully added. However, my action codes seems to unable to get the given class input and when I submit the button to add student data it will always throw an error saying that the class is full even though it's not full yet. Below is my action codes, what I have done so far :
if ($hal == 'managestudent') {
$name = $_POST['name'];
$image = $_FILES['image'];
$class = $_POST['class'];
$id = $_GET['id'];
if ($aksi == 'addstudent') {
$student = query("select name, count(name) from td_student where class='$class' ");
$student2 = mysql_fetch_array($student);
$capacity = query("select capacity from td_class where class='$class'");
$cap = mysql_fetch_array($capacity);
if (($student2) >= ($cap )) {
echo"<script> alert ('the class is full'); "
. "history.back();" . "</script>";
} else {
if (empty($image['tmp_name'])) {
echo "Without image<br>";
$sql = query("insert into td_student (name,class) values ('$name','$class)");
} else {
echo "With image<br>";
$namafile = uploadBerkas($image);
$sql = query("insert into td_student (name,class,image) values ('$name','$class,'$namafile')");
}
if ($sql == TRUE) {
echo "SQL True<br>";
echo"<script> alert('student data is added'); "
. "window.location='datasiswa.php';"
. "</script>";
} else {
echo "Sql Error " . mysql_error() . " ";
echo"<script> alert ('Error'); "
. "history.back();" . "</script>";
}
}
}
}
Thankyou for the helps.

Your issue is that mysql_fetch_array() Returns an array ..., not a string/value.
So when you do
if (($student2) >= ($cap ))
It is always returning false (the class if full) as it comparing 2 arrays, ie.
if((array(name, count(name)) >= (array(capacity)))
and not 2 values, ie.
if((count(name)) >= (capacity))
What you need to do is use the column name to get the actual value to evaluate, ie. $student2["count(name)"]/$cap["capacity"]
$student = query("select name, count(name) from td_student where class='$class' ");
$student2 = mysql_fetch_array($student);
$capacity = query("select capacity from td_class where class='$class'");
$cap = mysql_fetch_array($capacity);
if (($student2["count(name)"]) >= ($cap["capacity"])) {

Related

Allow only 1 POST of each dropdown value in PHP form

I have a simple PHP form to insert "models" (in dorpdown) with a price.
The thing I want to do is that you can only post model 1 once and model 2 once etc..
So if you choose model 1 in the dropdown and post it and try it again that it doesn't allow you because you already posted model 1.
sorry for my bad English
<select name="model">
<?
$modellen[1]= "Model 1";
$modellen[2]= "Model 2";
$modellen[3]= "Model 3";
foreach ($modellen as $key => $value)
{
echo "<option value='".$key."''>".$value."</option>";
}
?>
</select>
if(isset($_POST['toevoegen']))
{
$prijs = Safesql($_POST['prijs']);
$moment = date("Y-m-d h:i:sa");
$kiesmodel = Safesql($_POST['model']);
if(!$mysqli->query("INSERT INTO prijzen (prijs, created, model) VALUES (".$prijs.",'".$moment."' , '".$kiesmodel."')")) {echo $mysqli->error;}
else{ echo "het toevoegen is gelukt";}
Laden(0);
}
//show records from database
if ($query = $mysqli->query("SELECT * FROM prijzen")) { echo $mysqli->error;}
if ($query->num_rows >= 1)
{
while($row = $query->fetch_assoc())
{
?><tr><td><form action="index.php" method="post">
<? echo "Model" . " " . $row['model']; ?><img src="delete.png">
<img src="edit.png"><?
echo " prijs:" . $row['prijs']. "<br>" ."";?><?
}
}
try add validation before insert,
if(isset($_POST['toevoegen']))
{
$prijs = Safesql($_POST['prijs']);
$moment = date("Y-m-d h:i:sa");
$kiesmodel = Safesql($_POST['model']);
// validation
$sql = "SELECT * FROM prijzen WHERE model = '$kiesmodel'";
$query = $mysqli->query($sql);
$row = $query->fetch_assoc();
if (count($row) >= 1) {
echo "<script>alert('You already add this model')</script>";
}else{
if(!$mysqli->query("INSERT INTO prijzen (prijs, created, model) VALUES (".$prijs.",'".$moment."' , '".$kiesmodel."')")) {echo $mysqli->error;}
else{ echo "het toevoegen is gelukt";}
Laden(0);
}
}
may it can help you

Getting all EmployeeID's in dropdown list from mysql database?

In my case, I am getting only the EmployeeId which i have registered latest and not all the employeeId's from the table in database.
Code :
public function getEmployeeId() {
if (!isset($_SESSION["email"]) || !isset($_SESSION["passwrd"])) {
header("Location:index.php");
// Cannot Access this page without Login.
}
if (empty($_POST)) {
$query = mysqli_query($this->connection, "SELECT EmployeeId FROM employeeprofile") or die("Query execution failed: " . mysqli_error());
**while ($row = $query->fetch_assoc()) {**
$id = $row["EmployeeId"];
$_SESSION["id"] = $id;
}
}
}
i am using this session value in tag in my html form.
<select name="EmployeeId" required autofocus class='form-control'>
<option value=""> ----Select----</option>
<?php
if (isset($_SESSION["id"])) {
echo "<option value = " . $_SESSION["id"] . ">" . $_SESSION["id"] . "</option>";
}
?>
</select>
Someone suggested me to check the array , but i am confused.
You're currently overwriting the ID on each iteration. You need to store them in an array in which you append each ID instead:
// Make this session item an array
$_SESSION['id'] = [];
$query = mysqli_query($this->connection, "SELECT EmployeeId FROM employeeprofile") or die("Query execution failed: " . mysqli_error());
while ($row = $query->fetch_assoc()) {
// Push the id to the array
$_SESSION['id'][] = $row["EmployeeId"];
}
Now you need to iterate through the array with the ID's when printing the options:
if (isset($_SESSION["id"])) {
foreach ($_SESSION['id'] as $id) {
echo "<option value='$id'>$id</option>";
}
}
This should work, as long as you have session_start() in the top of your scripts.
I would probably not use sessions to store results like this, but I don't know enough of your code to be able to give you a good solution.
i thik the problem is that you should retrieve data in array from query and you can apply foreach loop to print the employee.
first get all the employee
$query = mysqli_query($this->connection, "SELECT EmployeeId FROM employeeprofile") or die("Query execution failed: " . mysqli_error());
$result = query($query);
now print the retrieved employee in option field
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<option value=" . $row["id"] . ">" . $row["id"] . "</option>"
}
} else {
echo "<option value="">No result found.</option>"
}
For me wouldn't advise to use sessioning, then to populate your select input, you do the below code, this is just a method of doing this anyway
public function getEmployeeId() {
if (!isset($_SESSION["email"]) || !isset($_SESSION["passwrd"])) {
header("Location:index.php");
// Cannot Access this page without Login.
}
$ids = array();
if (empty($_POST)) {
$query = mysqli_query($this->connection, "SELECT EmployeeId FROM employeeprofile") or die("Query execution failed: " . mysqli_error());
while($row = mysqli_fetch_array($query)){
$ids[] = $row['EmployeeId']; //we populate our array here
}
}
return $ids; //return the array here
}
from your html you do this
<select>
<option value="">Select</option>
<?php
$ids = getEmployeeId();
for($i=0;$i<count($ids); $i++){
?>
<option value="<?php echo $ids[$i];?>"><?php echo $ids[$i];?></option>
<?php }?>
</select>
It is because, you are putting only last value of array in $_SESSION["id"] variable
Change $_SESSION["id"] = $id; to $_SESSION["id"][] = $id;
and to print
if (isset($_SESSION["id"])) {
foreach($_SESSION["id"] as $v){
echo "<option value ='" . $v . "'>" . $v."</option>";
}
}

How to show average from mysql

How to show the average of a column in mysql?
Below is my code which i have tried so far :
<?php
if (isset($_GET["age"]));
$age = ($_GET["age"]);
include($_SERVER["DOCUMENT_ROOT"] . "/includes/config.php");
// Input
$sql = "SELECT AVG(column_name) FROM table_name";
// Check age
if ($age > 99 or $age < 5) {
echo ("We only store data of people between the age of 5 and 99.");
if (!mysqli_query($conn, $sql)) {
die('Error: ' . ((is_object($GLOBALS["___mysqli_ston"])) ? mysqli_error($GLOBALS["___mysqli_ston"]) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)));
}
}
else {
echo ("We got it!");
}
// Close connection
((is_null($___mysqli_res = mysqli_close($conn))) ? false : $___mysqli_res);
die();
?>
But how to exactly define a variable to the result of the AVG with a maximum of 2 decimals?
I want to used and show it into another file (so I will include this one).
What I have right now
<?php
if (isset($_GET["age"]));
$age = ($_GET["age"]);
include($_SERVER["DOCUMENT_ROOT"] . "/3/includes/config.php");
include($_SERVER["DOCUMENT_ROOT"] . "/3/includes/opendb.php");
// My own created code
$sql = $conn->query("SELECT ROUND(AVG(price AS FLOAT), 2) FROM data WHERE age= '$age'");
$data = $sql->mysqli_fetch_assoc();
$avg_data = $data['price'];
echo $avg_data;
// This below is from an other post but don't know how it works and if it is good.
$ratings = $conn->query("SELECT AVG(price) avg_rating FROM data form_id = '" . $age . "'");
$data2 = $ratings->mysqli_fetch_assoc();
$avg_rating = $data2['avg_rating'];
echo $avg_rating;
die();
?>
Use Like This For Getting Average witth two decimal points.
$sql = "SELECT ROUND(AVG(column_name AS FLOAT), 2) FROM table_name";
How I fixed it:
<?php
if (isset($_GET["age"])) {
$age = ($_GET["age"]);
include($_SERVER["DOCUMENT_ROOT"] . "/3/includes/config.php");
$con=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if (mysqli_connect_errno($con)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT AVG(price) FROM data WHERE age= '$age'") or die("Error: " . mysqli_error($con));
while($row = mysqli_fetch_array($result)) {
echo $row['AVG(price)'];
echo number_format($row['AVG(price)'], 2);
}
die();
}
else {
echo 'Something went wrong, try again.';
}
?>
$sql = 'SELECT *, ROUND(AVG(column_name), 2) AS avg_value FROM table_name';
avg_value will store the rounded + average value and add * if need to get all the column.

Only display a specific category from a database (PHP/SQL)

From a dropdown menu a user can choose: view all, athletic, dress, or sandals. I am creating a function that if the user chooses athletic--only the Product Type 'Athletic', only athletic items from the database will be shown.
Right now, because how my code is written, if the user selects 'Athletic' they will see athletic items, but also all other products in the database because the function showAllProducts was called.
I'm not sure how to write, that if a user selects a specific product type, only that product type will be shown.
if (isset($_SESSION['valid_user']))
{
//echo "I am in the if statement of the session";
echo 'You are logged in as: '.$_SESSION['valid_user'].' <br />';
showAllProducts();
} else {
echo "I am not setting the session variable";
//die;
}
$userCat = getUserCategory();
orderByCategory($userCat);
//function athleticCategory ---------------------------------------------
function athleticCategory() {
echo "I am in the athletic function" . "<br/>";
$con = getConnection();
$sqlQuery = "SELECT * from Products
WHERE ProductType='Athletic'";
// Execute Query -----------------------------
$result = mysqli_query($con, $sqlQuery);
if(!$result) {
echo "Cannot do query" . "<br/>";
exit;
}
$row = mysqli_fetch_row($result);
$count = $row[0];
if ($count > 0) {
echo "Query works" . "<br/>";
} else {
echo "Query doesn't work" ."<br/>";
}
// Display Results -----------------------------
$num_results = mysqli_num_rows($result);
for ($i=0; $i<$num_results; $i++) {
$row = mysqli_fetch_assoc ($result);
// print_r($row);
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['Image']).'" />';
echo "Price: " . stripslashes($row['Price']);
}
}
Dropdown Menu
<form action="register_script.php" name="frm" method="post">
<select name="category" id="category">
<option value="viewall">View All</option>
<option value="dress">Dress</option>
<option value="athletic">Athletic</option>
<option value="sandals">Sandals</option>
</select>
<input type="submit" value="Go" />
</form>
Edited Code:
$sqlQuery = "SELECT * from Products";
if($pUserCat == "athletic") {
$sqlQuery = "SELECT * from Products
WHERE ProductType='athletic'";
} elseif ($pUserCat == "dress") {
$sqlQuery = "SELECT * from Products
WHERE ProductType='dress'";
} elseif ($pUserCat == "sandals") {
$sqlQuery = "SELECT * from Products
WHERE ProductType='sandals'";
} elseif ($pUserCat == "viewall") {
$sqlQuery = "SELECT * from Products";
}
make a function , that accept one parameter ie category name and use default hint as 0
function categoryList($cat=false){
if($cat)
$sqlQuery = "SELECT * from Products
WHERE ProductType={$cat}";
else
$sqlQuery = "SELECT * from Products";
//do other stuff of Reading option
}
Set your 'View All' form option like this:
<option value="">View All</option>
You can use it as it is.
if (isset($_POST['category']))
$category = $_POST['category'];
$sqlQuery = "SELECT * from Products";
if ( ! empty($category)) {
if (get_magic_quotes_gpc()) {
$category = stripslashes($category);
}
if ( ! is_numeric($category)) {
$category = "'" . mysql_real_escape_string($category) . "'";
}
$sqlQuery .= " WHERE ProductType='{$category}'";
}
It has basic security features so people can't inject malicious SQL into your script.
If you call that function without any category, it will be assumed you want to show all values.
You dont need to check if for each and every single case and then write the sqlQuery according to that, as long as you use the same <option value="xxx"> as the categories are called in your db.

Checking querystring values in PHP

http://localhost/?area=characters&name=Michal+Stroganof
$result = mysql_query("SELECT * from players WHERE name = '$_GET[name]'");
while ($row = mysql_fetch_assoc($result)) {
echo "Name: " .$row['name']. "<br>";
echo "Level: " .$row['level']. "<br>";
}
This is all code of my characters.php
If the get variable "name" is not included in the URL i want to show a search form that searches the table players. How would I do this?
Do you mean just to change your SQL string like so?
$sql = 'SELECT * from players';
if (isset($_GET['name'])) {
$safename = mysql_real_escape_string($_GET['name']);
$sql .= " WHERE name='$safename'";
}
$result = mysql_query($sql);
Be sure to sanitize your SQL!
Use isset():
if (isset($_GET['name'])) {
// your above code
} else {
// display form
}
Quick and dirty:
<?php
if (!isset($_GET['name']))
{
echo '<form action="'. $_SERVER['PHP_SELF'] .'" method="GET">'
.'<input type="text" name="name" />'
.'</form>';
}
else
{
// your current code that queries your database here
}
?>

Categories