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>";
}
}
Related
I'm working on a project for a class and I'm having trouble passing on a variable from a Chosen selector. I am passing on the $inst variable just fine, but the $focus variable is giving me this:
Undefined index: chzn2 in C:\xampp\htdocs\phptest\results.php on line 20.
fyi: I have allowed for null in the database
Here is the code for the selectors.
$sql = "SELECT institutionName, instID FROM institutions";
$dropq = mysqli_query($conn, $sql);
echo "<select data-placeholder='Select an Institution' name='chzn1' class='chzn-select' standard='true' style='width:250px;'>";
while ($row = mysqli_fetch_array($dropq)) {
echo "<option></option><option value='" . $row['instID'] . "'>" . $row['institutionName'] . "</option>";
}
echo "</select>";
$sql1 = "SELECT orgFocus FROM communityOrgs";
$dropq = mysqli_query($conn, $sql1);
echo "<select data-placeholder='Select Focus Area' name='chzn2' class='chzn-select' multiple='true' style='width:250px;'>";
while ($row1 = mysqli_fetch_array($dropq)) {
echo "<option></option>
<option value='" . $row1['orgFocus'] . "'>" . $row1['orgFocus'] . "</option>";
}
echo "</select>";
Here is the code for the results
if (isset($_POST['submit-search'])) {
if(empty($_POST['chzn1']) && empty($_POST['chzn2'])){
echo "Please enter at least one value!";
}
else if(!empty($_POST['chzn1']) || !empty($_POST['chzn2'])) {
// Grabbing variables from User Inputs
$inst = $_POST['chzn1'];
$focus = $_POST['chzn2'];
$query = "SELECT * FROM partnerships WHERE instID = '$inst' OR orgFocus = '$focus'";
$result = mysqli_query($conn, $query);
$queryResults = mysqli_num_rows($result);
if($queryResults > 0) {
while ($row = mysqli_fetch_array($result)) {
echo "<div class='results-container'>
<h3>".$row['instName']."</h3>
<p>".$row['orgName']."</p>
<p>".$row['orgFocus']."</p>
</div>";
;}
}
As the error suggests:
Undefined index: chzn2
and according to your logic one out of the two values can be passed that leaves the ability for one to be unset so an error is thrown - as it should.
You need to do a check to see if either one of the $_POST keys exist separately and set their values respectively, either to what was passed or null.
Example
<?php
$chzn1 = null;
$chzn2 = null;
if (!empty($_POST['chzn1']))
$chzn1 = $_POST['chzn1'];
if (!empty($_POST['chzn2']))
$chzn1 = $_POST['chzn2'];
?>
Now they will both have default value so the error won't be thrown.
Note: Seeing as you are using mysqli_* make use of prepared statements.
Update #1
Maybe due to a formatting error but you also have a floating semicolon ;:
;}
Select and option is not separated. As you are echoing separate make it combine.
$row = "<select data-placeholder='Select Focus Area' name='chzn2' class='chzn-select' multiple='true' style='width:250px;'>";
while ($row1 = mysqli_fetch_array($dropq)) {
$row .= "<option></option>
<option value='" . $row1['orgFocus'] . "'>" . $row1['orgFocus'] . "</option>";
}
$row .= "</select>";
echo $row;
Same for other select tag
I'm trying to compose an estimate formula, and I stucked with value of dropdown list populated by MySQL.
The idea of this formula is when a user select a service from dropdown list and put the quantity in textfield the program will compute the price for the service.
The value of the prize is selected from MySQL table.
$query="SELECT $con_tent FROM services WHERE $id;
$con_tent= 'price'. '*'. $qunatity
But I don't know how to get the value from dropdwon list.
Probably with Ajax but still don't know how.
I solved this by modyfing code from http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html
<?php
require_once 'login.php';
$db_server = mysql_connect($db_hostname, $db_user, $db_password);
mysql_select_db($db_database) or die("unable to select database:" . mysql_error());
echo "<form action=licz.php method='post'>";
echo " <label for=\"select\"><select name=\"\" value=\"Select\" size=\"1\">";
$query = "SELECT * FROM uslugi ORDER BY id ASC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
global $ff;
$ajdi = $row['id'];
$nazwa = $row['nazwa'];
$options.= "<option value=\"$ajdi\" name=\"oko\">" . $nazwa . $ajdi;
}
echo "<option>";
echo $options;
echo "</option></select>";
echo " <input type=\"submit\" name=\"Submit\" value=\"Submit\">";
echo "</form>";
function wybor() {
global $id;
global $con_tent;
$var = 'price' . '*';
$quantity = 3;
//quantity will by from textfield but now it constant
$id_value = 1;
// here i need to make it dynamic
$id = "id={$id_value}";
$con_tent = $var . $quantity;
}
echo wybor();
$query = "SELECT $con_tent FROM services WHERE $id";
//query
if (!$query) Die("Unable to query: " . mysql_error());
$result = mysql_query($query);
if (!$result) Die("Unable to query: " . mysql_error());
$rows = mysql_num_rows($result);
for ($a = 0; $a < $rows; ++$a) {
$row = mysql_fetch_row($result);
echo $row[0] . " ";
echo $row[1] . " ";
echo $row[2] . " ";
echo $row[3] . "$br";
}
?>
You should apply ajax call to get value for database when there is a change in select box through calling a function on onchange event of javascript.
Read More for jquery AJAX
http://www.sitepoint.com/ajax-jquery/
http://www.tutorialspoint.com/jquery/jquery-ajax.htm
I'm trying to get a drop down menu to keep its selected value when the user hits submit, but it fails due to errors on the form.
I have a while loop returning values from a database to build the options for the drop down, but how do I echo "selected" on the right option?
I have tried if($district == $row["name"]) { echo "selected";} as you see below, but it doesn't work.
<?php
$result = mysql_query("SELECT dist.name FROM districts AS dist JOIN int_bd AS ibd ON dist.id = ibd.districts_id WHERE banners_id = 6 GROUP BY dist.id ORDER BY dist.id ASC", $connection);
if (!result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo '<option value="{$row["name"]}"'; if($district == $row["name"]) { echo "selected";} ; echo '>' . $row["name"] . "</option>";
}
?>
Sorry for the delay. None of the suggested answers worked for me. Any other ideas?
Can you try this,
<?php
$result = mysql_query("SELECT dist.name FROM districts AS dist JOIN int_bd AS ibd ON dist.id = ibd.districts_id WHERE banners_id = 6 GROUP BY dist.id ORDER BY dist.id ASC", $connection);
if (!result) {
die("Database query failed: " . mysql_error());
}
$district = $_REQUEST['name']; // You need pass the value you have been submitted
while ($row = mysql_fetch_array($result)) {
$selected ="";
if(trim($district) == trim($row["name"])) { $selected = "selected";}
echo '<option value="{$row["name"]}" '.$selected.' >' . $row["name"] . "</option>";
}
?>
Try this..
if($district == $row["name"])
{
echo "<option value='$district' selected>$district</option>";
}
I just found the answer. This is what I did:
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row["name"] . '"';
if($row["name"] == $district) { echo 'selected';} ;
echo '>' . $row["name"] . '</option>';
}
It seems to have been this line
echo '<option value="{$row["name"]}"';
that was causing the problem.
I have a form I'm using to send multiple fields with a similar name but using square brackets to send them as an array with the key being 'id'. I am able to loop through successfully using a foreach loop but my insert query fails to make any changes in the db.any clues as to why?
here is the code from the form:
$artist = mysql_fetch_array($allartists);
$allmusic = get_music_for_artist($artist_id);
$id = $music['id'];
while ($music = mysql_fetch_array($allmusic)) {
echo "<td class=\"td20 tdblue\">
<input name=\"song_title[" . $id . "]\" type=\"text\" value=\"" . $music['song_title'] . "\" />
</td>";
}
and here is the code on my form processor
foreach ($_POST['song_title'] as $id => $song) {
$query = "UPDATE music SET
song_title = '{$song}'
WHERE id = $id ";
if (mysql_query($query, $connection)) {
//Success
header("Location: yourmusic.php?pid=3");
exit;
} else {
//Display error message
echo "update did not succeed";
echo "<p>" . mysql_error() . "</p>";
}
}
Try this.
Also watch for security http://www.phptherightway.com/#data_filtering
foreach ($_POST['song_title'] as $id => $song) {
$id = (int) $id;
$song = mysql_real_escape_string($song);
$query = "UPDATE music SET
song_title = '$song'
WHERE id = $id LIMIT 1;";
if (mysql_query($query, $connection)) {
//Success
header("Location: yourmusic.php?pid=3");
exit;
} else {
//Display error message
echo "update did not succeed";
echo "<p>" . mysql_error() . "</p>";
}
}
I am making a login page that checks for matching values in a database if the SELECT query returns a matching row with username and password then it will return a row count of 1. The way I have it coded right now when I echo the variable that stores the row count it will echo 26 for some reason and I'm not to sure why.
Would someone explain if I am doing something wrong or if this is normal behavior and where that value is coming from?
function checkLogin($conn,$myusername,$mypassword,$row,$row1){
try {
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql)) {
if($results->fetchColumn() > 0) {
$sql = "SELECT * FROM CLL_users WHERE user_name = 'user' AND password = 'XXXXX'";
foreach ($conn->query($sql) as $row)
{
$rowCount = count($row);
echo $rowCount;
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
}
echo $count;
}
else {
print "NO ROWS";
}
}
} catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
}
Your code, $rowCount = count($row);, is counting the columns in the current row - not the number of rows returned by the query.
On the same note, you are echoing a second count related variable, $count, but you neither declare-it nor increment it in your code. It looks like this one is the one that's supposed to be counting the number of rows you loop through. If this is true, you should set it as $count = 0; before the loop and use $count++; within it:
$count = 0;
foreach ($conn->query($sql) as $row) {
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
$count++;
}
echo $count;
Also, you're currently using PDO's rowCount prior to selecting a user, and you're using it properly. You could just store that result into a variable and use it to tell how many rows you are receiving:
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql)) {
$numRows = $results->fetchColumn();
if($numRows > 0) {
... rest of your code ....
function checkLogin($conn,$myusername,$mypassword,$row,$row1)
{
try
{
$sql = "SELECT COUNT(*) FROM CLL_users WHERE user_name = 'user' AND password = 'XXXX'";
if ($results = $conn->query($sql))
{
$count = $results->fetchColumn();
echo "$count\n";
if($count > 0)
{
$sql = "SELECT * FROM CLL_users WHERE user_name = 'user' AND password = 'XXXXX'";
foreach ($conn->query($sql) as $row)
{
print ("Username: " . $row['user_name'] . "<br>");
print ("Username: " . $row['password'] . "<br>");
}
}
else
{
print "NO ROWS";
}
}
}
catch (PDOException $e)
{
echo 'Connection failed: ' . $e->getMessage();
}
}