Display database fields as checkboxes - php

I'm trying to display all my database fields like radio buttons. For example I have this database fields :
hostess_id
hostess_name_en
hostess_surname_en
... etc ...
I want to display them as radio buttons, in order to select them, then display data information only for the selected buttons.
How can I do that?
I have something like this:
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect to MySQL server: ' . mysql_error());
}
$dbname = 'db_up';
$db_selected = mysql_select_db($dbname, $link);
if (!$db_selected) {
die("Could not set $dbname: " . mysql_error());
}
$res = mysql_query('select * from hostess', $link);
while ($row = mysql_fetch_assoc($result)){
echo "<td><input type=\'checkbox\' name=\'hostess[]\' value=\'" . $row['hostess_id'] . "\'>" . $row['hostess_firstname_en'] . "<br />";
}
?>

With PDO, It will get all fields
$q = $dbh->prepare("DESCRIBE tablename");
$q->execute();
$table_fields = $q->fetchAll(PDO::FETCH_COLUMN);
With deprecated mysql_*
function mysql_field_array( $query ) {
$field = mysql_num_fields( $query );
for ( $i = 0; $i < $field; $i++ ) {
$names[] = mysql_field_name( $query, $i );
}
return $names;
}
// Example of use
$fields = mysql_field_array( $query );
Than you can loop through that array of field names and use the name with your check box.

Checkboxes need a unique name or they need to be an array. A checkbox array would be appropriate for what you're doing:
while ($row = mysql_fetch_assoc($result)){
echo "<input type='checkbox' name='hostess[]' value='" . $row['id'] . "' />" . htmlentities($row['hostess_surname_en']) . "<br />";
}
This will give you a list of checkboxes with the hostess surname next to each.
Now, when this form is submitted to a PHP script, you will be able to access the selected row id's with:
$selectedIds = $_POST['hostess']; // an array
$selectedIds is an array of the checked record ids.
I suggest using PDO or MySQLi for new code because the mysql_* library is deprecated.

Related

dynamic selected option using variables from mysql

After finally getting this to work, I thought I'd post it in case it maybe
I was having trouble working to populate a few sets of dropdown select tags.
I had researched a number of similar submissions and solutions, but I still couldn't find the answers I'd been looking for.
#Ronser had helped me to test through my queries, which lead me to learning more about how the arrays actually worked. I realised I needed to go back and to update the access column in TABLE 1 to access_id. (I should've indexed these originally).
Table 1: app_generalData
app_id,
title,
status_id,
category_id,
tags,
access_id
Table 2: app_access
access_id,
access_title
Desired result(s):
Objective 1: Show/echo the selected option (stored in app_access table)
Objective 2:
Build these queries with variables to allow for easy updating for adding new dropdowns.
Resulting HTML:
<select name="access"><option "">Global</option>\n<option " selected ">Corporate</option>\n<option "">Local Site</option>\n</select>
Code:
<?php
//connect to the database
require_once('connectvars.php');
// global variable for this populating this dropdown
$dropdown = "access";
$before_var = "app_";
$column1= $before_var.$dropdown;
$after_var = "_title";
$column2= $dropdown.$after_var;
$id_var= "_id";
$dropdown_table_id= $dropdown.$id_var;
$optionsList = array();
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die ('Error connecting to MySQL server.');
echo '<select name="' . $dropdown . '">';
// See if we're viewing a selected app or are we creating a new app
if (isset($_GET['app_id'])) {
// print_r($_GET); // GET is Successful
// 'if' [app_id] is appended in the url
// STEP 1: Get the stored value of the SELECTED from mysql
// Get "selected item" (id) from app_generalData (table) with the "selected app" (id)
$option = "SELECT ".$dropdown_table_id." FROM app_generalData WHERE app_id ='" . $_GET['app_id'] . "'";
// submit the select statement
// Get & store the value of "selected" <option>
$selected_option = mysqli_query($dbc, $option)
or die(mysql_error());
$row_1=mysqli_fetch_array($selected_option);
// STEP 2: Build the SELECT input
// Set the array of data to populate dropdown list <option>s
$options = "SELECT * FROM ".$column1." ORDER BY ".$dropdown_table_id."";
// NOTE: print_r($options)...SELECT access_title FROM app_access ORDER BY access_id
$selected_options = mysqli_query($dbc, $options)
or die(mysqli_error());
$kk = 0; //initialize kk
while($row_2 = mysqli_fetch_array($selected_options)) {
$selected ='';
if($row_1["$dropdown_table_id"]==$row_2["$dropdown_table_id"]) {
$selected=' selected ';
}
$optionsList[$kk++] ='<option "' . $selected . '">' . $row_2["$column2"] . '</option>';
}
// Echo the <option>s
$optionCount = count($optionsList);
for($i=0;$i<$optionCount;$i++) {
echo $optionsList[$i].'\n';
}
}
else {
// Action 'if' no [app_id] is appended in the url
};
// close the last <select> tag
echo '</select>';
// close the last database
mysqli_close($dbc);
?>
Please try the following...
Check for the 'app_id'.
Print the sql query and run directly in your mysql.
If it returns no rows or error please verify the sql query.
try this...
$options = "SELECT ".$column2." FROM ".$column1." ORDER BY ".$dropdown_table_id."";
$kk = 0; //initialize kk
while($row = mysqli_fetch_array($options)) {
$selected ='';
if($selected_option==$row["$column2"]) {
$selected=' selected ';
}
$optionsList[$kk++] ='<option "' . $selected . '">' . $row["$column2"] . '</option>';
//try this change. or
echo '<option "' . $selected . '">' . $row["$column2"] . '</option>'; //print it here itself
}
print_r($optionsList);
<?php
//connect to the database
require_once('connectvars.php');
// global variable for this populating this dropdown
$dropdown = "access";
$before_var = "app_";
$column1= $before_var.$dropdown;
$after_var = "_title";
$column2= $dropdown.$after_var;
$id_var= "_id";
$dropdown_table_id= $dropdown.$id_var;
$optionsList = array();
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME)
or die ('Error connecting to MySQL server.');
echo '<select name="' . $dropdown . '">';
// See if we're viewing a selected app or are we creating a new app
if (isset($_GET['app_id'])) {
// print_r($_GET); // GET is Successful
// 'if' [app_id] is appended in the url
// STEP 1: Get the stored value of the SELECTED from mysql
// Get "selected item" (id) from app_generalData (table) with the "selected app" (id)
$option = "SELECT ".$dropdown_table_id." FROM app_generalData WHERE app_id ='" . $_GET['app_id'] . "'";
// submit the select statement
// Get & store the value of "selected" <option>
$selected_option = mysqli_query($dbc, $option)
or die(mysql_error());
$row_1=mysqli_fetch_array($selected_option);
// STEP 2: Build the SELECT "selected" and <options>
// Set the array of data to populate dropdown list <option>s
$options = "SELECT * FROM ".$column1." ORDER BY ".$dropdown_table_id."";
// NOTE: print_r($options)...SELECT access_title FROM app_access ORDER BY access_id
$selected_options = mysqli_query($dbc, $options)
or die(mysqli_error());
$kk = 0; //initialize kk
while($row_2 = mysqli_fetch_array($selected_options)) {
$selected ='';
// Compare access_id from table1 against access_id from table2
if($row_1["$dropdown_table_id"]==$row_2["$dropdown_table_id"]) {
$selected=' selected ';
}
$optionsList[$kk++] ='<option "' . $selected . '">' . $row_2["$column2"] . '</option>';
}
// Echo the <option>s
$optionCount = count($optionsList);
for($i=0;$i<$optionCount;$i++) {
echo $optionsList[$i].'\n';
}
}
else {
// Action 'if' no [app_id] is appended in the url
};
// close the last <select> tag
echo '</select>';
// close the last database
mysqli_close($dbc);
?>

value of dropdown list from mysql

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

Need help displaying mysql database contents to webpage

I need help displaying data from mysql to a webpage, I am coding in php.
My database consists of products which are cars(same type e.g Chevy), right now I have 2 rows (I can add more if I want to), each cars contains the image path, and description.
I can show one row (car) but I am unable to show all rows. I know I have to go through a loop to get all the data from the cars database but I am not sure how to implement it.
This is what I have so far. Assuming I already connected to my database
note: the image path I would like to show the picture in my website.
This is how i would like it to display in my webpage:
$query = "SELECT * FROM cars where cars.carType = 'Chevy' AND \
cars.active = 1";
$numberOfFieds = mysqli_num_fields($result);
$numberOfRows = mysqli_num_rows($result);
/* Gets the contents */
$row = mysqli_fetch_row($result);
$rows = mysqli_fetch_assoc($result);
$fieldcarssontable = array_keys($row);
echo "<table>";
while($row = mysqli_fetch_assoc($result)){
echo "<th>" . $fieldcarssontable[imgPath] . "</th>";
echo "<th>" . $fieldcarssontable[description] . "</th>";
}
echo "</tr>";
echo "</table>";
Just add a while loop. mysqli_fetch_assoc returns a row and moves the internal pointer to the next row until all rows are fetched, then it returns false and the while loop will stop
Pseudo syntax to understand while
while ( this is true ) {
execute this
}
So on your case you can say
while ( $row = mysqli_fetch_assoc( $result ) ) {
// process/output $row
}
mysqli_fetch_assoc and mysqli_fetch_row literally do the same, assoc gives you the array with your result field names as index so this is simpler to access ( $row['name'] rather than $row[0] when using fetch_row )
Have fun! :)
EDIT
// connect to your database server
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'my_db');
// an error occured
if (!$link) {
die('Connect Error (' . mysqli_connect_errno() . ') '
. mysqli_connect_error());
}
// build your query
$query = "SELECT
* # select actual fields instead of *
FROM
cars
WHERE
cars.carType = 'Chevy'
AND
cars.active = 1";
// execute query
$result = mysqli_query($link, $query );
if ( !$result ) {
die( 'no result' );
}
// number of fields
$numberOfFields = mysqli_num_fields($result);
// the field names
$fieldNames = mysqli_fetch_fields($result);
// number of result rows
$numberOfRows = mysqli_num_rows($result);
// watch the content of fieldName and compare it with the table header in the output
print_r( $fieldName );
echo "<table>\n";
// table header, not neccessary to put this into a loop if the query isn't dynamic
// so you actually know your field names - you can echo the header without any variable.
// for the sake of learning about loops I added this
foreach( $fieldNames as $index => $fieldName ) {
echo "\t<th>field #" $index . ", name:" . $fieldName . "</th>\n";
}
// now it's time to walk through your result rows, since we only need to check for "true" a while loop does best
while ( $row = mysqli_fetch_assoc( $result ) ) {
echo "\t<tr><td>" . $row['imgPath'] . "</td><td>" . $row['description'] . "</td></tr>\n";
}
echo "</table>\n";
// remove the result from memory
mysqli_free_result( $result );
mysqli_close( $link );
You misspelled $numberOfFields in your loop, which means you're using a different variable for your loop control. Your loop won't work.
I recommend turning on the error reporting so PHP can catch this stuff for you.
Use this... just while loop
<?php
// Array
while($result = mysql_fetch_assoc($result)) {
//show you fields
echo $result["FieldName"];
}
?>
Or use this proper
<?php
// Edit it as per your query
$query = "SELECT * FROM cars";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while($row = $result->fetch_assoc()) {
//show you fields
echo $row["Name"];
}
/* free result set */
$result->free();
}
/* close connection */
$mysqli->close();
?>

PHP: Separate MySQL query values with a comma

I have a MySQL query like this written in PHP:
$merkki = $_GET["merkki"];
// Retrieve all the data from the table
//to show models based on selection of manufacturer
$result = mysql_query("SELECT * FROM Control_Mallit WHERE merkki_id = $merkki")
or die(mysql_error());
echo '{';
while($row = mysql_fetch_array($result)){
echo '"' . $row['id'] . '"' . ":" . '"' . $row['malli'] . '"';
}
echo '}';
Result is correct, but how I can get a comma after each record? If I echo (,) after each row my code doesn't work. I need it formatted as described below.
{
"":"--",
"series-1":"1 series",
"series-3":"3 series",
"series-5":"5 series",
"series-6":"6 series",
"series-7":"7 series"
}
What's the best way to do this?
Immediately stop using your code. It is vulnerable to SQL injection. Think of what would happen if the value of merkki was 1 OR 1=1. The statement would return all records:
SELECT * FROM Control_Mallit WHERE merkki_id = 1 OR 1=1
You need to bind parameters to your query using mysqli_ or PDO functions (mysql_ functions are being deprecated. Also, use a column list and do not SELECT *.
Here is a possible solution using mysqli_ (not tested):
<?php
$link = mysqli_connect('localhost', 'my_user', 'my_password', 'world');
/* check connection */
if (!$link) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$array = array();
/* create a prepared statement */
$stmt = mysqli_prepare($link, "SELECT id, malli FROM Control_Mallit WHERE merkki_id = ?");
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, 'i', $_GET[merkki]);
/* execute query */
$result = mysqli_stmt_execute($stmt);
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
$array[] = '"' . $row['id'] . '"' . ":" . '"' . $row['malli'] . '"';
}
/* free result set */
mysqli_free_result($result);
/* close connection */
mysqli_close($link);
echo '{' . implode(',', $array) . '}';
?>
Edit
Following your original code, this solution should work:
$merkki = $_GET["merkki"];
$array = array();
// Retrieve all the data from the table to show models based on selection of manufacturer
$result = mysql_query("SELECT * FROM Control_Mallit WHERE merkki_id = $merkki")
or die(mysql_error());
while($row = mysql_fetch_array($result)){
$array[] = '"' . $row['id'] . '"' . ":" . '"' . $row['malli'] . '"';
}
echo '{' . implode(',', $array) . '}';
Try:
$merkki = $_GET["merkki"];
$merkki = mysql_real_escape_string($merkki);
// Retrieve all the data from the table to show models based on selection of manufacturer
$result = mysql_query("SELECT * FROM Control_Mallit WHERE merkki_id = $merkki")
or die(mysql_error());
$numRows = mysql_num_rows($result);
$row = 1;
echo '{';
while($row = mysql_fetch_array($result)){
echo '"' . $row['id'] . '"' . ":" . '"' . $row['malli'] . '"';
if ($row < $numRows) {
echo ',';
}
$row++;
}
echo '}';
It just uses the row count to determine if it should echo a comma or not based on whether or not it is on the last result.
Also, be sure to escape any input you pass to mysql queries or you are vulnerable to SQL injection. See about switching to PDO or Mysqli in the future.
I'd just stick everything in an array and use json_encode() to output it, eg
$data = array();
while ($row = mysql_fetch_array($result)) {
$data[$row['id']] = $row['malli'];
}
echo json_encode($data);
Small example here - http://codepad.viper-7.com/My27XJ
Also, you should not be using the deprecated mysql extension. Instead, I recommend PDO, eg
$db = new PDO(/* connection details */);
$stmt = $db->prepare('SELECT id, malli FROM Control_Mallit WHERE merkki_id = ?');
$stmt->bindParam(1, $_GET['merkki']);
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
// and so on

Populate a PHP Dropdown List from MySQL Database

I'm trying to populate a dropdown list in my web page from a mysql database table which has only one column (pathology_id). I know there is test data in there but the best I can do is populate the box with the field name, not the row values. The code I have thus far is below, can anyone suggest how to get more than just the column name? Thanks in advance.
<?php $con = mysql_connect("localhost","dname","dbpass");
if(!$con)
{
die('Could not connect: ' . mysql_error());
}
$fields = mysql_list_fields("dbname","PATHOLOGY",$con);
$columns = mysql_num_fields($fields);
echo "<form action = newcase.php method = POST><select name = Field>";
for($i = 0; $i < $columns ; $i++)
{
echo "<option value = $i>";
echo mysql_field_name($columns , $i);
}
echo "</select></form>";
if(!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else
{
echo "1 record added";
}
mysql_close($con) ?>
Try this:
<?php
// This could be supplied by a user, for example
$firstname = 'fred';
$lastname = 'fox';
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT firstname, lastname, address, age FROM friends WHERE firstname='%s' AND lastname='%s'",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname));
// Perform Query
$result = mysql_query($query);
// Check result
// This shows the actual query sent to MySQL, and the error. Useful for debugging.
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
// Use result
// Attempting to print $result won't allow access to information in the resource
// One of the mysql result functions must be used
// See also mysql_result(), mysql_fetch_array(), mysql_fetch_row(), etc.
while ($row = mysql_fetch_assoc($result)) {
echo $row['firstname'];
echo $row['lastname'];
echo $row['address'];
echo $row['age'];
}
// Free the resources associated with the result set
// This is done automatically at the end of the script
mysql_free_result($result);
?>
From PHP: mysql_query().
mysql_list_fields just returns information about a given table, NOT the data contained.
Select option should has close tag.
echo '<form action="newcase.php" method="POST"><select name"="Field">';
for($i = 0; $i < $columns ; $i++)
{
echo '<option value="' . $i . '">';
echo mysql_field_name($columns , $i);
echo '</option>';
}
echo '</select></form>';

Categories