How do I create this array? (PHP) - 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>

Related

Order list of options based on MySQL query - PHP

I am presenting a list of options to the user based on a database query. The results are being fetched correctly however they are currently unordered and I would like to display them in alphabetical order in the option list. I have tried several solutions so far with "ORDER BY" on the query level however with no success. Is there a simple way to achieve this? (The list contains 1000+ results) The code is as follows:
<?php
$user_id = $_SESSION['user_id'];
$sql = "SELECT * FROM add_bulding WHERE description<>''";
$query = $this->db->query($sql);
$building_title = $query->result_array();
?>
<div>
<select>
<option value="">Select Building</option>
<?php foreach ($building_title as $value) { ?>
<option value = "<?php echo $value['id']; ?>">
<?php echo $value['title']; ?>
</option>
<?php
}
?>
</select>
</div>
Try changing your query to:
$sql = "SELECT * FROM add_bulding WHERE description<>'' ORDER BY title DESC";
Sounds like you want a query like:
SELECT id, title FROM add_bulding WHERE description<> ORDER BY title desc
Alternately, you can sort it in php:
<?php
$tmp = array();
foreach ($building_title as $value){
$tmp[$value['id']] = $value['title'];
}
ksort($tmp);
foreach ($tmp as $k => $v) {
print "<option value=\"" + $k + "\">" + $v + "</option>\n";
}
?>
However, in either case, be sure to sanitize your values so you don't end up with XSS problems.
Try this query :
$sql = "SELECT * FROM add_bulding WHERE description<>'' ORDER BY title";
If you want to get title data with alphabetical order then you can write 'ASC' or do not need to write any after ORDER BY title.
But you want to get title data with descending order then you need to write 'DESC' after ORDER BY title
I hope you will get solution.

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>
...

PHP Form from Array Select Value Edit/Save

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'];

I'm having trouble getting categories and subcategories

Here's my database:
id name parent_id
1 Computers NULL
2 Apple 1
3 Books 1
4 Music NULL
5 CDs 4
6 Records 4
My categories function:
public function showCategories($parent_id = 0){
if($parent_id == 0){
$sql = "SELECT * FROM categories WHERE parent_id IS NULL";
} else {
$sql = "SELECT * FROM categories WHERE parent_id =:parentid";
}
$stmt = $this->db->prepare($sql);
$stmt->bindParam(':parentid', $parent_id);
$stmt->execute();
$categories = array();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
array_push($categories, array($row['id'] => $row['name']));
}
return $categories;
}
Here's my category page:
<?php
//Instantiate categories class
$categories = new categories($db);
$categoriesMain = $categories->showCategories(0);
?>
<html>
<head></head>
<body>
<form action="" method="post">
<?php //Get parent categories and put them into a select box ?>
<select name="categoriesMain">
<?php for($i=0;$i<count($categoriesMain);$i++){ ?>
<option value="<?php echo $i; ?>">
<?php echo $categoriesMain[$i]; ?>
</option>
<?php } ?>
</select>
<input type="submit" name="submit" value="submit"/>
</form>
<?php //if form submits then show sub categories ?>
<?php if(isset($_POST['submit'])){
$categoriesSub = $categories->showCategories($_POST['categoriesMain']);
for($i=0;$i<count($categoriesSub);$i++){
echo $categoriesSub[$i];
}
} ?>
</body>
</html>
Let me try to explain what im having trouble with. I think my whole design is out of place because it feels like that but im having a brain block at the moment.
In the function I'm returning an array like Array ( [0] => Array ( [1] => Computers ) [1] => Array ( [4] => Music ) ). If you think this is the wrong way to return it let me know. Ok then do you see CategoriesMain? I'm using a for loop to output this array and for option=value im echoing $i however this $i goes like 1, 2, 3, 4 however I want the value to be the value of the parent category e.g. 1, 4 so that I can collect the value using $_POST['cateogoriesMain'] in the next for loop where I'm displaying cateogriesSub where it will get the database rows for those with the parent_id = to whatever was selected in the selectbox previously. I hope it makes sense.
You should use the key of the array for the option value, like this:
<select name="categoriesMain">
<?php foreach ($categoriesMain as $k => $v) { ?>
<option value="<?php echo $k; ?>">
<?php echo $v; ?>
</option>
<?php } ?>
</select>
edit also change the following line inside the php function, instead of:
array_push($categories, array($row['id'] => $row['name']));
do
$categories[$row['id']] = $row['name'];

formatting mysql data for ouptut into a table

Following on from a question earlier today this answer was given to read the data into an array and separate it to print vehicle type and then some data for each vehicle.
<?php
$sql = "SELECT * FROM apparatus ORDER BY vehicleType";
$getSQL = mysql_query($sql);
// transform the result set:
$data = array();
while ($row = mysql_fetch_assoc($getSQL)) {
$data[$row['vehicleType']][] = $row;
}
?>
<?php foreach ($data as $type => $rows): ?>
<h2><?php echo $type?></h2>
<ul>
<?php foreach ($rows as $vehicleData):?>
<li><?php echo $vehicleData['name'];?></li>
<?php endforeach ?>
</ul>
<?php endforeach ?>
This is almost perfect for what I want to do but I need to print out two columns from the database ie ford and mondeo before going into the second foreach loop. I've tried print $rows['model'] and all the other combinations I can think of but that doesn't work. Any help much appreciated
I'm a bit confused by your question but the SELECT * in the SQL statement means that every column from the database should be present as a key=>value pair in the $row array. So if you needed another "column," output here into an HTML list element <li>, you just echo (note: not "print") that column name as an array key. So if you needed the type of the car column found in a column with the name "model" you'd do this:
<?php
$sql = "SELECT * FROM apparatus ORDER BY vehicleType";
$getSQL = mysql_query($sql);
// transform the result set:
$data = array();
while ($row = mysql_fetch_assoc($getSQL)) {
$data[$row['vehicleType']][] = $row;
}
?>
<?php foreach ($data as $type => $rows): ?>
<h2><?php echo $type?></h2>
<ul>
<?php foreach ($rows as $vehicleData):?>
<li><?php echo $vehicleData['name'];?></li>
<li><?php echo $vehicleData['model'];?></li>
<?php endforeach ?>
</ul>
<?php endforeach ?>
EDIT: I'm still unclear on your question, but if every car has the same vehicleType, and you're just looking to grab that once before looping through all the results, I'm guessing this will do it:
<?php
// Set up a SQL query to grab one row
$query_to_grab_only_vehicle_type = "SELECT vehicleType FROM apparatus WHERE 1 LIMIT 0,1";
// Fetch that row and turn it into an array
$vehicle_type_array = mysql_fetch_array(mysql_query($query_to_grab_only_vehicle_type));
// Initialize a variable with the array value that came from the vehicleType column
$vehicle_type = $vehicle_type_array['vehicleType'];
// You could uncomment and use the following to echo out the variable
// echo "Vehicle type: $vehicle_type";
$sql = "SELECT * FROM apparatus ORDER BY vehicleType";
$getSQL = mysql_query($sql);
// transform the result set:
$data = array();
while ($row = mysql_fetch_assoc($getSQL)) {
$data[$row['vehicleType']][] = $row;
}
?>
<?php foreach ($data as $type => $rows): ?>
<h2><?php echo $type?></h2>
<ul>
<?php foreach ($rows as $vehicleData):?>
<li><?php echo $vehicleData['name'];?></li>
<li><?php echo $vehicleData['model'];?></li>
<?php endforeach ?>
</ul>
<?php endforeach ?>

Categories