Querying MySQL with PHP and javascript drop down menu - javascript

I've looked all over for a few days now, but haven't found a solution to my problem. I'm writing some PHP to query from a MySQL database that I have setup on my WAMP server. I'm also learning PHP and HTML javascript as I go, so the syntax of both languages is still a little unfamiliar to me.
My goal is to have a drop down selector box is written in Java that allows the user to chose a filter to apply to the select query, something like this:
SELECT * from exampletable WHERE header = "selected_option"
Where 'exampletable' is the table existing in the SQL database, 'header' is a column within that table, and 'selected option' is the user's choice from the drop-down.
I have tried writing various HTML forms with actions that call the PHP file that contains the SQL query using the $_POST superglobal, but nothing seems to work. Any suggestions and examples of solutions would be amazing.
Thanks!
index.php (index.php is the front end with the user interface)
<!DOCTYPE HTML>
<html>
<form action="search.php" method="post">
<select name="family">
<option value="" selected="selected">Any family</option>
<option value="capacitory">capacitor</option>
<option value="resistor">resistor</option>
<option value="ferrite bead">ferrite bead</option>
</select>
<input name="search" type="submit" value="Search>
</form>
</html>
search.php (search.php receives the selected option value and passes it into the MySQL query)
<!DOCTYPE HTML>
<html>
<head>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
$con = mysqli_connect('localhost','root','kelly188','mysql');
mysqli_select_db($con,"testv2");
$varfam = $_POST['family'];
$query = "SELECT * FROM testv2 WHERE (family = $varfam)";
$result = mysqli_query($query);
if($result)
{
while ($row=mysql_fetch_array($result)){
echo "<tr>";
echo "<td>".$row['family']."</td>";
}
} else {
die(mysqli_error());
}
?>
</body>
</html>

You should use a prepared statement to prevent SQL injection. The mysql_fetch_array function has been removed from recent versions of PHP. Something more like the following would be more ideal.
if ($stmt = $con->prepare("SELECT * FROM testv2 WHERE (family = ?)")) {
$stmt->bind_param("s", $_POST['family']);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>".htmlentities($row['family'])."</td>";
echo "</tr>";
}
$stmt->close();
}
See PHP documentation: http://php.net/manual/en/mysqli.prepare.php

index.php
<form action="search.php" method="post">
<select name="family">
<option value="" selected="selected">Any family</option>
<option value="capacitory">capacitor</option>
<option value="resistor">resistor</option>
<option value="ferrite bead">ferrite bead</option>
</select>
<input name="search" type="submit" value="Search"/>
</form>
search.php
<?php
//////////////////////////////////
// Connect to database using PDO
$servername = "localhost";
$username = "test";
$password = "";
$dbname = "test_db";
$db_conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,$password);
// End of database connection
////////////////////////////////////
if(isset($_POST['search']))
{
$family = $_POST['family'];
if(empty($_POST['family']))
{
$stmt = $db_conn->prepare("SELECT * FROM testv2");
$stmt->execute();
//we get the data
while($data = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $data['family'];
echo "<hr>";
}
}
else
{
$stmt = $db_conn->prepare("SELECT * FROM testv2 WHERE family = :family");
$stmt ->bindParam(':family', $family);
$stmt->execute();
//we get the data
while($data = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo $data['family'];
echo "<hr>";
}
}
}
?>

Related

How do I display the HTML GET request data on the same HTML page, using a separate PHP file to fetch it?

I'm trying to get data from a MySQL database, that is being selected from a dropdown in an HTML file, and have the data display on the same HTML page that it is being selected from. I already have the HTML and PHP working to retrieve the data and display it, but it is not displaying on the same page that the user requests it from, it is displaying on the PHP page.
Here is the HTML code for get_project_form.html :
<html>
<head>
<title>Get Project Form</title>
<!--Link this html page to the project_style.css page-->
<link rel="stylesheet" type="text/css" href="project_style.css">
</head>
<body>
<div class="container">
<form action="get_project_action.php" autocomplete="off" method="get">
<label for="Query Selections">Query Selections : (You can only select
all data from "Projects"
for now):</label>
<select id="first_query" name="queries" required>
<option value="" disabled selected>Make a Selection</option>
<option value="Projects">Projects</option>
</select><br />
<input type="submit" value="Submit"><br />
</div>
</body>
</html>
After you make the selection and click submit the data appears on a page with the URL,
http://localhost:8015/get_project_action.php?queries=Projects
Here is the code for the php file get_project_action.php :
<?php
echo "<table style='border: solid 1px black;'>";
class TableRows extends RecursiveIteratorIterator
{
function __construct($it) {
parent::__construct($it, self::LEAVES_ONLY);
}
function current() {
return "<td style='width: 150px; border: 1px solid black;'>" .
parent::current() . "</td>";
}
function beginChildren() {
echo "<tr>";
}
function endChildren() {
echo "</tr>" . "\n";
}
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "pmo";
try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username,
$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$query = $_GET["queries"];
$stmt = $conn->prepare("SELECT * FROM $query");
$stmt->execute();
// set the resulting array to associative
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
foreach (new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as
$k => $v) {
echo $v;
}
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}
$conn = null;
echo "</table>";
?>
I'd like to keep the HTML and PHP separate if possible. But from what I'm reading I'm guessing that isn't possible. I'm hearing that its best to keep the logic in a separate PHP file but that its best to put the rest of the PHP that does the displaying in the HTML file and change the .html file to a .php instead. But I was hoping there is a way to have the data display in the get_project_form.html page below the form somewhere without combining any of the PHP inside the get_project_form.html file and changing it to a .php. If this is possible, please show me how. If not, please feel free to show me how to do whatever is considered good practice for displaying the data on a web page. Any help will be highly appreciated!
suppose in php file you are using $dropdownData array variable to store data from db.
//PHP file
<?php
//query to fetch data from db.
$dropdownData;
$this->view('get_project_form.html',$dropdownData);
?>
//Then use this array variable $dropdownData in ur HTML file with "for loop" to display
//HTML file
//you can also validate the $dropdownData if it's not empty; otherwise php will give error.
<select id="first_query" name="queries" required>
<option value="" disabled selected>Make a Selection</option>
<? foreach ($dropdownData as $val => $text) { ?>
<option value="<? echo $val; ?>" > <? echo $text;?> </option>
<? } ?>
</select>

How to work in php page with more mysql database connections in real-time

I have three mysql databases with same structure (same tables). Then I have one query, that return different results from each database.
I want have one php page, where I will have radiobutton, listbox, etc. (without submit button), where I will choose database (DB1/DB2/DB3) and then I will see the results according to the selected database (I want it in real-time, without submit button).
What I have:
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<?php
include_once ('connection_db_1.php');
?>
<body>
<form action="">
<select name="database">
<option value="DB1">DB1</option>
<option value="DB2">DB2</option>
<option value="DB3">DB3</option>
</select>
</form>
<?php
include ('queries.php');
$test_1 = mysqli_query($mysqli_db, $test);
echo "
<table>
<thead>
<tr>
<th>Column_1</th>
</tr>
</thead>";
while ($row = mysqli_fetch_array($test_1)) {
echo "<form method=\"post\"><tr>";
echo "<td>" . $row['Column_1'] . "</td>";
echo "</tr></form>";
}
echo "</table><br>";
mysqli_close($mysqli_db);
?>
</body>
</html>
queries.php
<?php
$test = "select Column_1 from TEST; ";
?>
connection_db_1.php
<?php
// Connection data
$servername = "servename";
$username = "username";
$password = "pasword";
$dbname = "dbname_1";
// Create connection
$mysqli_db = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($mysqli_db->connect_error) {
die("Connection failed: " . $mysqli_db->connect_error);
}
?>
connection_db_2.php
<?php
// Connection data
$servername = "servename";
$username = "username";
$password = "pasword";
$dbname = "dbname_2";
// Create connection
$mysqli_db = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($mysqli_db->connect_error) {
die("Connection failed: " . $mysqli_db->connect_error);
}
?>
I think, that I need some javascript/ajax solution, but I dont know how use it effectively.
Thank you for some advice.
Per now I can't see you showing any examples where you use or have implemented any ajax handler.
I could suggest you use either plain Javascript or jQuery (by including a javascript library, see her
What you could do, before considering implementing AJAX, is the following (it will include the database after first selection and form submission):
<?php
if (isset($_POST["database"])) {
$db = $_POST["database"];
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<?php
include_once("connection_db_" . $db . ".php"); /* This will include the selected connection */
?>
<body>
<form action="" method="post">
<select name="database">
<option value="1">DB1</option>
<option value="2">DB2</option>
<option value="3">DB3</option>
</select>
</form>
<?php
include('queries.php');
$test_1 = mysqli_query($mysqli_db, $test);
echo "
<table>
<thead>
<tr>
<th>Column_1</th>
</tr>
</thead>";
while ($row = mysqli_fetch_array($test_1)) {
echo "<form method=\"post\"><tr>";
echo "<td>" . $row['Column_1'] . "</td>";
echo "</tr></form>";
}
echo "</table><br>";
mysqli_close($mysqli_db);
?>
</body>
</html>
Are the databases on the same server? If so, you only need one connection to the server. You can make the query by adding the database name in the query:
select Column_1 from dbname_1.TEST
or
select Column_1 from dbname_2.TEST

Get data MySQL DB and display on in HTML

How would I code into my program using PHP/JavaScript and HTML/CSS to display data from a database I made in MySQL Monitor on the blue section below:
I made buttons that use PHP to go into the database and show the data on the HTML page:
HTML:
<form action="fullridez.php" method="post">
<h4 id="Filter">GPA</h4>
<input id="FilterBox" name="gpa" type="text"/>
<h4 id="Filter">Amount</h4>
<input id="FilterBox" name="amount" type="text"/>
<h4 id="Filter">School</h4>
<input id="FilterBox" name="school" type="text"/>
<input type="submit" id="FilterBox" name="myForm" onkeypress="checkEnter()" ><img src="search.png" width=15 height=15 /></button>
</form>
<script>
</script>
PHP:
<?php
if(isset($_POST['myForm'])) {
$servername = "localhost";
$username = "root";
$password = "";
$database = "scholarshiplist";
$conn = mysqli_connect($servername, $username, $password, $database);
$gpa = $_POST['gpa'];
$amount = $_POST['amount'];
$count = "SELECT * FROM scholarships";
$result = mysqli_query($conn, $count);
if ($result->num_rows > 0) {
$sql = "SELECT * FROM scholarships WHERE GPA <= " . $gpa . " AND Amount <= "
. $amount;
if ($result = mysqli_query($conn, $sql)) {
while ($row=mysqli_fetch_row($result)) {
for($i = 0; $i < count($row); $i++) {
echo $row[$i] . '<br>';
}
}
}
} else {
echo "0 results";
}
$conn->close();
}
SQL:
USE ScholarshipList;
CREATE TABLE Scholarships
(
id int unsigned NOT NULL auto_increment,
School varchar(500) NOT NULL,
GPA decimal(10,2) NOT NULL,
Amount decimal(10,2) NOT NULL,
PRIMARY KEY (id)
);
I am using XAMPP
When I click the button on the HTML file it bring me to the PHP page and all I see is the PHP code. I don't want it to go to the page but stay on the same page showing the data below the buttons.
This is what the page looks like so far
page
What am I doing wrong?
If your HTML form is contained within the 'fullridez.php' file and you are posting the form inputs to that same file, then you need to have some PHP where you'd like to output to be checking for results and then looping through those results while echoing them out:
<table>
<tr><td>Col 1</td><td>Col 2</td><td>Col 3</td></tr>
<?php
while($row = mysql_fetch_assoc($result))
{
echo "<tr><td>"
. $row['col_1'] . "</td><td>"
. $row['col_2'] . "</td><td>"
. $row['col_3'] . "</td></tr>";
}
?>
</table>
You can build a wireframe div table with for loop:
<?php
$num_rows = mysql_num_rows($result);
for ($i=0;$i<$num_rows;$i++) {
//loop through all rows of data
$row = mysql_fetch_assoc($result); // your data is now: $row['fieldName']
?>
<div>
GPA <input name="" value="<?php echo($row['gpa'])?>;" type="text">
AMOUNT <input name="" value="<?php echo($row['amount'])?>;" type="text">
SCHOOL <input name="" value="<?php echo($row['school'])?>;" type="text">
</div>
<?php
} //end of the loop
?>

Change SQL statement upon change on seclection

I have two divs.
First div
Has inputs like checkbox and select.
<div>Events Selection</div>
Events <input type="checkbox" id="Option-1" checked="true">
Leaves <input type="checkbox" id="Option-2" checked="true">
Meetings <input type="checkbox" id="Option-3" checked="true">
Travels <input type="checkbox" id="Option-4" checked="true">
<div>Station Selection</div>
<select id="Filters1">
<option value="0">All Stations</option>
<option value="1">Main Station</option>
<option value="2">Sub Station</option>
<option value="3">Sub Station Main Office</option>
</select>
Second div
Has a SQL statement $sql = "SELECT * FROM events"; which i want to echo all those checked and selected options from First div.
So, my question is how to dynamically change the SQL statement when the selections or checkbox changed in First div.
Like: When the page loads, it should be like this:
$sql = Select * From events Where (every checkboxes are
checked and `All Stations` are selected.)
and when a user wants to filter the result from First div then the $sql statement should be changed to what the user selected and checked.
Like: I want to check the Events and Meetings checkbox with Main Station selection, so now i want that the $sql statement should be change to my selection in the Second div.
At first use parameterized query's, don't construct them dynamically. Examples and explanation on MSDN.
Write stored procedure that will receive value of selected option and will bring you data you need. F.e.:
CREATE PROCEDURE dbo.getevents
#value int
AS
SELECT *
FROM events
WHERE somecolumn = #value
It is simplified version, I guess you need some if statement like IF #value = 0...SELECT this ... IF #value = 1
In that case you can use:
$sql = "EXEC dbo.getevents ?";
$stmt = sqlsrv_query($conn, $sql, array($value));
And then fetch results and show it on your page.
EDIT#1
Using XAMP and SQL Server 2014
Disclaimer: I post this code only for demonstration purpose. Parameters are passed as a string, no styling, maybe some mistakes.
I have an installed XAMP. Downloaded sqlsrv libraries, enable them in php.ini.
I got local SQL Server with database Test. SQL server has an instance named sqldev. My computer name is workshop. So, instead of SERVER\INSTANCE should be workshop\sqldev. Instead of DATABASE - Test. That is what I wrote to connect.
At first I create table like this:
CREATE TABLE dummy (
id int identity(1,1),
[Desc] nvarchar(max),
[Type] nvarchar(100)
)
INSERT INTO dummy VALUES
('Do something already','Events'),
('Congrats!','Events'),
('Meet up at six PM','Meetings'),
('To Amsterdam','Travels'),
('goodbye!','Leaves')
Table contains some dummy-data to play with.
The next step:
Download jQuery from https://jquery.com/download/ (I used jquery-3.1.1.js)
index.php
<html>
<head>
<script src="jquery-3.1.1.js"></script>
<style>
table {
width:20%
}
table, td, th {
border-collapse: collapse;
border: 1px solid gray;
}
</style>
</head>
<body>
<div>Events Selection</div>
Events <input type="checkbox" id="option" class="options" name="options[]" value="Events">
Leaves <input type="checkbox" id="option" class="options" name="options[]" value="Leaves">
Meetings <input type="checkbox" id="option" class="options" name="options[]" value="Meetings">
Travels <input type="checkbox" id="option" class="options" name="options[]" value="Travels">
<div id="response"></div>
<script>
$('input:checkbox').click(function() {
$.ajax({
url: "sql_page.php",
type: "post",
data: $('.options:checked').serialize(),
success: function(data) {
$('#response').html(data);
}
});
});
</script>
</body>
</html>
sql_page.php
<?php
header('Content-Type: text/html; charset=utf-8');
$serverName = "SERVER\INSTANCE";
$connectionInfo = array("Database"=>"DATABASE");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if(isset($_POST['options'])) {
if( $conn === false ) {
echo "Unable to connect.</br>";
die( print_r( sqlsrv_errors(), true));
}
$values = $_POST['options'];
$valuelist = "'" . implode("', '", $values) . "'";
$tsql = "SELECT * FROM dummy WHERE [Type] IN (".$valuelist.");";
$stmt = sqlsrv_query($conn, $tsql);
if( $stmt === false ) {
echo "Error in executing query.</br>";
die( print_r( sqlsrv_errors(), true));
}
echo "<table>";
while ($obj = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC)) {
echo "<tr>
<td>".$obj[0]."</td>
<td>".$obj[1]."</td>
<td>".$obj[2]."</td>
</tr>\n";
}
echo "</table>";
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn );
}
?>
Then I go on index.php in my browser:
If you are using MySQL you need another libraries and commands to use, but they are similar to what I wrote. The main idea is to connect to the database and run some query with parameters, it is a sql_page.php idea.
The index.php part sends Ajax request to sql_page.php when checkboxes are clicked. And then show the data from this page (that was got from SQL Server) in div with id=response.
EDIT#2
Using EasyPHP Devserver 16.1.1 dowloaded from here
I installed EasyPHP in default folder, start it, went to http://127.0.0.1:1111, started Apache + PHP on port 8888, started MySQL.
I create a DB named air-hr, table named events in it. The script and structure of table below:
CREATE TABLE `events` (
`eventid` int(11) NOT NULL,
`eventname` varchar(100) NOT NULL,
`eventcategory` varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `events` (`eventid`, `eventname`, `eventcategory`) VALUES
(1, 'Go now!', 'Leaves'),
(2, 'Meet some new people', 'Meetings'),
(3, 'Travel to Amsterdam', 'Travels'),
(4, 'PARTY HARD!', 'Events');
Also I create user test that can connect to DB and select from table.
I have created 2 files in C:\Program Files (x86)\EasyPHP-Devserver-16.1\eds-www project folder (their description is below) and copy jquery-3.1.1.js.
index.php like above and
sql_page.php
<?php
header('Content-Type: text/html; charset=utf-8');
if(isset($_POST['options'])) {
$values = $_POST['options'];
$valuelist = "'" . implode("', '", $values) . "'";
$query = "SELECT * FROM events WHERE eventcategory IN (".$valuelist.");";
$link = mysqli_connect("localhost", "test", "testpass", "air-hr");
if (!$link) {
echo "Error: Unable to connect to MySQL." . PHP_EOL;
echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
exit;
}
echo "<table>";
if ($result = mysqli_query($link, $query)) {
while ($row = mysqli_fetch_row($result)) {
echo "<tr>
<td>".$row[0]."</td>
<td>".$row[1]."</td>
<td>".$row[2]."</td>
</tr>\n";
}
mysqli_free_result($result);
}
echo "</table>";
mysqli_close($link);
}
?>
And results here:
Hope this helps you!
here you code
first named your inputs and select as follow:
<form action="sql_page.php" method="post">
<div>Events Selection</div>
Events <input type="checkbox" id="Option-1" name="Option-1" checked="true">
Leaves <input type="checkbox" id="Option-2" name="Option-2" checked="true">
Meetings <input type="checkbox" id="Option-3" name="Option-3" checked="true">
Travels <input type="checkbox" id="Option-4" name="Option-4" checked="true">
<div>Station Selection</div>
<select id="Filters1" name="Filters1">
<option value="0">All Stations</option>
<option value="1">Main Station</option>
<option value="2">Sub Station</option>
<option value="3">Sub Station Main Office</option>
</select>
<input type="submit" id="submit">
</form>
and in your sql_page.php here php code
if (isset($_POST)) {
foreach ($_POST as $col => $value) {
$whare .= "$col = '$value' AND ";
}
$whare = rtrim($whare,'AND ');
$sql = "Select * From events Where $whare";
}

autosubmit drop down value into database

i'm trying to auto submit the value of drop down menu using onchange=this.form.submit() into database but i couldn't make it work. can anyone please help me. any suggestions will be highly appreciated.
here is the code:
<?
require_once ('database.php');
?>
<form action="" method=post>
<select name="assignee" onchange="this.form.submit()">
<option value="0">Unassigned</option>
<?
$find_selected = mysql_query("select assign_to from orders where id = $id");
$asignee =mysql_fetch_row($find_selected);
$list=mysql_query("SELECT id, full_name from user where username <> 'root' and nature = 3");
while($row_list=mysql_fetch_assoc($list)){
?>
<option value="<? echo $row_list['id']; ?>"<? if($row_list['id']== $asignee['0']){ echo "selected"; } ?>><? echo $row_list['full_name'] ?></option>
<?
}
mysql_free_result($list);
mysql_free_result($find_selected);
?>
</select>
</form>
<?php
if(isset($_POST['submit'])){
$sql = "UPDATE `orders` SET `assign_to` = '{$_POST['assignee']}' WHERE `id` = '$id' ";
mysql_query($sql) or die(mysql_error());
}
?>
<?php
if(isset($_POST['assignee'])){
$sql = "UPDATE `orders` SET `assign_to` = '{$_POST['assignee']}' WHERE id=$id";
mysql_query($sql);
}
?>
You just defined your query but didn't executed it

Categories