Dynamic MySQL query depending on dynamic PHP dropdown - php

I am looking for help with how to fetch different MySQL queries from database depending on the dynamic PHP dropdown. Below is everything I have done so far (1. created Database, 2. created PHP dynamic dropdown, 3. the struggle part - how to get the HTML/PHP form change it´s MySQL query depending on the dynamic drop-down selected in step 2).
Here is my Create Database:
CREATE TABLE computers (
id int(3) NOT NULL auto_increment primary key,
pc_make varchar(25) NOT NULL default '',
pc_model varchar(25) NOT NULL default ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO computers VALUES (1, 'Dell', 'Latitude');
INSERT INTO computers VALUES (2, 'Dell', 'Inspiron');
INSERT INTO computers VALUES (3, 'HP', 'Pavilion');
INSERT INTO computers VALUES (4, 'HP', 'Spectre');
INSERT INTO computers VALUES (5, 'Lenovo', 'Thinkpad');
INSERT INTO computers VALUES (6, 'Lenovo', 'Ideapad');
Here is the part that produces the dynamic drop-down (it gives me the result of 3 distinct records: "Dell", "HP" and "Lenovo"):
<?
$connect = mysqli_connect('localhost', '', '', '');
$sql="SELECT DISTINCT(pc_make) AS pc_make FROM computers ORDER BY pc_make ASC";
$result = mysqli_query($connect, $sql);
if(mysqli_num_rows($result) > 0){
$output= '<select name="listofpcmakes">';
while($rs = mysqli_fetch_array($result)){
$output.='<option value="'.$rs['id'].'">'.$rs['pc_make'].'</option>';
}
}
$output.='</select>';
echo $output;
?>
And below is my attempt to display only the records that match the selected pc_make (for instance Dell, which should result in 2 records) from the dynamically created dropdown. Looks like I am only hitting the wall here.
<html>
<body>
<form id="my_form" name="my_form" method="post">
<table class="table">
<thead>
<tr>
<th>id</th>
<th>pc_make</th>
<th>pc_model</th>
</tr>
</thead>
<tbody>
<?PHP
$sql_final="SELECT * FROM computers WHERE pc_make = (how to capture the 'selected pc_model' from the dynamically generated dropdown???) ";
$result_final = mysqli_query($connect, $sql_final);
while ($myrow = mysqli_fetch_array($result_final))
{
?>
<tr>
<td><?PHP echo $myrow["id"]; ?></td>
<td><?PHP echo $myrow["pc_make"]; ?></td>
<td><?PHP echo $myrow["pc_model"]; ?></td>
</tr>
<?PHP
}
?>
</body>
</html>
To restate the issue, how should I build the HTML form part, which only fetches records (pc_make, pc_model) for a single manufacturer (Dell, HP, or Lenovo) which is selected from the dynamically generated dropdown. I am trying to avoid creating static mysql queries, since the manufacturers list may considerably change in the future.
Thanks all in advance for providing helping hand...

When you select an option from your dropdown and submit the form, the result will be in $_POST superglobal. So, you need to check $_POST and retrieve the value of your dropdown.
At the top of the page:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$selected_pc_model = $_POST['listofpcmakes'];
}
You can now use $selected_pc_model in your SQL query:
$sql_final="SELECT * FROM computers WHERE pc_make = $selected_pc_model";
A more complete example using the code you submitted above:
<?php
if (($_SERVER['request_method']) == 'POST') { // Checking to see if form is submitted
$selected_pc_model = $_POST['listofpcmakes']; // Getting the selected PC model value
}
?>
<html>
<body>
<form id="my_form" name="my_form" method="post">
<table class="table">
<thead>
<tr>
<th>id</th>
<th>pc_make</th>
<th>pc_model</th>
</tr>
</thead>
<tbody>
<?php
if (isset($selected_pc_model)) { // if there is a $selected_pc_model
$sql_final="SELECT * FROM computers WHERE pc_make =" . $selected_pc_model;
$result_final = mysqli_query($connect, $sql_final);
while ($myrow = mysqli_fetch_array($result_final)) {
?>
<tr>
<td><?PHP echo $myrow["id"]; ?></td>
<td><?PHP echo $myrow["pc_make"]; ?></td>
<td><?PHP echo $myrow["pc_model"]; ?></td>
</tr>
<?php
}
} else { // else if there is NOT a $selected_pc_model
echo '<tr>
<td>Error: PC Model is not selected.</td>
</tr>';
}
?>
</tbody>
</table>
</body>
</html>
There is more to do when you write this kind of code such as data validation and error checking etc., but this should be enough to get you going. For more, you should read PHP tutorials and/or get a couple of courses.

Related

Table data is not arranged

as i am a beginner so i want to ask how can i run the multiple queries using PHP for the same row to have multiple data in the table in html. i have tried many attempts but nothing worked i am using MYSQL as backend. I know that i have not written code for the first row and second column i.e. the second <td> on wicket keeper but the thing is that i want all rounder data to come in the second <td> of wicket keeper section. when running this code it is providing the output fine for wicket keeper but for all rounder column the data is starting after the end of wicket keeper data. i know why this problem is occurred but how can i solve this please tell??
CODE HERE:
<?php
$sql="select * from teams where role = 'WicketKeeper'";
$result=mysqli_query($conn,$sql) or die(mysqli_error());
while($row=mysqli_fetch_assoc($result)){
?>
<tr>
<td><?php echo $row["name"] ?></td>
<td></td>
<td></td>
<td></td>
</tr>
<?php } ?>
<?php
$sql="select * from teams where role = 'AllRounder'";
$result=mysqli_query($conn,$sql) or die(mysqli_error());
while($row=mysqli_fetch_assoc($result)){
?>
<tr>
<td></td>
<td><?php echo $row["name"] ?></td>
<td></td>
<td></td>
</tr>
<?php } ?>
Here is a good way to generate the rows of the display you showed.
First, use this query:
SELECT name, role FROM teams ORDER BY role DESC;
It generates rows in the order you want them, wicketkeepers first.
Then, use this php code to generate your display.
<?php
$sql="SELECT name, role FROM teams ORDER BY role DESC";
$result=mysqli_query($conn,$sql) or die(mysqli_error());
while($row=mysqli_fetch_assoc($result)){
$role = $row["role"];
$name = $row["name"];
$wicketkeeper = $role == "WicketKeeper" ? $name : "";
$allrounder = $role == "AllRounder" ? $name : "";
?>
<tr>
<td><?php echo $wicketkeeper ?></td>
<td><?php echo $allrounder ?></td>
<td></td>
<td></td>
</tr>
<?php } ?>
This renders the rows in the result set from your query, placing names in columns according to their roles.
In the general case, this task is known as pivoting a table.
Pro tip 1 Try to avoid SELECT * in queries. Instead give the names of the columns you need. This makes your code easier for a stranger to read, and it may make your queries run faster.
Pro tip 2 Anytime you catch yourself reusing the same query where it only varies by a WHERE clause, try to use a single query. This can make your application run faster.

Codeigniter: Move one row from one table to another at one time

I'm kinda stuck here! I have to two tables free_members and domstic_members and I need to move selected rows from free_members tables to the domestic_members table. why I'm saying selected rows because of I at the end of every row in free_members tables there is an upgrade option which will move that row to the domestic_members table. I have the code but it's not working the way I want. right now what is happening is when I click on upgrade option it just copies the whole table records and sends it's to the other table. this here is the code
Controller
function upgradeprofile() {
// $this->load->database();
$this->load->model('freemember_model');
$this->freemember_model->upgrade();
}
model
function upgrade() {
$query = $this->db->get('free_members');
foreach ($query->result() as $row) {
$this->db->where('id', $member_id);
$this->db->insert('domestic_members', $row);
}
}
View
<center> Search Member:
<input type="text" name ='search' id='search' placeholder="Search a member"/></center>
<input type="hidden" name ='limit_from' id='limit_from'/>
</form>
<br><center><button type="button" onclick="CallPrint1('background12')">Print</button>
<div id="background12" class="box-body">
<table id="example1" class="table table-bordered table-striped">
<thead>
<tr>
<th>Sr#</th>
<th><center>Full Name</th>
<th><center>Mobile Number</th>
<th><center>Membership# / CNIC</th>
<th><center>Email Address</th>
<th><center>Province</th>
<th><center>District</th>
<th><center>Tehsil</th>
<th><center>Union Council</th>
<?php /*?> <?php if($sessiondata['deletemembers']):?><?php */?>
<?php if($sessiondata['username'] != 'bilal.sabir'):?>
<th><center>Delete</th>
<?php endif;?>
<?php /*?><?php if($sessiondata['data_modification'] && $sessiondata['username'] != 'bilal.sabir' ):?><?php */?>
<?php if($sessiondata['username'] != 'bilal.sabir'):?>
<th><center>Print</th>
<th><center>Edit</th>
<th><center>Change Pwd</th>
<th><center>Upgrade</th>
<?php endif;?>
</tr>
</thead>
<tbody>
<?php $sr=0;?>
<?php foreach ($freemembers as $member): ?>
<tr><td><center><?php echo $sr+=1; ?></td><td><center><?php echo $member->first_name; ?></td>
<td><center><?php echo $member->mobile; ?></td><td><center><?php echo $member->cnic; ?></td>
<td><center><?php echo $member->email; ?></td>
<td><center><?php echo $member->province; ?></td><td><center><?php echo $member->district; ?></td><td><center><?php echo $member->tehsil; ?></td><td><center><?php echo $member->uc; ?></td>
<?php /*?> <?php if($sessiondata['deletemembers']):?><?php */?>
<?php if($sessiondata['username'] != 'bilal.sabir'):?>
<td><center>delete</td>
<?php endif;?>
<?php /*?><?php if($sessiondata['data_modification'] && $sessiondata['username'] != 'bilal.sabir' ):?><?php */?>
<?php if($sessiondata['username'] != 'bilal.sabir'):?>
<td><center>print</td>
<td><center>edit</td>
<td><center>change pwd</td>
<td><center>Upgrade</td>
<?php endif;?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
this is the view of my table free_members
Based upon your View, you have this...
index.php/admin/upgradeprofile/" . $member->id
So if $member->id = 100 the url will be
index.php/admin/upgradeprofile/100
So you are passing a member_id as mentioned in your model code BUT you are not getting it nor are you using the where correctly.
So you need to get a handle on the member_id...
This is ONE Solution/idea...This relies on you providing a correctly validated integer... You need to always Check/validate your inputs...
Controller
function upgradeprofile($member_id) {
// Need to check that $member_id is an integer
// To be added by the OP
$this->load->model('freemember_model');
// $member_id is passed in via the URL.
$this->freemember_model->upgrade($member_id);
}
Model
function upgrade() {
// Which member do we want to get from the free_members Table?
$this->db->where('id', $member_id);
$query = $this->db->get('free_members');
// Did we get a result? i.e was a valid member id passed in?
if($query !== false) {
$row = $query->row();
$this->db->insert('domestic_members', $row);
} else {
// Do nothing or handle the case where an illegal number was used...
}
}
Note: This code is not tested and is only to be used as a guide.
It can be refactored a number of ways but I am trying to keep it simple for now.
So please, do not just copy and paste this without at least "thinking" about what you are trying to do and how the code might be written to achieve it.
The main points here are...
1. You have to use a member id of some kind so you can retrieve the record for the free member so you can insert it into the other table.
2. You are providing this "member id" in the url so you need to extract it.
3. You can do that by either setting it as a parameter in the method being called... Or you can use segments ( look it up ).
So once you have the member id you can fetch the free member entry and insert it into the other table BUT What do you want to happen to the entry in the free members table because that is still going to be there and now you have two copies of the same information... Delete it?
If you need further explanation - ask.
One last point.
You should be making sure you fully understand what is you are doing and not just doing it because someone said to or you thought it was a good idea... Have a Good Reason and think of the implications...
I'm not familiar with Codeigniter but MySQL syntax should be this:
INSERT INTO table1 (table1.row1, table1.row2)
SELECT table2.row1, table2.row2
FROM table2
WHERE PUT_YOUR_CONDITION_IF_NEEDED
I've found this for Codeigniter.

MySQL, PHP: Display MySQL table in HTML table

sorry, I'm still very novice with server-side (back-end) development, thank you for helping in advance.
Recently, I've been developing a web page which you can choose which table you want to display from the mySQL server, then it will create an editable table in HTML using the mySQL table data.
So far, I'm only able to fetch which table to get from mySQL and display it using in the form of an array, which doesn't really look that great.
I wonder if you can display the array in a form of an editable table without knowing the how many columns, column names as it is different for every different table.
Later on, I have to upload the cell that is updated back to mySQL database and I've no idea how to do that as well.
Sorry for the trouble, this website had been a great help for me and the community is great. Thanks a lot!
Image of what I have so far:
Code I have so far:
SelectTable:
<div class="table-responsive">
<b>List of Tables</b>
<table class="table table-condensed selection_table">
<tbody>
<tr>
<?php
if ($tableResult = mysqli_query($conn,"show tables")){
while($table = mysqli_fetch_array($tableResult)) {
echo("<tr> <td>". "<a class = 'list_tables' href = ?clickedTable=$table[0]>". $table[0] . "</a>" ."</td> </tr>");
}
}else{
die("<b>"."No Table in Database!"."</b>");
}
if (isset($_GET['clickedTable'])){
$selectedTable = $_GET["clickedTable"];
}
?>
</tr>
</tbody>
</table>
</div>
Fetch array from selected table:
<?php
if (isset($_GET['clickedTable'])){
echo("<b> Current Table is: </b> ".$selectedTable. "<br/>");
$query = "SELECT * FROM $selectedTable";
if ($result = mysqli_query($conn , $query)) {
while ($row = mysqli_fetch_array($result)){
print_r($row);
}
}
}else{
echo("Please select a table");
}
?>

Making a HTML table based on SQL data in PHP

I am trying to make a dynamic HTML table with PHP, populating it with data from MySQL database. So far I have tried the while loop, but the result ends up in displaying the same first row it gets multiple times.
<div class = "container">
<p>Registered companies:</p>
<table border = "1px" align = "left">
<tr>
<th>Username</th>
<th>Company name</th>
<th>Company value1</th>
<th>Company value2</th>
</tr>
<?php
$compRowIncrement = 0;
while ($compRowIncrement < $companyRowCount) {
?>
<tr>
<td><?php echo $companyRow['user_name']?></td>
<td><?php echo $companyRow['company_name']?></td>
<td><?php echo $companyRow['company_value1']?></td>
<td><?php echo $companyRow['company_value2']?></td>
</tr>
<?php
$compRowIncrement++;
}
?>
</table>
</div>
It should display 3 rows of data for example (SQL query returns 3 different values). But so far I have achieved to get 3 rows (like I need) with the same data (first value it gets from the database).
How do I do it so each table row is populated with different data, as it is in the database.
I'm just learning, so if you don't mind ignore the css values in table :).
EDIT1 (Added query)//
$getPlayerCompanies = $MySQLi_CON -> query("SELECT DISTINCT *
FROM companies
LEFT JOIN player ON companies.player_id = player.player_id
LEFT JOIN users ON users.user_id = player.user_id
WHERE users.user_id =".$_SESSION['userSession']);
$companyRow = $getPlayerCompanies -> fetch_array();
$companyRowCount = $getPlayerCompanies -> num_rows;
Following query currently returns 3 rows, like it should.
where did the $companyRow values get populated?
I belive your code should be more like this (or with mysqli commands)
<?php
while ($companyRow = $getPlayerCompanies -> fetch_array() )
{
?>
<tr>
<td><?php echo $companyRow['user_name']?></td>
...
</tr>
<?php
}
?>

Inserting specific values into a DB, and displaying it on a table?

I'm trying to insert specific values(knife, and blanket) into a Database, but's not inserting into the DB/table at all. Also, I want to display the inserted values in a table below, and that is not working as well. It is dependant on the insert for it to show on the table. I am sure, because I inserted a value through phpmyAdmin, and it displayed on the table. Please, I need to fix the insert aspect.
The Insert Code/Error Handler
<?php
if (isset($_POST['Collect'])) {
if(($_POST['Object'])!= "knife" && ($_POST['Object'])!= "blanket")
{
echo "This isn't among the room objects.";
}else {
// this makes sure that all the uses that sign up have their own names
$sql = "SELECT id FROM objects WHERE object='".mysql_real_escape_string($_POST['Object'])."'";
$query = mysql_query($sql) or die(mysql_error());
$m_count = mysql_num_rows($query);
if($m_count >= "1"){
echo 'This object has already been taken.!';
} else{
$sql="INSERT INTO objects (object)
VALUES
('$_POST[Object]')";
echo "".$_POST['object']." ADDED";
}
}
}
?>
TABLE PLUS EXTRA PHP CODE
<p>
<form method="post">
</form>
Pick Object: <input name="Object" type="text" />
<input class="auto-style1" name="Collect" type="submit" value="Collect" />
</p>
<table width="50%" border="2" cellspacing="1" cellpadding="0">
<tr align="center">
<td colspan="3">Player's Object</td>
</tr>
<tr align="center">
<td>ID</td>
<td>Object</td>
</tr>
<?
$result = mysql_query("SELECT * FROM objects") or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
// Print out the contents of each row into a table?>
<tr>
<td><label for="<?php echo $row['id']; ?>"><?php
$name2=$row['id'];
echo "$name2"; ?>
</label></td>
<td><? echo $row['object'] ?></td>
</tr>
<?php }// while loop ?>
</table>
</body>
if(($_POST['Object'])!= knife || ($_POST['Object'])!= blanket)
THese value knife and blanket are string. So you may need to use quotes around them to define them as string, or php won't understand ;)
If the primary key of Objects is id and it is set to auto-increment
$sql = "INSERT INTO objects SET id = '', object = '".$_POST['Object']."'";
try
$sql= "INSERT INTO objects(object) VALUES ('".$_POST['Object'].")';
and you should probably put an escape in there too
You insert query is nor correct.
$sql = "INSERT INTO objects (id, object) values('','".$_POST['Object']."') ";
and this code
if(($_POST['Object'])!= "knife" || ($_POST['Object'])!= "blanket")
{
echo "This isn't among the room objects.";
}
will always be executed value of object is knife or blanket, because a variable can have one value. You must use
if(($_POST['Object'])!= "knife" && ($_POST['Object'])!= "blanket")
{
echo "This isn't among the room objects.";
}
Your SQL syntax is wrong. You should change the:
INSERT INTO objects SET id = '', object = '".$_POST['Object']."'
to
INSERT INTO objects ( id, object ) VALUES ('', '".$_POST['Object']."'
If you want your inserts to also replace any value that might be there use REPLACE as opposed to INSERT.

Categories