I have a problem when I retrieve data from database the result is
How to retrieve the data normally?
This is my codes..
$wewqry = $mysqli->prepare("SELECT itemname from table_item ");
$wewqry->execute();
$wewqry->bind_result($itemname);
$wewqry->store_result();
while ($wewqry->fetch()){
$table = array("itemname" => $itemname);
foreach ($table as $t => $w){
echo '<select name="itemname">';
echo "<option>$w</option>";
echo '</select>';
}
}
You should not create a new <select> each time through the loop, do it once outside the loop:
echo '<select name="itemname">';
while ($wewqry->fetch()) {
echo "<option>$itemname</option>";
}
echo '</select>';
You also don't need to make an array for each row you fetch. Just insert the result variable directly into the echo statement.
Related
I am trying to display html table from a stored procedure using PDO.Resultset contains lot of columns and rows which needs to be exported to an excel.
But I need to get the column names to be on the first row, how can be possible on the below code? Any help ?
$q= $db->prepare( "CALL spalldetails" );
$q->execute();
while ($arrValues = $q->fetch(PDO::FETCH_ASSOC))
{
echo "<tr>";
foreach ($arrValues as $key=>$value)
{
$column_names[]=$key;
?>
<td><?=$value?></td>
<?
}
echo "</tr>";
}
The below code displays the column name, but I want it to be the top row of the table.
echo "<tr>";
foreach ($column_names as $name)
{ ?>
<td>
<?=$name?>
</td>
<?
}
echo "</tr>";
?>
The question has nothing to do with stored procedures, as it's applicable to any data returned from database.
the most convenient way would be to fetch the data first, get the column names from the first row and then print the data.
besides, use of prepare execute is not justified for this query
$data = $db->query( "CALL spalldetails" )->fetchAll(PDO::FETCH_ASSOC);
$column_names = array_keys($data[0]);
here you have your column names before output which you can make using foreach() instead of while()
I would suggest instead of printing the output immediately while processing the through the for loop, you rather create a string to output later. This can be accomplished simply like this: (mind you the below is untested air code, but to show you an example of what I mean)
$q= $db->prepare( "CALL spalldetails" );
$q->execute();
while ($arrValues = $q->fetch(PDO::FETCH_ASSOC))
{
$tablestring .= "<tr>";
foreach ($arrValues as $key=>$value){
$column_names[]=$key;
$tablestring .= "<td>".$value."</td>";
}
$tablestring .= "</tr>";
}
$headstring .= "<tr>";
foreach ($column_names as $name)
{ $headstring .= "<td>".$name."</td>";
}
$headstring .= "</tr>";
echo "<table>".$headstring.$tablestring."</table>";
I need to get the values of the selected select
like the orderno of the changed row
The table looks like this
if I change order no 1002 into sold
$query = mysql_query("select * from orders");
while($row = mysql_fetch_assoc($query))
{
echo '<tr>';
echo '<td>'.$row['orderno'].'</td>';
echo '<td>'.$row['total'].'</td>';
echo '<td>';
if($row['status'] == "sold")
{
echo '<select name = "status[]">';
echo '<option value = "sold" selected>Sold</option>';
echo '<option value = "cancelled">Cancelled</option>';
echo '</select>';
}
else
{
echo '<select name = "status[]">';
echo '<option value = "sold">Sold</option>';
echo '<option value = "cancelled" selected>Cancelled</option>';
echo '</select>';
}
echo '</td>
echo </tr>';
}
if(isset($_POST['status']))
{
//sample only
echo "You change orderno ".$orderno_here." with the
total of ".$total_of_order." into ".$selected_status_of_orderno_here;
}
There are many records in the table and the selects are the same
how do I get the values of the selected select
Following your question, whatever i understood, according to that i am supposing you are getting data from form like tags in your page. If that is the case, you know that which value is changed to be reflected in db. So you can get that selected select from this.
you can check the change through this code:
if(isset($_POST['element'])){
//if this block executed, the <element> named element is changed
}
ignore this answer if this is not the case you are using in your code..
This question already has answers here:
create dropdown menu on each loop assign database value to option element
(2 answers)
Closed 9 years ago.
Im working on a page for a sports team where the coach can select his team. What im trying to do is:
1) Print different positions
2) Assign next to position name, players who are ONLY relevant to the
position. (i.e if the positions name is flanker only flankers should
be displayed in the drop-down menu)
My logic for the above problem is:
Assign position names to array called $position Loop over array
querying database, with position having a different value after each loop.
Selected players that match the position gets assigned to an
array called $playerName
Print the $position variable
Create dropdown menu for each position
assign value
from $playername array to the option element in the drop down
menu.
Now there should be different positions with dropdown menus,
next to them, containing player names relevant to position.
//create position array
$position = array(
"THP",
"HKR",
"LH",
"LK4",
"LK5",
"FLH"
);
echo '<form name="slectPlayers" method="post">';
foreach ($position as $pposition) {
$result = mysql_query("SELECT `player_id`,`name`,`surname` FROM `player_info` WHERE `position` = '$pposition'") or die(mysql_error());
while ($row = mysql_fetch_array($result)) { //create arrays
$id[] = $row['player_id'];
$playerName[] = $row['name'];
$playerLastName[] = $row['surname'];
// print position and open select element
foreach ($position as $playerPosition) {
print $playerPosition;
echo '<select>';
foreach ($playerName as $name) { //assign playername to position element
echo '<option>' . $name;
'</option>';
echo '</select>';
echo '<br />';
} //close assign player nae to position loop
} //end print position and open select loop
} //end while loop
} //end opening for each loop
echo '</form>';
unfortunately for me either my logic is wrong or my code is incorrect. This is the ouput I get: (Note only the name Tendai is displayed in all dropdown meus no other names appear)
If been struggling with this one all morning if someone could point me in the right direction it would be greatly appreciated
(note to modirators the picure above does not contain real names and is only a fictional database)
You can do it like this. the logic is something different
function get_players_by_position($position)
{
$query = "SELECT
`player_id`,
`name`,
`surname`
FROM `player_info`
WHERE `position` = $position
ORDER BY name ";
$result = mysql_query($query);
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[] = $row;
}
return $data;
}
foreach($position as $pposition){
$data = get_players_by_position($pposition);
echo $pposition;
echo '<select>';
foreach($data as $row){
echo '<option '.$row['id'].'>' . $row['name'].'</option>';
}
echo '</select>';
echo '<br />';
unset($data);
}
In your original code, you could remove the two foreach loops in the while loop. Use $pposition in place of $playerPosition and your code should work as expected. Here's your code, with my suggested changes, in your procedural style:
$position = array(
"THP",
"HKR",
"LH",
"LK4",
"LK5",
"FLH"
);
echo '<form name="selectPlayers" method="post">';
foreach ($position as $pposition) {
$result = mysql_query("SELECT `player_id`,`name`,`surname` FROM `player_info`
WHERE `position` = '$pposition'") or die(mysql_error());
echo '<select name="'. $pposition . '">';
while ($row = mysql_fetch_array($result)) {
print $pposition;
echo '<option value="' . $row['player_id'] . '">'.
$row['name'] .' '. $row['surname'].
'</option>';
} //end while loop
echo '</select>';
echo '<br />';
} //end opening for each loop
echo '</form>';
I have a web site that contains an HTML form, in this form I have a dropdownlist with list of agents that works in the company, I want to fetch data from MySQL database to this dropdownlist so when you add a new agent his name will appear as an option in the drop down list.
<select name="agent" id="agent">
</select>
To do this you want to loop through each row of your query results and use this info for each of your drop down's options. You should be able to adjust the code below fairly easily to meet your needs.
// Assume $db is a PDO object
$query = $db->query("YOUR QUERY HERE"); // Run your query
echo '<select name="DROP DOWN NAME">'; // Open your drop down box
// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.htmlspecialchars($row['something']).'">'.htmlspecialchars($row['something']).'</option>';
}
echo '</select>';// Close your drop down box
# here database details
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');
$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);
echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";
}
echo "</select>";
# here username is the column of my table(userregistration)
# it works perfectly
You need to fetch all rows from the database and then iterate over them, displaying a new <option> for each one of them. Pay attention to avoid XSS by using htmlspecialchars().
$pdo = new \PDO("mysql:host=localhost;dbname=test;charset=utf8mb4", 'user', 'password', [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);
// Select all values from the table Agents
$stmt = $pdo->prepare("SELECT Id, Name FROM Agents");
$stmt->execute();
echo '<select name="agent" id="agent">';
// For each row from the DB display a new <option>
foreach ($stmt as $row) {
// value attribute is optional if the value and the text is the same
echo '<option value="'.htmlspecialchars($row['Id']).'">';
echo htmlspecialchars($row['Name']); // The text to be displayed to the user
echo '</option>';
}
echo '</select>';
If you want to preselect one of the values, then you need to apply selected attribute to one of the <options>:
$selected = 'Somebody';
echo '<select name="agent" id="agent">';
foreach ($stmt as $row) {
if ($selected === $row['Name']) {
echo '<option value="'.htmlspecialchars($row['Id']).'" selected >';
} else {
echo '<option value="'.htmlspecialchars($row['Id']).'">';
}
echo htmlspecialchars($row['Name']);
echo '</option>';
}
echo '</select>';
What you are asking is pretty straight forward
execute query against your db to get resultset or use API to get the resultset
loop through the resultset or simply the result using php
In each iteration simply format the output as an element
the following refernce should help
HTML option tag
Getting Datafrom MySQL database
hope this helps :)
I am trying to populate a selection box (dropdown) from a mysql table in php, but I get blank results, Can someone look in my code and tell me what is wrong?
I need to populate the select with the dates available from my sql query, so they show up as seletion options....
<?php
echo JText::_('Please select the date:');
$database= &JFactory::getDBO();
$database->setQuery('SELECT training_id,training,trainingDate FROM training');
$result = $database->loadObjectList();
echo '<select name="whatever">';
foreach ($result as $row) {
echo '<option value="'.$row->training_id.'" />';
}
echo '</select>';
?>
You assign an option value, but you don't provide human-readable option text:
echo '<select name="whatever">';
foreach ($result as $row) {
<!-- here we go -->
echo '<option value="'.$row->training_id.'">'.$row->training.'</option>'; // always close options!!!
}
echo '</select>';
echo '<option value="'.$row->training_id.'">'.$row->trainingDate.'</option>';
If that doesn't work then your $row->training_id isn't set and so you'll need to debug that (e.g. doing a print_r($row) just before that line to see what is inside the $row object)
Try this:
while($row = mysql_fetch_object($result)) {
instead of this:
foreach($result as $row) {