Accessing Information from SQL While inside a form - php

I have a Query that looks something like this (I know its vulnerable to sql injection, its just a template):
$db = mysql_connect("host","un", "pw");
mysql_select_db("db", $db);
$sql = "SELECT *"
. " FROM Student" ;
$result = mysql_query($sql);
$students = mysql_fetch_assoc($result);
$numRows = mysql_num_rows($result);
Then I have this form:
<form name="form" id="form" method="post" action="page">
<select name="student" id="student">
<?
for ($i=0;$i<=$numRows;$i++){
echo "<option>" . $students['StudentID'] . "</option>";
}
?>
<option selected="selected">Please select a student</option>
</select>
This should print something like a drop down box with all the values from the table as items. However, I get a drop down box with 6 of the same items, in this case, I get 6 student Id's, but they are all the same ID. I have six students in the db, and I would like to display each of them as an option. What am I doing wrong?
TIA

Have a look at the examples of mysql_fetch_assoc. It will only return one record. In order to get all of them, you have to use it in a loop, e.g.:
$students = array();
while(($student = mysql_fetch_assoc($result))) {
$students[] = student;
}
and later:
<?php foreach($students as $student): ?>
<option><?php echo $student['StudentID']; ?></option>
<?php endforeach; ?>
or with a for loop (but it is not necessary if you don't need a counter):
<?php for($i = 0; $i < numRows; $i++): ?>
<option><?php echo $students[$i]['StudentID']; ?></option>
<?php endfor; ?>
(Note: I use the alternative syntax for control structures which imho is much more readable when mixing HTML and PHP)

Related

Duple select from database in same table but diffent proposes

First option of select must be the name referring to the ID. The remaining select options are the remaining names
<select class="input" name="client_id">
<?php
$sel_client_detail="Select * from client WHERE client_id=".$id."";
$result_detail = mysqli_query($con,$sel_client_detail);
while($new_record_row = mysqli_fetch_assoc($result_detail)) { ?>
<option selected><?php echo $row['nome'];?></option>
<?php };?>
<?php
$sel_client="Select * from client";
$result = mysqli_query($con,$sel_client);
?>
<option>-----------</option>
<?php while($new_record_row = mysqli_fetch_assoc($result)) { ?>
<option><?php echo $new_record_row['nome'];?></option>
<?php };?>
</select>
Output:
<select>
<option selected> Izzi (current ID name)</option>
<option> ____________</option>
<option> Other existing clients</option>
<option> Other existing clients</option>
<option> Other existing clients</option>
<option> Other existing clients</option>
</select>
If you want the user to be first in your option list just run the query once and build the HTML parts in 2 seperate strings. Then once the loop is complete put them together and echo them
<?php
echo '<select class="input" name="client_id">';
$itsme = '';
$others = '<option>-----------</option>';
$sql = "Select * from client";
$result = $con->query($sql);
while($row = $result->fetch_assoc()){
if ( $id == $row['id'] ) {
$itsme = "<option selected='selected'>$new_record_row[nome]</option>";
} else {
$others += "<option>$new_record_row[nome]</option>";
}
}
// put the option tags together in the order you specified
echo $itsme . $others . '</select>';
Here's a different, but more conventional, approach to this common scenario:
Why not just make the chosen ID selected when you get to it in the list? Then it will still show to the user first. It's more efficient than having two separate queries.
Like this:
<select class="input" name="client_id">
<?php
$sel_client="Select * from client";
$result = mysqli_query($con,$sel_client);
?>
<option>-----------</option>
<?php while($new_record_row = mysqli_fetch_assoc($result)) { ?>
<option <?php echo ($new_record_row["client_id"] == $id ? "selected": ""); ?> ><?php echo $new_record_row['nome'];?></option>
<?php };?>
</select>

Unable to display the same data fetched from mysqli database in 2 times [duplicate]

This question already has answers here:
How can I use mysqli_fetch_array() twice?
(4 answers)
Closed last year.
I have fetched an associative array from MySQL database.
When I try to display data using while loop for the first time it behaves normally.
But when I try to use the same while loop 2 times the first one shows the data but the second one is blank.
My code looks as follows
<?php
include 'inc/dbcon.php';
$query = mysqli_query($con, "select * from product");
?>
<select required class="form-control">
<?php
while ($row = mysqli_fetch_assoc($query)) {
?>
<option><?php echo $row['product_name'] ?></option>
<?php
}
?>
</select>
<select required class="form-control">
<?php
while ($row = mysqli_fetch_assoc($query)) {
?>
<option><?php echo $row['product_name'] ?></option>
<?php
}
?>
</select>
And the out put is like this
Once a row is fetched from the $query, that row is completely removed from the $query so trying to fetch that row again will return nothing.
So to reuse the $query, you should instead fetch all rows into a variable. Try this
<?php
include 'inc/dbcon.php';
$query = mysqli_query($con, "select * from product");
$rows = mysqli_fetch_all($query, MYSQLI_ASSOC);
?>
<select required class="form-control">
<?php
foreach ($rows as $row) {
?>
<option><?php echo $row['product_name'] ?></option>
<?php
}
?>
</select>
<select required class="form-control">
<?php
foreach ($rows as $row) {
?>
<option><?php echo $row['product_name'] ?></option>
<?php
}
?>
</select>
?>

Throw select php variable into a form and convert it to a POST variable

I'm trying to use a drop down menu to load data from a select value. I want it passed into a php document in order to use the data that I need. What should I do? Thanks in advance.
This is my code for the select menu:
$sqlz = "SELECT * FROM content_temp1 WHERE user_uname='$uname'";
$resultz = mysql_query($sqlz);
$checkz = mysql_numrows($resultz);
$count = 0;
?>
<select name="ltemp">
<?php
while($count<$checkz){
$selectname=mysql_result($resultz,$count,"temp1_name");
?>
<option value="<?php echo "$selectname";?>"><?php echo $selectname;?></option>
<?php
$count++;
}
?>
</select>
<input type="submit" value="Load Template" class="ufbutton"><br></center>
</form>
and this is my php page
$uname = $_GET['username'];
$loadtemp = $_POST['ltemp'];
header("Location:editing1.php?username=$uname&tempname=$loadtemp");
it seems that you have use " inside " in this line :
<option value="<?php echo \"$selectname\";?>"><?php echo $selectname;?></option>
try this:
$sqlz = "SELECT * FROM content_temp1 WHERE user_uname='$uname'";
$resultz = mysql_query($sqlz);
$checkz = mysql_numrows($resultz);
$count = 0;
?>
<select name="ltemp">
<?php
while($count<$checkz){
$selectname=mysql_result($resultz,$count,"temp1_name");
?>
<option value="<?php echo \"$selectname\";?>"><?php echo $selectname;?></option>
<?php
$count++;
}
?>
</select>
Alternative :
$sqlz = "SELECT * FROM content_temp1 WHERE user_uname='$uname'";
$resultz = mysql_query($sqlz);
?>
<select name="ltemp">
<?php
while ($row = mysql_fetch_array($resultz, MYSQL_ASSOC)) {
$selectname=$row["temp1_name"];
?>
<option value="<?php echo \"$selectname\";?>"><?php echo $selectname;?></option>
<?php } ?>
</select>
Be careful this is ripe for sql injection without validating the input;
SQL Injection with GET

Populate html <select> with array data from mysql in PHP

I can see the query returning results, but I can't seem to be able to put them into a html dropdown box. Also, the dropdown box has just as many entries as the query returns, but THEY ARE ALL WHITE SPACES. HOWEVER, the page source shows correct option values such as
<option value="3 John"></option>
<option value="Jude"></option>
<option value="Revelation"></option>
Can somebody help me out? Why dont they actually show in the dropdown box?
<html>
<?php
//Connect to the database
$mysqli = new mysqli("localhost", "root", "", "bible");
//Return an error if we have a connection issue
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
//Query the database for the results we want
$query = $mysqli->query("select distinct bname as Name from kjv limit 1");
//Create an array of objects for each returned row
while($array[] = $query->fetch_object());
array_pop($array);
//Print out the array results
print_r($array);
?>
<h3>Dropdown Demo Starts Here</h3>
<select name="the_name">
<?php foreach($array as $option) : ?>
<option value="<?php echo $option->Name; ?>"></option>
</select>
<?php endforeach; ?>
Try This
<select name="the_name">
<?php foreach($array as $option) : ?>
<option value="<?php echo $option['Name']; ?>"><?php echo $option['Name']; ?></option>
<?php endforeach; ?>
</select>
After the query is executed use the while loop to add the options to select
$query = $mysqli->query("select distinct bname as Name from kjv limit 1"); ?>
<select>
<?php while($option = $query->fetch_object()){ ?>
<option><?php echo $option->Name; ?></option>
<?php } ?>
</select>
Not sure what the array_pop is doing in the code
AS TIM WAX SAID THIS IS THE SOLUTION
$query = $mysqli->query("select distinct bname as Name from kjv limit 1"); ?>
<select>
<?php while($option = $query->fetch_object()){ ?>
<option><?php echo $option->Name; ?></option>
<?php } ?>
</select>
<select name="the_name">
<?php foreach($array as $option) : ?>
<option value="<?php echo $option->Name; ?>"></option>
<?php endforeach; ?>
</select>
You ended your loop in a way that it also create <select> tag again and again. Change it and try again. I don't know much about .php but it could be a problem in showing your dropdown box.
here is mine .. im a beginner but it works for me,
$query = $mysqli->query("SELECT * FROM `student_type_db`"); //table of student type
echo "<select>";
while($row = $query->fetch_array()){
echo "<option>";
echo $row['student_type'] . " - " . $row['student_description'];
echo "</option>";
}
echo "</select>";
// student type = 1 | student description = regular
// output : 1 - regular

Display Mysql table field values in Select box

I want to display the Mysql table Filed values in selectbox. I tried the following code to display.
But it normally display the specified field values in echo function and not in select box. I don't know where I mistake.
$con = mysql_connect("localhost","root","root");
$db = mysql_select_db("Time_sheet",$con);
$get=mysql_query("SELECT Emp_id FROM Employee");
while($row = mysql_fetch_assoc($get))
{
echo ($row['Emp_id']."<br/>");
}
<html>
<body>
<form>
<select>
<option value = "<?php echo($row['Emp_id'])?>" ><?php echo($row['Emp_id']) ?></option>
</select>
</form>
</body>
</html>
Also the field values must be display in ascending order. How to achieve..
<?php
$con = mysql_connect("localhost","root","root");
$db = mysql_select_db("Time_sheet",$con);
$get=mysql_query("SELECT Emp_id FROM Employee ORDER BY Emp_id ASC");
$option = '';
while($row = mysql_fetch_assoc($get))
{
$option .= '<option value = "'.$row['Emp_id'].'">'.$row['Emp_id'].'</option>';
}
?>
<html>
<body>
<form>
<select>
<?php echo $option; ?>
</select>
</form>
</body>
</html>
PS : On a sidenote, please stop using mysql_* functions. Take a look at this thread for the reasons.
You can easily do it like this
$con = mysql_connect("localhost","root","root");
$db = mysql_select_db("Time_sheet",$con);
$get=mysql_query("SELECT Emp_id FROM Employee");
<html>
<body>
<form>
<select>
<option value="0">Please Select</option>
<?php
while($row = mysql_fetch_assoc($get))
{
?>
<option value = "<?php echo($row['Emp_id'])?>" >
<?php echo($row['Emp_id']) ?>
</option>
<?php
}
?>
</select>
</form>
</body>
</html>
You have to use while loop to display option in select box. try this ...
$con = mysql_connect("localhost","root","root");
$db = mysql_select_db("Time_sheet",$con);
$get=mysql_query("SELECT Emp_id FROM Employee order by Emp_id");
<html>
<body>
<form>
<select>
<?php
while($row = mysql_fetch_assoc($get))
{
?>
<option value="<?php echo $row['Emp_id']; ?>"><?php echo $row['Emp_id']; ?></option>
<?php
}
?>
</select>
</form>
</body>
</html>
<?php
$con = mysql_connect("localhost","root","root");
$db = mysql_select_db("Time_sheet",$con);
$get=mysql_query("SELECT Emp_id FROM Employee");
?>
<html>
<body>
<form>
<select>
<?php
while($row = mysql_fetch_assoc($get)){?>
<option value = "<?php echo($row['Emp_id'])?>" ></option>
<?php } ?>
</select>
</form>
</body>
<?php
$con = mysql_connect("localhost","root","root");
$db = mysql_select_db("Time_sheet",$con);
$res=mysql_query("SELECT Emp_id FROM Employee");
?>
<html>
<body>
<form>
<select>
<?php
while ($row = $res->fetch_assoc())
{
echo '<option value=" '.$row['id'].' "> '.$row['name'].' </option>';
}
?>
</select>
<form>
</body>
</html>
There a few tips to offer that will condense the code block for this task -- too many to just comment under the accepted answer.
Tested Code:
if (!$con = new mysqli("localhost", "root", "root", "Time_sheet")) {
echo "Database Connection Error: " , $con->connect_error; // don't show actual error in "production" stage
} elseif (!$result = $con->query("SELECT Emp_id FROM Employee ORDER BY Emp_id")) {
echo "Syntax Error: " , $con->error; // don't show actual error in "production" stage
} else {
echo "<select>";
foreach ($result as $row) {
echo "<option>{$row['Emp_id']}</option>";
}
echo "</select>";
}
The if line is both declaring $con and checking it for a falsey return value in one step.
Never provide the raw connection or query errors to your users. It is okay during development, but you don't want strangers to have access to critical/informative errors that your server will provide. This is a basic best practice for security.
The elseif line is both declaring $result and checking it for a falsey return value in one step.
The else block will process the zero or more rows of data that were generated as a result of the successful SELECT query.
The mysqli result is "traversable" which means you can iterate it using foreach() and enjoy direct access to the row data via associative keys. PHP Manual Reference Another StackOverflow Post
When writing an array element into a literal string via interpolation, it is good practice (though not always necessary) to wrap the element in curly braces. This will often trigger helpful highlighting in IDEs and ensure that the characters that follow the array are not accidentally coupled to the variable name itself.
You ONLY need to write a value attribute inside of the <option> tag IF the value is different from text between the opening and closing tags (<option>the text in here</option>). Form submissions and javascript implementations will all work the same if you omit the redundant value attribute.
If you DO wish to submit a different value in the select field rather than the text, here is what the syntax can look like:
echo "<option value=\"{$row['Emp_id']}\">{$row['Emp_name']}</option>";
If you want to write a selected attribute on one of the options based on a pre-existing variable (e.g. $selected_id), it can look like this:
echo "<option" , ($row['Emp_id'] == $selected_id ? " selected" : "") , ">{$row['Emp_name']}</option>";
If you wanted to combine the two previous processes, it can look like this:
echo "<option value=\"{$row['Emp_id']}\"" , ($row['Emp_id'] == $selected_id ? " selected" : "") , ">{$row['Emp_name']}</option>";

Categories