HTML Select option with PHP Dynamic - php

I'm getting a weird result when i try to implement the PHP inside a HTML
The config is literally my DB connection, other scripts work well but only for this matter i couldn't figure out.
Maybe I missed out some elements.
<select name="country">
<option value="" disabled selected style="display: none;">All Japan Cities</option>
<?php
include 'scripts/config.php';
$query = "SELECT state FROM product";
$result = mysql_query($query);
$count = count($result);
if (!empty($count)) {
while($row = mysql_fetch_array($result))
{
$state = $row['state'];
echo "<option value='$state'> $state </option>";
}
} else {
echo '<option>No data</option>';
}
?>
</select>
I keep on getting no data for my select statement where I have 3 results in my db.

I don't think you can do a count() on a mysql result set like that.
Try using mysql_num_rows instead, like this:
....
$count = mysql_num_rows($result);
if (!empty($count)) {
....
Also, as others have said, these old mysql_ functions are deprecated, so you should probably switch to mysqli or PDO if that is practical as well.

Related

Create special dynamic select

I want to do the next thing but I don't know how to do this, I'll try to explain me
I have an field generated by php code like this (Works)
<select id="profiles_select" name="profiles_select">
<?php
do {
?>
<option value="<?php echo strtoupper($system['profile']);?>">
<?php echo strtoupper($system['profile']);?></option>
<?php
} while($system = mysql_fetch_assoc($r)); //the "$r" it's the query
$rows = mysql_num_rows($r);
if($rows > 0) {
mysql_data_seek($r, 0);
$systemas = mysql_fetch_assoc($r);
}
?>
</select>
The query
<?php
$q="SELECT DISTINCT profile FROM sys_profiles";
$r=mysql_query($q,$ConecLocal) or die(mysql_error());;
$systemas=mysql_fetch_assoc($r);
$tsys=mysql_num_rows($r);
?>
What I need?
I need generate another similar to first generated by php code but, this time I need made a Query including the value of the first , something like this:
<?php
$value_select=$_GET['profiles_select'];
$q2="SELECT DISTINCT systems FROM sys_profiles where profile=$value_select";
$r2=mysql_query($q,$ConecLocal) or die(mysql_error());;
$profiles2=mysql_fetch_assoc($r);
$tsys=mysql_num_rows($r);
?>
Next of the query I need show in the another the query result, something similar to the first select (generated by php), but do the query when the first of the it's selected
<select id="systems_select" name="system_select">
<?php
do {
?>
<option value="<?php echo strtoupper($system['systems']);?>">
<?php echo strtoupper($profiles2['systems']);?></option>
<?php
} while($profiles2 = mysql_fetch_assoc($r2)); //the "$r2" it's the another query
$rows2 = mysql_num_rows($r2);
if($rows2 > 0) {
mysql_data_seek($r2, 0);
$systemas = mysql_fetch_assoc($r2);
}
?>
</select>
Thanks for the help.

Populating Dropdown HTML Menu with MySQL Query Results

I'm attempting to populate an HTML dropdown menu with the results of a MySQL query. The query is running fine and not throwing any errors, but for some odd reason the results won't display correctly.
<?php
$query = "SELECT * FROM parts WHERE itemName LIKE 'Processors:%'";
$result = mysql_query($query) or die("Unable to query CPU parts");
while($row=mysql_fetch_array($result)) {
$option .= "<option value='{$row['itemName']}'></option>";
}
?>
<select name="cpu"><? echo $option; ?></select>
I'm pretty sure it lies somewhere in the $option .= ... ; but it I can't seem to figure it out.
You are not printing the value to be shown in dropdown
try this
while($row=mysql_fetch_array($result)) {
$option .= "<option value='{$row['itemName']}'>{$row['itemName']}</option>";
}
I saw that you are using short tags here
<select name="cpu"><? echo $option; ?></select>
please make sure you have short tag enabled in php.ini
Two things:
You need to initialize $option and print the value to be shown in the dropdown
<?php
$query = "SELECT * FROM parts WHERE itemName LIKE 'Processors:%'";
$result = mysql_query($query) or die("Unable to query CPU parts");
$option = "";
while($row=mysql_fetch_array($result)) {
$option .= "<option value='{$row['itemName']}'>{$row['itemName']}</option>";
}
?>
<select name="cpu"><? echo $option; ?></select>
Seems you forget to add a value inside <option></option> field you only set value for fetching $_POST[] but not for viewing. :D
Also seeing $option variable to be concatenated seems that you already declared it at first
if not you need to probably declared it first.cause this may result to error undefined variable.
<?php
$query = "SELECT * FROM parts WHERE itemName LIKE 'Processors:%'";
$result = mysql_query($query) or die("Unable to query CPU parts");
$option = '';
while($row=mysql_fetch_array($result)) {
$option .= '<option value='.$row['itemName'].'>'. $row['itemName'].'</option>';
}
?>
<select name="cpu"><?php echo $option; ?></select>
Forgot the simplest part:
$aa .= "{$row['itemName']}";
I needed to add the actual label to be displayed between the option tags :)

Select multiple (PHP and MySQL)

I have a form with a select multiple like this:
<select name="states[]" size="5" multiple>
<option value="2">state 1</option>
<option value="3">state 2</option>
<option value="4">state 3</option>
<option value="5">state 4</option>
<option value="6">state 5</option>
</select>
I want to have the possibility to choose more than one state, and then make the query to my database and show the description of each state chosen.
So this is what I have to make the query using PHP and MySQL:
$state = $_POST['states'];
$data = mysql_query("SELECT * from states WHERE id_state = '$state'",$db);
while($row = mysql_fetch_array($data)){
$result=$row['description'];
}
echo $result;
I have that code and it doesn't show anything.
How can I fix this problem?
Try this
$state = $_POST['states']; // return Array
$count_states = count( $state );
if( $count_states > 0) {
$states = implode( ',', $state);
$data = mysql_query("SELECT * from states WHERE id_state IN ($states)",$db);
while($row = mysql_fetch_array($data)){
echo $row['description'];
}
}
This would require a simple foreach to go through the array and get results based on each value as such,
foreach($_POST['states'] as $state) {
$data = mysql_query("SELECT * from states WHERE id_state = '$state'",$db);
$row = mysql_fetch_array($data);
echo $row['description'];
}
Also since you're not protecting your query in some sort and are using mySQL which has been deprecated as of PHP 5.5.0, I suggest you looking into PDO or mySQLi Prepared statements
$_POST['states'] holds an Array with all the ID's of the selected states.
Off course you can query your database for every posted state_id, but way nicer (and faster) would it be to make a query which looks like this and uses only one query:
SELECT description FROM states WHERE id_state=1 OR id_state=2 etc etc
This also might be a good point to start using a database abstraction layer like PDO.
As the number of posted states is variable, we need to make the statement also variable:
// The [connection setup][2] by PDO is done in $conn, with some proper exception handlers
// e.g. $conn = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
// Fill an array with count() number of elements with value 'id_state=?'
$place_holders = array_fill(0, count($_POST['state']), 'id_state= ?');
//implode the array
$place_holders = implode(' OR ', $place_holders);
// prepare the query
$st = $conn->prepare("SELECT description FROM state WHERE $place_holders");
// execute to above prepared query with the $_POSTED states
$st->execute($_POST['state']);
// traverse the result
foreach($st->fetchAll() AS $r){
// do some magic
}
You could build the string by iterating through the array:
$state = "";
foreach($_POST['states'] AS $s)
{
// Sanitize $s here
$state .= "`id_state` = " . $s . " OR";
}
if($state)
{
$state = substr($state, 0, -3);
$data = mysql_query("SELECT * from states WHERE $state",$db);
while($row = mysql_fetch_array($data)){
echo $row['description'];
}
}
Of course, you should use something like MySQLi or PDO to handle database interaction. They will have ways to sanitize input easily so you can avoid obvious SQL injection.
Tamil has a pretty good IN select method as well. This is just one option.
Example (pages for edit):
//On select_multiple.php (Form):
<?php
//Conn
include('incl_config.php');
//Multiple data to bring
$sql = " select COD_DXS,VALOR_DXS from hc_dxsindromico where ESTADO_DXS='1' ";
$result=#mysql_query($sql);
?>
//In the form select:
<select multiple="multiple" size="7" name="dxsindromico[]"> //look yes or yes brackets []
<option value="" selected="selected">Choose one or more options</option>
<?php
while($row=mysql_fetch_array($result)){
?>
<option value="<?php echo $row['COD_DXS']; ?>" style="color:#F00;"><?php echo $row['VALOR_DXS'];?></option>
<?php } ?>
</select>
//////////// On grabar_mtr.php ///////////////
<?php
include('incl_config.php');
/*Multiple selection form in HTML5, PHP and Bootstraps
Created by: www.nycsoluciones.com
Version: 1.1*/
//we use a foreach to traverse the array (values of our select and save them in the table dxsindromico_data)
if(isset($_POST['dxsindromico'])){
foreach( $_POST['dxsindromico'] as $insertar ) {
//echo $insertar;
$sqli="insert into dxsindromico_data(DXSINDROMICO_HC) values('$insertar')";
//echo $sqli;
//exit;
$resulti=mysql_query($sqli);
}
} else{
foreach( $_POST['dxsindromico'] as $insertar ) {
//echo $insertar;
$sqli="insert into dxsindromico_data(DXSINDROMICO_HC) values('$insertar')";
$resulti=mysql_query($sqli);
}
}
?>

Using php to fill a <select> on webpage. Looking for a faster load time

I added this :
<select>
<option value=""></option>
<?php include 'connect/config.php'; ?>
<?php include 'connect/opendb.php'; ?>
<?php
$query = $db->query('SELECT type FROM card_type');
$rows = $query->fetchAll();
foreach($rows as $row) {
print '<option value="'.$row['type'].'">'.$row['type'].'</option>';
}
?>
<?php $db =null ?>
</select>
to my page and now it's takeing about 5 seconds longer to load the page.
Is there a more effecient way to fill a option box from a database?
These are some issues in your code that affects performance:
You should not call print for each row of your table. That penalizes
performance (if the server is not caching the output) as everytime
you call print you will be sending bytes across the net which is a
costly operation that is better be done once for one big chunk of
data rather than many times for small chunks of data , that is
the reason web servers will often cache all your PHP output prior to
sending it to the browser.
You should pass by reference the array value when traversing the
array with foreach, to avoid the copy of a variable in each
iteration of the loop.
Echo with commas, not periods. If
you use periods, PHP has to concatenate the string before it
outputs. If you use commas, it just outputs them in order with no
extra processing.
You should use echo instead of print(). As a language construct rather than a
function, echo has a slight performance advantage over print().
So this is your code with points 2, 3 and 4 above corrected, thus assuming your web server is caching output:
<?php
$query = $db->query('SELECT type FROM card_type');
$rows = $query->fetchAll();
foreach($rows as &$row) {
echo '<option value="', $row['type'] ,'">' ,$row['type'] , '</option>';
}
?>
and this is your code with point 1 and 2 above corrected, thus assuming your web server is not caching the output:
<?php
$query = $db->query('SELECT type FROM card_type');
$rows = $query->fetchAll();
$out = '';
foreach($rows as &$row) {
$out .= '<option value="'.$row['type'].'">'.$row['type'].'</option>';
}
echo $out;
?>
Right now, you're putting the entire database table into a php array. If your table is large, this may cause the delay in response.
Try this instead, for the part where you fill the <select>:
<?php
$query = $db->query('SELECT type FROM card_type');
while($row = $query->fetch_array()) {
print '<option value="'.$row['type'].'">'.$row['type'].'</option>';
}
?>
Try this one..
<select>
<option value=""></option>
<?php
include 'connect/config.php';
include 'connect/opendb.php';
$query = $db->query('SELECT type FROM card_type');
$rows = $query->fetchAll();
$select_option = '';
foreach($rows as $row) {
$select_option .= '<option value="'.$row['type'].'">'.$row['type'].'</option>';
}
echo $select_option;
unset($db);
?>
</select>

Some PHP Code is breaking the rest of the page

I have an odd problem. Basicly my page works fine however after a small bit of php, everything after those lines dont load too the page.
<?php
//GET SCHOOLS
$sql = "SELECT `id` FROM `school`";
$query = mysql_query($sql) or die(mysql_error());
$numschools = mysql_num_rows($query);
echo "<select id=\"schoolselect\" class=\"schoolselect\" value=\"Select School\">
<option id='selectschool' value = \"select\" name=\"select\">Select A School</option>
";
while($result = mysql_fetch_array($query) or die(mysql_error()))
{
$school = $result['id'];
echo "<option value = \"$school\" name=\"$school\">".$school ."</option>";
}
echo "</select>";
?>
everything before that works, the php part works but anything after that echo "select" doesnt
any help would be amazing
Never call die(mysql_error()) inside a fetch loop. mysql_fetch_array() returns FALSE when no more rows are available, so when the last row is reached, die() is called and your script will terminate leaving the </select> unclosed. You won't get an error message, but you'll be left with incomplete HTML that won't render properly in the browser.
// Don't call die(mysql_error()) in a fetch loop!
while($result = mysql_fetch_array($query))
{
$school = $result['id'];
echo "<option value = \"$school\" name=\"$school\">".$school ."</option>";
}
Chances are your script is or die()ing inside the <select> tag, which is invisible in the browser.
View the page's source, and you'll most likely see a PHP fatal error or a die message at the end.
EDIT: Or read Michael's answer, cuz I forgot how things worked. Duh :p At least this answer will help you find related problems in the future.

Categories