Using MySQL results array more than once [duplicate] - php

This question already has answers here:
Get all mysql selected rows into an array
(6 answers)
Closed 9 years ago.
I have the following code in my page
<?php
$dbc = mysql_connect();
$db = mysql_select_db();
$results= mysql_query("SELECT * FROM tbl_teams");
?>
<div class="datagrid"><table>
<thead><tr><th>header</th><th>header</th><th>header</th></tr></thead>
<tbody>
<tr>
<td>
<select name="game1_team1"><option value="0">Choose Team 1</OPTION><?php while($row = mysql_fetch_array($results)) {echo '<option value="'.$row['team_ID'].'">'. $row['team_name'].'</option>';}?></select>
</td>
<td>Vs.</td>
<td>
<select name="game1_team2"><option value="0">Choose Team 2</OPTION><?php while($row = mysql_fetch_array($results)) {echo '<option value="'.$row['team_ID'].'">'. $row['team_name'].'</option>';}?></select>
</td>
</tr>
The code shows the names of football teams from the MySQL table in dropdown game1_team1 but not in game1_team2; it's as though I can't use the same query twice. How do I remedy this? I'd like to use the same values for 60 identical drop downs on the page.
Can I store the values into an array and resuse them in each dropdown?

NOTE: The mysql_* function family is deprecated!
What does that mean? It means you should stop using it today. Old code should be updated as time and budget allow, but you should never, EVER write a new line of code that involves these functions
Another note: it is bad practice to use SELECT *... -- explicitly name the columns you are going to use in your query. That way, if the table structure changes, you can detect that because your query will fail, and react accordingly (in code). This is part of a broader concept known as defensive coding.
On to the problem at hand!
You can use PDO to fetch an array of results out of the database. You can then use that array as many times as you'd like!
// simple sample for connecting with PDO
$host="my.host.name"; // Host name
$username="my_user_name"; // username
$password="my password"; // password
$db_name="my_database_name"; // Database name
$pdo = new PDO('mysql:host='.$host.';dbname='.$db_name, $username, $password);
// actually do the query
$statement= $pdo->prepare('
SELECT
time_ID,
team_name
FROM
`tbl_teams`
');
$statement->execute();
// get an array with all the results
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
After that, you can loop the array to make a set of options, or do anything else with the data. For example:
$options = array();
foreach ($results as $one_result){
$options[] = '<option value="'.$one_result['team_ID'].'">'.$one_result['team_name'].'</option>';
}
print '<select name="someSelectElement">'.implode('', $options).'</select>';
Documentation
Deprecation notice for mysql_* functions - http://www.php.net/manual/en/function.mysql-query.php
PHP PDO - http://php.net/manual/en/book.pdo.php
PHP mysqli - http://php.net/manual/en/book.mysqli.php

Using PDO you can easily fetch your results into an array, besides, the mysql_* functions are deprecated.
<?php
$db = new PDO( ... );
$stmt = $db->prepare("SELECT * FROM tbl_teams");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<div class="datagrid">
<table>
<thead><tr><th>header</th><th>header</th><th>header</th></tr></thead>
<tbody>
<tr>
<td>
<select name="game1_team1">
<option value="0">Choose Team 1</OPTION>
<?php
foreach($results as $team) {
echo "<option value='{$team['team_ID']}'>{$team['team_name']}</option>";
}
?>
</select>
</td>
<td>Vs.</td>
<td>
<select name="game1_team2">
<option value="0">Choose Team 2</OPTION>
<?php
foreach($results as $team) {
echo "<option value='{$team['team_ID']}'>{$team['team_name']}</option>";
}
?>
</select>
</td>
</tr>
</tbody>
</table>
However, for efficiency I'd do this:
<?php
$db = new PDO( ... );
$stmt = $db->prepare("SELECT * FROM tbl_teams");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
$teamList = '';
foreach($results as $team) {
$teamList .= "<option value='{$team['team_ID']}'>{$team['team_name']}</option>";
}
?>
...
<select name="game1_team1">
<option value="0">Choose Team 1</OPTION>
<?php echo $teamList; ?>
</select>
...
<select name="game1_team2">
<option value="0">Choose Team 2</OPTION>
<?php echo $teamList; ?>
</select>

you can also use MYSQLI_*
<?php
$dbc = mysqli_connect('host','user','password','db_name');
$results= mysqli_query("SELECT `team_ID`,`team_name` FROM tbl_teams");
?>
<div class="datagrid">
<table>
<thead><tr><th>header</th><th>header</th><th>header</th></tr></thead>
<tbody>
<tr>
<td>
<select name="game1_team1">
<option value="">Choose Team 1</OPTION>
<?php while($row1 = mysqli_fetch_array($dbc ,$results)) { echo '<option value="'.$row1['team_ID'].'">'. $row1['team_name'].'</option>';} ?>
</select>
</td>
<td>Vs.</td>
<td>
<select name="game1_team2">
<option value="">Choose Team 2</OPTION>
<?php while($row2 = mysqli_fetch_array($dbc ,$results)) {echo '<option value="'.$row2['team_ID'].'">'. $row2['team_name'].'</option>';}?>
</select>
</td>
</tr>
</tbody>
</table>
it will work now.. :)

Related

How to fetch data from database table on PHP page

I have created one IMS in that I am trying to fetch data from one table from the database and display it in drop-down form to another page.
In the database, I have created one table named a party in that table one column named party_name is available and I have to fetch that column data to my order page. Below is my Code. If anyone knows a solution than please help.
<select name="party[]" style="width:100%;" required>
<?php
$result=mysql_query("SELECT * FROM partys");
while ($row = mysql_fetch_array($result)) {
?>
<option value="<?php echo $row['id'];?>"><?php echo $row['party_name'];?></option>
<?php
}
?>
</select>
Firstly: mysql extension is deprecated, you should use at least mysqli_*:
Secondly: try the below example, replacing the database connection string variables with your database credentials:
<select name="party[]" style="width:100%;" required>
<option value="">-- Please select --</option>
<?php
$dbc = mysqli_connect('localhost', 'userName', 'password', 'databaseName')
or die('Error connecting to MySQL server.');
$query = "SELECT * FROM partys";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row['id'];?>"><?php echo $row['party_name'];?></option>
<?php } ?>
</select>

PDO query stop loop - Php

so i trying to use some query at pdo , but only the first select show results , the second select dont show the results , only show " Selecione "
look my code below
<?php
$con1 = new PDO('mysql:host=localhost;dbname=db','root','passdb');
$con1->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sqlimpressora = $con1->query("SELECT * FROM impressoras");
?>
<html>
<body>
<form>
<select name="impressora" class="form-control">
<option value="selecione">Selecione...</option>
<?php while($prod = $sqlimpressora->fetch(PDO::FETCH_BOTH)) { ?>
<option value="<?php echo $prod['nome'] ?>"><?php echo $prod['nome'] ?></option>
<?php } ?>
</select>
<select name="impressora" class="form-control">
<option value="selecione">Selecione...</option>
<?php while($prod2 = $sqlimpressora->fetch(PDO::FETCH_BOTH)) { ?>
<option value="<?php echo $prod2['nome'] ?>"><?php echo $prod2['nome'] ?></option>
<?php } ?>
</select>
</form>
</body>
</html>
Do not use ->fetch twice, use ->fetchAll and loop over the result.
$sqlimpressora = $con1->query("SELECT * FROM impressoras");
$result = $sqlimpressora->fetchAll();
foreach($result as $prod) {
// <select > .....
}
Each call to $sqlimpressora->fetch() will move the cursor to the next record in the result set. So when your first while loop finished it moved the cursor to the end of the result set and thus another fetch() call fetched nothing.
One possible solution is to fetch the records into an array and use foreach to iterate through it:
$rows = $sqlimpressora->fetchAll();
foreach ($rows as $prod) {}
foreach ($rows as $prod) {}

Code implementation in php-mysql

I am trying to understand the code and I am confused to understand the code at this point below. in the first example I want to fetch data from the database and display them as drop-down list but unfortunately it is not displaying anything, and in the second example everything is working fine (fetching data displaying as the drop-down list) bu the problem is that I cant understand the code in the second example it looks much more complicated than the first example. So I want to correct my first example and after that I can rebuilt the second example based on the first one.
First table is department (ID, persondepartment, Description)
Second table board ( personboard, description)
ps: this is for my project so I dont care about Security
First Example - Not Working
<td>Department</td>
<td>
<select name='persondepartment' ID="dept">
<option ID="0">-- Select Department --</option>
<?php
mysql_connect('localhost', 'data_datab', 'password');
mysql_select_db ("data");
$getalldepartments = "SELECT * FROM department";
WHILE ($viewdepartments = mysql_fetch_array(
$getalldepartments)){
?>
<option ID="<?php echo $viewdepartments['ID'];?>
"> <?php echo $viewdepartments ['persondepartment'] ?></option>
<?php } ?>
</select>
</td>
Second Example - Working
<td>Board</td>
<td>
<?php
mysql_connect('localhost', 'data_datab', 'password');
mysql_select_db ("data");
$sql = "SELECT * FROM board";
$result = mysql_query($sql);
echo "<select name='personboard'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['personboard'] . "'>" . $row['personboard'] . "</option>";
}
?>
</td>
Try to change
$getalldepartments = "SELECT * FROM department";
to:
$getalldepartments = mysql_query("SELECT * FROM department");
and consider to use mysqli instead of deprecated mysql extension.
Correct version with PDO
<td>Department</td>
<td>
<select name="persondepartment" id="dept">
<option value="0">-- Select Department --</option>
<?php
try {
$pdo = new PDO('mysql:host=localhost;dbname=data', 'data_datab', 'password');
} catch (PDOException $e) {
echo '<option value="">' . $e->getMessage() . '</option>';
}
$getalldepartments = $pdo->query("SELECT * FROM department");
while ($viewdepartments = $getalldepartments->fetch(PDO::FETCH_ASSOC)) {
?>
<option value="<?= $viewdepartments['ID']; ?>"><?= $viewdepartments['persondepartment']; ?></option>
<?php
}
?>
</select>
</td>

Drop down form list with MySQL [duplicate]

This question already has answers here:
Populate drop down list from MySQL column data
(2 answers)
Closed 7 years ago.
so I want to make a drop down list in my form but rather than manually writing the options in the form I want to link it to my database.
HTML
<form>
<select name="fruit">
<option value="apple">Apples</option>
<option value="banana">Bananas</option>
<option value="pear">Pears</option>
</select>
<input type="submit" value="Submit">
</form>
This is what I have so far but I want to exclude the option values and replace them with existing records in my database. How do I do this in PHP?
I know I will be using something like, but I'm not sure
$results = $pdo->query('SELECT * FROM fruit');
foreach ($results as $row)
Thanks for the help :)
Assuming that your fruit table has name field:
<form>
<select name="fruit">
<?php
$results = $pdo->query('SELECT * FROM fruit');
foreach ($results as $row):
?>
<option value="<?php $row['name']?>"><?php ucfirst($row['name']) . "s"; ?></option>
<?php endforeach; ?>
</select>
<input type="submit" value="Submit">
</form>
<form>
<select name="fruit">
<?php
$conn = new PDO("mysql:host=localhost;dbname=database", 'username', 'password', array( PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$results = $conn->query("SELECT * FROM fruit");
while($row = $results->fetch( PDO::FETCH_ASSOC )){
?>
<option value="<?= $row['id'] ?>"><?= $row['fruitname'] ?></option>
<?php
}
?>
</select>
<input type="submit" value="Submit">
</form>
This should give you a basic idea of how to do this.
In your case this is the solution:
<form>
<select name="fruits" class="form-control">
<?php
$results = $pdo->query('SELECT * FROM fruit');
foreach ($results as $row)
{
?><option value="<?= $row['id'] ?>"><?= $row['fruitname'] ?></option><?php
}
?>
</select>
<input type="submit" value="Submit">
</form>

How do I populate the selected value of drop down lists with Mysql data? [duplicate]

This question already has answers here:
Using PHP to populate a <select></select> dropdown? [duplicate]
(7 answers)
Closed 7 months ago.
I need the values of form inputs to be populated by the sql database. My code works great for all text and textarea inputs but I can't figure out how to assign the database value to the drop down lists eg. 'Type of property' below. It revolves around getting the 'option selected' to represent the value held in the database.
Here is my code:
$result = $db->sql_query("SELECT * FROM ".$prefix."_users WHERE userid='$userid'");
$row = $db->sql_fetchrow($result);
echo "<center><font class=\"title\">"._CHANGE_MY_INFORMATION."</font></center><br>\n";
echo "<center>".All." ".fields." ".must." ".be." ".filled."
<form name=\"EditMyInfoForm\" method=\"POST\" action=\"users.php\" enctype=\"multipart/form-data\">
<table align=\"center\" border=\"0\" width=\"720\" id=\"table1\" cellpadding=\"2\" bordercolor=\"#C0C0C0\">
<tr>
<td align=\"right\">".Telephone." :</td>
<td>
<input type=\"text\" name=\"telephone\" size=\"27\" value=\"$row[telephone]\"> Inc. dialing codes
</td>
</tr>
<tr>
<td align=\"right\">".Type." ".of." ".property." ".required." :</td>
<td>Select from list:
<select name=\"req_type\" value=\"$row[req_type]\">
<option>House</option>
<option>Bungalow</option>
<option>Flat/Apartment</option>
<option>Studio</option>
<option>Villa</option>
<option>Any</option>
</select>
</td>
</tr>
....
using your current code:
<?php
$options = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');
foreach($options as $option) {
if ($option == $row['req_type']) {
print '<option selected="selected">'.$option.'</option>'."\n";
} else {
print '<option>'.$option.'</option>'."\n";
}
}
?>
assuming $row['req_type'] is one of the values in $options. i strongly suggest quoting your array elements (ie $row['req_type'] instead of $row[req_type]. the latter method generates errors under error_reporting(E_ALL)
you also might want to look at resources such as phpbuilder.com. some articles are pretty outdated, but will provide you with some basics on how to better structure your code. (for example, separating your HTML from your PHP code woulud help readiability in this sitaution a lot).
edit: as per the comments, any information displayed should be escaped properly (see htmlentities() for example).
Nigel,
See the answer with the check mark next to it. It go me start in solving my problem. First I select my data from the table, then I select the data i want display in my dropdown menu. If the data from the primary table matches the data from the dropdown table selected is echoed.
$query9 = "SELECT *
FROM vehicles
WHERE VID = '".$VID."'
";
$result9=mysql_query($query9);
while($row9 = mysql_fetch_array($result9)){
$vdate=$row9['DateBid'];
$vmodelid=$row9['ModelID'];
$vMileage=$row9['Mileage'];
$vHighBid=$row9['HighBid'];
$vPurchased=$row9['Purchased'];
$vDamage=$row9['Damage'];
$vNotes=$row9['Notes'];
$vKBBH=$row9['KBBH'];
$vKBBM=$row9['KBBM'];
$vKBBL=$row9['KBBL'];
$vKBBR=$row9['KBBR'];
$vYID=$row9['YID'];
$vMID=$row9['MID'];
$vModelID=$row9['ModelID'];
$vELID=$row9['ELID'];
$vECID=$row9['ECID'];
$vEFID=$row9['EFID'];
$vColorID=$row9['ColorID'];
$vRID=$row9['RID'];
$vFID=$row9['FID'];
$vDID=$row9['DID'];
$vTID=$row9['TID'];
}
$query1 = "SELECT * FROM year ORDER BY Year ASC";
$result1=mysql_query($query1);
echo "<select name='Year'>";
while($row1 = mysql_fetch_array($result1)){
echo "<option value = '{$row1['YID']}'";
if ($vYID == $row1['YID'])
echo "selected = 'selected'";
echo ">{$row1['Year']}</option>";
}
echo "</select>";
May not be efficient, but it's simple & gets the job done.
$dropdown = str_replace("<option value=\"".$row[column]."\">","<option value=\"".$row[column]."\" selected>",$dropdown);
Thanks Owen. Your code seems perfect but gave lots of php errors. I simplified it to this but just get whitespace as options:
<td>Select from list: <select name=\"req_type\">
$option = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');
foreach($option as $option) {
if ($option == $row[req_type]) {
<option selected>$option</option>}
else {
<option>$option</option>}};
</select></td>
<?php
$result = $db->sql_query("SELECT * FROM ".$prefix."_users WHERE userid='$userid'");
$row = $db->sql_fetchrow($result);
// options defined here
$options = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');
?>
<center><font class="title"><?php echo _CHANGE_MY_INFORMATION; ?></font></center><br />
<center> All fields must be filled </center>
<form name="EditMyInfoForm" method="POST" action="users.php" enctype="multipart/form-data">
<table align="center" border="0" width="720" id="table1" cellpadding="2" bordercolor="#C0C0C0">
<tr>
<td align="right">Telephone :</td>
<td>
<input type="text" name="telephone" size="27" value="<?php echo htmlentities($row['telephone']); ?>" /> Inc. dialing codes
</td>
</tr>
<tr>
<td align="right">Type of property required :</td>
<td>Select from list:
<select name="req_type">
<?php foreach($options as $option): ?>
<option value="<?php echo $option; ?>" <?php if($row['req_type'] == $option) echo 'selected="selected"'; ?>><?php echo $option; ?></option>
<?php endforeach; ?>
</select>
</td>
</tr>
...
oops.. a little too carried away.
Thanks everyone for all your help. Although I couldn't get any one answer to work it gave me ideas and I have accomplished the job! I ended up going about it a long-winded way but hey-ho if it's not broke don't fix it.
if ($row[$req_type]=='House'){
$sel_req_type1='selected';
}
else if ($row[$req_type]=='Bugalow'){
$sel_req_type2='selected';
}
etc. etc. etc.
And in the table:
<option $sel_req_type1>House</option>
<option $sel_req_type2>Bulgalow</option>
etc. etc. etc.
I still have other issues to overcome i.e. htmlentities for the text fields and quoting the array elements (ie $row['req_type'] instead of $row[req_type]. But I'll ask that on another question. Thanks again
Here is another way of going about it.
<?php
$query = "SELECT * FROM ".$prefix."_users WHERE userid='$userid'";
$result = mysql_query($query); ?>
$options = array('House', 'Bungalow', 'Flat/Apartment', 'Studio', 'Villa', 'Any');
<select name="venue">
<?php
while($row = mysql_fetch_array($result)) {
print '<option value="'.$option.'"';
if($row['req_type'] == $option) {
print 'selected';
}
print '>'.$option.'</option>';
}
?>
</select>

Categories