PHP Form from Array Select Value Edit/Save - php

I'm using an array to output a form for product entry.
$labels = array(
"category" => "Model",
"model_number" => "Model No.",
"description" => "Description");
The categories are populated as select/option set, which is easy when adding a new product. The issue comes when I need to edit the product. I would like to query the category table to return all the available categories to populate the select/option set. At the same time, I need to query the products table so that I can provide their saved Model Number and Description.
The following is my code from the add form to give you an idea of how I'm structuring this.
foreach($labels as $field => $label) {
if($field == "category") {
echo "<label>$label:</label>";
echo "<select name=\"$field\">";
while($row=mysqli_fetch_assoc($result)) {
extract($row);
echo "<option value=\"$category\">$category</option>";
}
echo "</select>";
echo "<br />";
}
else {
echo "<label>$label:</label>";
echo "<input type=\"text\" name=\"$field\" />";
echo "<br />";
}
Thanks for the help. I'm sure it's simple, but my brain isn't quite providing me with the solution at the moment.

Having $labels array is a bad idea.
Get all your data first. Select your product data into array. Select your categories into array.
Show the form, as any other HTML you create with PHP
<label>Model:</label>
<select name="category">
<? foreach($cats as $category): ?>
<option<? if ($category == $row['category'])?> selected?>><?=$category?></option>
<? endforeach ?>
</select>
<br />
<label>Model No.:</label>
<input type="text" name="model_number" value="<?=$row['model_number']?>"/>
<br />
and so on
don't forget to htmlspecialchars() your values before placing them into value attribute

you can query the product table like this:
$sql = "SELECT * FROM products WHERE product_id = $product_id";
$q = mysql_query( $sql );
$row = mysql_fetch_assoc( $q );
$model_number = $row['model_number'];
$description = $row['description'];
$category = $row['category'];

Related

How to dynamically get the value of a select tag from MySQL table

Thanks for dropping by and I'm sorry if this question seems to be easy as I'm kinda new to php. Im trying to do a school project and my problem now is that I cant seem to get the values of the dropdown. I have been trying to search in every forum and some similar questions in here but they seem to only show how i can populate the dropdown with database values.
The code for populating the dropdown menu is working, but recording the selected value is not working for me.
Here is my php code for the dropdown:
<div class="panel">
<label class="panelname">Category:</label>
<select name="category" class="signup_field">
<option>Select One</option>
<? // retrieve all the categories and add to the pull down menu
$query = 'SELECT category_id, name FROM category ORDER BY name ASC';
$request = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($request, MYSQLI_NUM)) {
$cat_id = $row[0];
echo "<option value=\"row[0]\"";
//check for stickyness:
if (isset($_POST['category']) && ($_POST['category'] == $row[0])) {
echo ' selected="selected"';
//$_POST[]
} echo ">$row[1]</option>\n";
}
?>
</select>
<? if (array_key_exists('category', $add_product_errors)) echo '<label class="error">' . $add_product_errors['category'] . '</label>'; ?>
</div>
and here is my part of my code for validation: -
// Check for a form submission:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
// Check for a category:
if (!isset($_POST['category']) || !filter_var($_POST['category'], FILTER_VALIDATE_INT, array('min_range' => 1))) {
$add_product_errors['category'] = 'Please select a category!';
}
..... // other codes for validation (Eg: if (empty($add_product_errors)) { proceed to query} )
I don't know what seems to be the problem but there are no values recorded in the $_POST['category'] for me to save into MySQL and I keep getting the Please select a category error.
Thank you all for your help. :)
your problem seems to be echo "<option value=\"row[0]\"";. You want to replace it with
echo "<option value=\"$row[0]\"";
echo "<option value=\"row[0]\""; just puts a String row[0] there
Thanks, I seem to have solve the problem ..
I have seemed to have deleted the ($)row in the row[0] for it to be read properly.
just put $ on the row[0]:
echo "<option value=\"row[0]\"";
I used to solve this problem like ... In your case.
while ($row = mysqli_fetch_array($request, MYSQLI_NUM)) {
$cat_id = $row[0];
$str = null;
if (isset($_POST['category']) && ($_POST['category'] == $row[0])) {
$str = 'selected="selected"';
}
echo '<option value="'.$row[0].'" '.$str.'>'.$row[1].'</option>';
}

Dropdown Menu to Query Database

First of I apologize if this is a dumb question - I'm just starting to pick up my php/mysql skills. I'm making a dropdown form with 3 dropdowns. I want to be able to trigger a query from the form. You select Part Type, Make, Model hit submit and a table of results is displayed.
I have my form populated with 3 arrays and when you hit submit, I can echo the key of each selected item to the page:
echo '<form action="dbBrowse.php" method="post">';
$mak = array (0 => 'Make', 'Ford', 'Freightliner', 'Peterbilt', 'Sterling', 'Mack', 'International', 'Kenworth', 'Volvo');
$mod = array (0 => 'Model', 'Argosy', 'Midliner');
$p = array (0 => 'Part', 'Radiator', 'Charge Air Cooler', 'AC');
echo '<select name="drop1">';
foreach ($p as $key => $value) {
echo "<option value=\"$key\">
$value</option>\n";
}
echo '</select>';
echo '<select name="drop2">';
foreach ($mak as $key => $value) {
echo "<option value=\"$key\">
$value</option>\n";
}
echo '<select/>';
echo '<select name="drop3">';
foreach ($mod as $key => $value) {
echo "<option value=\"$key\">
$value</option>\n";
}
echo '<select/>';
echo '</form>';
//echo keys of selection
echo $_POST['drop1'];
echo "<br />";
echo $_POST['drop2'];
echo "<br />";
echo $_POST['drop3'];
//these echo something like 1, 1, 3 etc. to my page
Where I'm getting lost is I'm looking to take the selected options and insert them into a query something like this:
$dropSearch = mysql_query('SELECT * FROM parts WHERE part= "$partTypeVar" . AND WHERE make = "$makeTypeVar" . AND WHERE model = "$modelTypeVar"');
$partTypeVar being the corresponding value to the key that is being returned from the array.
I'm driving myself crazy trying to figure out how to make that happen. Eventually I want to expand this further but just being able to create a mysql statement with the values selected would make my day right now. I understand the concept of what needs to happen but I'm unsure of how to accomplish it. Any help or pushes in the right direction would be greatly appreciated.
First of all, you have to delete the . char in your SQL query, there's no need to use it for now and of course assign the correct values to the variables.
$partTypeVar = mysql_real_escape_string($_POST['$drop1']);
$makeTypeVar = mysql_real_escape_string($_POST['$drop2']);
$modelTypeVar = mysql_real_escape_string($_POST['$drop3']);
$dropSearch = mysql_query('SELECT * FROM parts WHERE part= "$partTypeVar" AND WHERE make = "$makeTypeVar" AND WHERE model = "$modelTypeVar"');
I am assuming that's the correct order of your variables.
I hope this help!
If I've understood your question, when the form is submitted, you want to query the database with the selected values.
Example using AND:
// Prepare the Query
$query = sprintf(
"SELECT * FROM parts WHERE part='%s' AND make='%s' AND model='%s'",
mysql_real_escape_string($_POST['drop1']),
mysql_real_escape_string($_POST['drop2']),
mysql_real_escape_string($_POST['drop3'])
);
// Execute the Query
mysql_query($query);
This will select all rows from the table parts that match those three values.
Example using OR:
// Prepare the Query
$query = sprintf(
"SELECT * FROM parts WHERE part='%s' OR make='%s' OR model='%s'",
mysql_real_escape_string($_POST['drop1']),
mysql_real_escape_string($_POST['drop2']),
mysql_real_escape_string($_POST['drop3'])
);
// Execute the Query
mysql_query($query);
This will select all rows from the table parts that match any of those three values.
You can read more about this:
mysql_query
mysql_real_escape_string
MySQL 5.6 Reference Manual :: 12 Functions and Operators :: 12.3 Operators
<select name="myFilter">
<option value="Chooseafilter" name="default">Choose a filter...</option>
<option value ="Lastname" name="opLastName">Last Name</option>
<option value="Firstname" name="opFirstName">First Name</option>
<select>
<li><!--TEXT SEARCH INPUT--><input type="text" name="search_filter" /></li>
...
dbconnection();#assume that all connection data is here
...
$filter = $_POST['myFilter']; #
...
switch($filter)
{
case "Lastname":
$selectedoption = "profile_name";
break;
case "Firstname":
$selectedoption="profile_first_name";
break;
case "Chooseafilter":
$selectedoption = "";
break;
}
$result = pg_query($db_con, "SELECT * FROM profile WHERE ".$selectedoption." LIKE'%$_POST[search_filter]%'");
$row = pg_fetch_assoc($result);
if (isset($_POST['submit']))
{
while($row = pg_fetch_assoc($result))
{
echo"<ul>
<form name='update' action='' method='POST'>
<li>Guest Last Name:</li>
<li><input type='text' name='profile_name_result' value='$row[profile_name]' /></li>
<li>Guest First Name:</li>
<li><input type='text' name='profile_first_name_result' value='$row[profile_first_name]' /></li>
<li><input type='submit' value='Update' name='update'></input></li>
...

inserting checkbox values to database

I have a php form with some textbox and checkboxes which is connected to a database
I want to enter all the details into the database from the form.All the textbox values are getting entered except the checkbox values.I have a single column in my table for entering the checkbox values and the column name is URLID.I want to enter all the selected checkbox(URLID)values to that single column only ,separated by commas.I have attached the codings used.can anyone find the error and correct me?
NOTE: (The URLID values in the form is brought from the previous php page.those codings are also included.need not care about it)
URLID[]:
<BR><?php
$query = "SELECT URLID FROM webmeasurements";
$result = mysql_query($query);
while($row = mysql_fetch_row($result))
{
$URLID = $row[0];
echo "<input type=\"checkbox\" name=\"checkbox_URLID[]\" value=\"$row[0]\" />$row[0]<br />";
$checkbox_values = implode(',', $_POST['checkbox_URLID[]']);
}
?>
$URLID='';
if(isset($_POST['URLID']))
{
foreach ($_POST['URLID'] as $statename)
{
$URLID=implode(',',$statename)
}
}
$q="insert into table (URLID) values ($URLID)";
You really should separate your model from the view. It's 2011, not 2004 ;o
if (isset($_POST['checkbox_URLID']))
{
// Notice the lack of '[]' here.
$checkbox_values = implode(',', $_POST['checkbox_URLID']);
}
$URLIDs = array();
while($row = mysql_fetch_row($result))
{
$URLIDs[] = $row[0];
}
foreach ($URLIDs as $id)
{
?>
<input type="checkbox" name="checkbox_URLID[]" value="<?php echo $id; ?>" /><?php echo $id; ?><br />
<?php
}
?>
<input type="submit"/>

How do I create this array? (PHP)

I am a little stuck on how to create this array.
My data:
category_id | category_name
1 bikes
2 cars
3 books
4 computers
Array:
$category=array();
$query = "SELECT * FROM categories ORDER BY name ASC";
$result = $db->query($query);
$category=array('category_id'=>$category_id, 'category_name'=>$category_name);
while ($row = $result->fetch_array()){
$category_id=$row['category_id'];
$category_name=$row['name'];
}
I want to create an array so that I can echo the data in a radio list like...
<input type='radio' value='<?PHP echo $category['category_id']; ?>'
name='category[]'><?PHP echo $category['category_name']; ?>
o bikes
o cars
o books
o computers
The problem is that the array only consists of one pair (1, bikes) and not all the data.
How can I make an array with all the data?
Thanks!
You are doing three things wrong, first you are not actually setting $category to equal anything - only the values of two undefined values, which default to null. So you end up with an array like:
array('category_id' => null, 'name' => null)
Second, you are doing nothing with the values of $category_id and $category_name when you do set them. Next, you are not going through the array item by item, you simply output the initial way it was set - which is linked to another problem that your array is short of a dimension. It should be 2-dimensional, not 1-dimensional.
This code sums up the gist of it all. I would suggest reading up on how arrays work in PHP and how to define them, they're a very commonly used data type throughout frameworks and the like.
$query = "SELECT * FROM categories ORDER BY name ASC";
$result = $db->query($query);
$categories=array();
while ($row = $result->fetch_array()){
$categories[] = array('category_id' => $row['category_id'], 'category_name' => $row['name']);
}
Then when you need to output:
foreach ( $categories as $category ) {
?>
<input type='radio' value='<?php echo $category['category_id']; ?>' name='category[]'><?php echo $category['category_name']; ?>
<?php
}
This can of course be cleaned up further.
That is because you are echoing out side of the loop there by giving you only first row records eg bikes, you should do like:
$category=array();
$query = "SELECT * FROM categories ORDER BY name ASC";
$result = $db->query($query);
$category=array('category_id'=>$category_id, 'category_name'=>$category_name);
while ($row = $result->fetch_array()){
$category_id=$row['category_id'];
$category_name=$row['name'];
?>
<input type='radio' value='<?PHP echo $category['category_id']; ?>'
name='category[]'><?PHP echo $category['category_name']; ?>
<?php
}
You are assigning to variables $category_id and $category_name, rather than to the array $category, so you're only seeing the first row returned from the query.
I normally use PDO, and would write it something like this:
<?php
$db = ...
$sql = 'SELECT * FROM categories ORDER BY category_name ASC';
$categories = $db->query($sql);
?>
<html>
<body>
<? foreach ($categories as $category): ?>
<input type="radio" name="category[]" value="<?= $category->category_id ?>">
<?= $category->category_name ?>
</input>
<? endforeach ?>
</body>
</html>

How to display mysql records as preselected checkboxes?

I have a table column called post_tags within a table called posts where assigned tags are stored separated by the # symbol. I also have a table called tags where all tag names are stored. I would like to design my database in a more normalized way but for the purpose I am trying to achieve this is the easiest option.
Anyway, I want to display on the screen all the entries from the tags table as checkboxes, so I do:
$query = mysql_query("SELECT * FROM tags ORDER BY name");
while ($row = mysql_fetch_assoc($query)) {
$tag = $row['name'];
echo "<input type='checkbox' name='tags[]' value='$tag' />\n";
}
Next I want to have the tags that are assigned to a particular post be preselected. For example, if I have a post with the following in it's post_tags column:
party#beaches#dolphins#
I want the "party", "beaches" and "dolphin" checkboxes to be checked by default (while the checkboxes for the other options are unchecked). How can this be done?
try the two results and the in_array() function.
<?php
$tags = mysql_query("SELECT * FROM tags ORDER BY name");
$post_tags = "party#beaches#dolphins#";
$arr_tags = explode("#", $post_tags);
while ($row = mysql_fetch_assoc($query)) {
$check = in_array($arr_tags, $row['name'])? 'checked="checked"' : "";
echo '<input type="checkbox" name="tags[]" value="'.$row['name'].'" '.$check.' />';
echo "\n";
}
?>
UPDATE
Because of Jeff question on performance, I looked for faster solutions and using isset() is faster so this would do a faster lookup of the values. the array_flip() is 3 time less taxing than in_array():
<?php
$tags = mysql_query("SELECT * FROM tags ORDER BY name");
$post_tags = "party#beaches#dolphins#";
$arr_tags = array_flip(explode("#", $post_tags));
while ($row = mysql_fetch_assoc($query)) {
$check = isset($arr_tags[$row['name']])? 'checked="checked"' : "";
echo '<input type="checkbox" name="tags[]" value="'.$row['name'].'" '.$check.' />';
echo "\n";
}
?>
The first thing to do is see if there is any existing data. So run that query and put the result of that table cell into lets say $checkedstring if not then put your default string in.
<?php
$checkedstring = "party#beaches#dolphins#";
//Pull from DB if exsists and set $checkedstring to that value
///
$checkeditems = explode ( "#" , $checkedstring);
$checked = array();
foreach($checkeditems as $item)
{
$checked[$item]=true;
}
$query = mysql_query("SELECT * FROM tags ORDER BY name");
while ($row = mysql_fetch_assoc($query))
{
$tag = $row['name'];
$checkedstatus = '';
if($checked[$tag])
{
$checkedstatus = "checked='checked'";
}
echo "<input type='checkbox' name='tags[]' value='$tag' $checkedstatus />\n";
}
?>

Categories