Displaying query results after submitting a PHP form - php

I am currently working on a school project using php and mysql. I have created a form with three drop down boxes where users select types of data they are looking for. However, I am having a lot of trouble displaying the results after the form is submitted. Here is my current code:
<?php
require_once 'connection.php';
?>
<form action="stats.php" method ="post">
<input type="hidden" name="submitted" value="true" />
<fieldset>
<legend>
Specify Date, Month, and County
</legend>
<p>
<label for="year">
Please select a year
</label>
<select name= 'year'>
<?php
$query = "select distinct year from unemployed";
$result = $conn->query($query);
while($row = $result->fetch_object()) {
echo "<option value='".$row->year."'>".$row->year."</option>";
}
?>
</select>
</p>
<p>
<label for="month">
Please select a month
<label>
<select name= 'month'>
<?php
$query = "select distinct month from unemployed";
$result = $conn->query($query);
while($row = $result->fetch_object()) {
echo "<option value='".$row->month."'>".$row->month."</option>";
}
?>
</select>
</p>
<p>
<label for="location">
Please specify a location
</label>
<select name='select'>
<?php
$query = "select * from unemployed";
$result = $conn->query($query);
while ($finfo = $result->fetch_field()) {
echo "<option value='".$finfo->name."'>".$finfo->name."</option>";
}
?>
</select>
</p>
<input type ="submit" />
</fieldset>
</form>
<?php
if (isset($_POST['submitted'])) {
include('connection.php');
$gYear = $_POST["year"];
$gMonth = $_POST["month"];
$gSelect = $_POST["select"];
$query = "select $gSelect from unemployed where year='$gYear' and month='$gMonth'";
$result = $conn->query($query) or die('error getting data');
echo"<table>";
echo "<tr><th>Year</th><th>Time</th><th>$gSelect</th></tr>";
while ($row = $result->fetch_object()){
echo "<tr><td>";
echo $row['Year'];
echo "</td><td>";
echo $row['Month'];
echo "</td><td>";
echo $row['$gSelect'];
echo "</td></tr>";
}
echo "</table";
} // end of main if statement
?>
I am almost certain my problem lies within my while statement. I get the titles of my table columns to show up (Year, Month, $gSelect), but I am not getting my query results to be displayed.
I have tried:
while ($row = $result->fetch_object())
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
Neither of these are working for me. I have looked at php.net for guidance. I am still confused with what to do. If anyone could help me, I would really appreciate it.

Always check your returns:
if( ! $result = $conn->query($query) ) {
die('Error: ' . $conn->error());
} else {
while($row = $result->fetch_object()) {
echo "<option value='".$row->year."'>".$row->year."</option>";
}
}
Also putting error_reporting(E_ALL); at the top of your script while you're developing it will help enormously as well.

You should really look into passing variables as parameters to your query instead of injecting them as variables directly into your query. This can lead to sql injection attacks.
Also, here's a quick example of how to write a query using PDO and mysql:
//Simple Query
$dbh = new PDO('mysql:host=localhost;dbname=testdb;charset=utf8', 'username', 'password');
//Useful during development.
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//mysql can have prepares depending on the version: http://stackoverflow.com/questions/10113562/pdo-mysql-use-pdoattr-emulate-prepares-or-not
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sth = $dbh->query("SELECT * FROM table");
var_dump($sth->fetchAll(PDO::FETCH_ASSOC));
//Now with pass params and a prepared statement:
$query = "SELECT * FROM table WHERE someCol = ?";
$sth = $dbh->prepare($query);
$sth->bindValue(1,"SomeValue");
$sth->execute();
$results = $sth->fetchAll(PDO::FETCH_ASSOC));

Related

PHP mySQL select via html select

I'm trying to do a select from a table based on the post value of an HTML select box. I'm getting no results at all, I'm echoing out the post value no problem. The statement works on it's own but won't when I use the select form to populate it. This is just my test I will be adding other options to the dropdown box.
<?php
if(isset($_POST['value'])) {
if($_POST['value'] == 'Militaria') {
$query = "SELECT * FROM listings WHERE category1=Militaria";
}
else {
// query to get all records
$query = "SELECT * FROM listings";
}
}
$sql = mysql_query($query);
while ($row = mysql_fetch_array($query)){
echo 'Description:' . $row['description'];
}
mysql_close($con);
?>
Here is the html form I'm using, can anyone tell me where I'm going wrong, should I do it a different way etc, I'm new to php? Thanks!!
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post' name='form_filter' >
<select name="value">
<option value="all">All</option>
<option value="Militaria">Militaria</option>
</select>
<br />
<input type='submit' value = 'Filter'>
</form>
mysql_fetch_array() should receive resorce as a parameter. Try mysql_fetch_array($sql).
Quote around 'Militaria' and mysql_fetch_array($sql)
<?php
if(isset($_POST['value'])) {
if($_POST['value'] == 'Militaria') {
$query = "SELECT * FROM listings WHERE category1='Militaria'";
}
else {
// query to get all records
$query = "SELECT * FROM listings";
}
$sql = mysql_query($sql);
while ($row = mysql_fetch_array($sql)){
echo 'Description:' . $row['description'];
}
mysql_close($con);
}
?>
<form action='<?php echo $_SERVER['PHP_SELF']; ?>' method='post' name='form_filter' >
<select name="value">
<option value="all">All</option>
<option value="Militaria">Militaria</option>
</select>
<br />
<input type='submit' value = 'Filter'>
</form>
You have two mistakes in your php code.
1st : quote around Militaria. The query should be, $query = "SELECT * FROM listings WHERE category1='Militaria'";
2nd : mysql_fetch_array accepts executed query's result as parameter. It should be, $row = mysql_fetch_array($sql)
Final code:
<?php
if(isset($_POST['value'])) {
if($_POST['value'] == 'Militaria') {
$query = "SELECT * FROM listings WHERE category1 = 'Militaria'";
}
else {
// query to get all records
$query = "SELECT * FROM listings";
}
}
$sql = mysql_query($query);
while ($row = mysql_fetch_array($sql)){
echo 'Description:' . $row['description'];
}
mysql_close($con);
?>

Fill drop down list on page load php

I have two input text fields where user has to specify the begin and end of the fly.
<input type="text" name="start" placeholder="Start destination">
<input type="text" name="end" placeholder="End destination">
I would like to change that and give user to chose start and end destination from database.
<select>
<option value="$id">$name</option>
</select>
I know how to get done if i read database and input values manually, but i know its posible if page loads and execute my SELECT QUERY.
So i have to create dropdown list and fill that with a values from database.
This dropdown list has to be filled when the page load.
Some idea for this ???
I am working with php.
Thank you in advance !!
EDIT : I get done this only with php.
<?php
$db_host = "localhost";
$db_username = "root";
$db_password = "";
$db_name = "flights";
$conn = mysql_connect("$db_host","$db_username","$db_password") or die ("no conn");
#mysql_select_db("$db_name") or die ("no database");
if ($conn = true) {
// echo "";
}
//cyrilic
$sql = "SET NAMES 'utf8'";
mysql_query($sql);
//query for end
$sql="SELECT Distinct end from flights_table;";
$result=mysql_query($sql);
echo "<select name=\"city\">";
echo "<option>end destination</option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value='".$row['end']."'>".$row['end']." </option>";
}
echo "</select>";
?>
This php fires when page loads. Those select options i have putted in a form, and when form is submited, it fires php itself. I am getting selected options this way :
$startfly=$_POST['end'];
I am doing this for starting the flight :)
Thank you guys !
Try this :
At the top of page include your database connection file :
<?php
require "connection.php";
?>
Then :
<?php
$selectStart = "Start : <select name='start'>";
$selectEnd = "End : <select name='end'>";
$query = mysql_query("SELECT * FROM someTable ORDER BY dateField ASC");
if(mysql_num_rows($query) > 0)
{
while($row = mysql_fetch_assoc($query))
{
$selectStart .= "<option value='".$row['startItem']."'>".$row['startItemName']."</option>";
$selectEnd .= "<option value='".$row['endItem']."'>".$row['endItemName']."</option>";
}
}
$selectStart = "</select>";
$selectEnd = "</select>";
?>
In your HTML :
<form action='destinationPage.php' method='post'>
<?php
echo $selectStart;
echo $selectEnd;
?>
<input type='submit' value='Submit' />
</form>

MySQL search enquiry error

I am trying to create a form which allows the user to search for an event using the Venue and category fields which are scripted as dropdown boxes and the Price and finally by event title, as shown via the code if a keyword is entered which matches the fields on the database it should output all the related information for that event if any matches have been made on either search fields, but it seems to output every single event from the database no matter what I type in the search field.
DATABASE: http://i.imgur.com/d4uoXtE.jpg
HTML FORM
<form name="searchform" action ="PHP/searchfunction.php" method = "post" >
<h2>Event Search:</h2>
Use the Check Boxes to indicate which fields you watch to search with
<br /><br />
<h2>Search by Venue:</h2>
<?php
echo "<select name = 'venueName'>";
$queryresult2 = mysql_query($sql2) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult2)) {
echo "\n";
$venueID = $row['venueID'];
$venueName = $row['venueName'];
echo "<option value = '$venueID'";
echo ">$venueName</option>";
}# when the option selected matches the queryresult it will echo this
echo "</select>";
mysql_free_result($queryresult2);
mysql_close($conn);
?>
<input type="checkbox" name="S_venueName">
<br /><br />
<h2>Search by Category:</h2>
<?php
include 'PHP/database_conn.php';
$sql3 ="SELECT catID, catDesc
FROM te_category";
echo "<select name = 'catdesc'>";
$queryresult3 = mysql_query($sql3) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult3)) {
echo "\n";
$catID = $row['catID'];
$catDesc = $row['catDesc'];
echo "<option value = '$catID'";
echo ">$catDesc </option>";
}
echo "</select>";
mysql_free_result($queryresult3);
mysql_close($conn);
?>
<input type="checkbox" name="S_catDes">
<br /><br />
<h2>Search By Price</h2>
<input type="text" name="S_price" />
<input type="checkbox" name="S_CheckPrice">
<br /><br />
<h2>Search By Event title</h2>
<input type="text" name="S_EventT" />
<input type="checkbox" name="S_EventTitle">
<br /><br />
<input name="update" type="submit" id="update" value="Search">
searchfunction.php file
<?php
$count = 0;
include 'database_conn.php';
$venuename = $_REQUEST['venueName']; //this is an integer
$catdesc = $_REQUEST['catdesc']; //this is a string
$Price = $_REQUEST['S_price'];
$EventT = $_REQUEST['S_EventT'];
$sql = "select * FROM te_events WHERE venueID LIKE '%$venuename%' OR catID LIKE '%$catdesc%' OR eventPrice LIKE '%Price%' OR eventTitle LIKE '%$EventT%'";
$queryresult = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult))
{
echo $row['eventTitle'];
echo $row['eventDescription'];
echo $row['venueID'];
echo $row['catID'];
echo $row['eventStartDate'];
echo $row['eventEndDate'];
echo $row['eventPrice'];
}
mysql_free_result($queryresult);
mysql_close($conn);
?>
The query should be
$sql = "select * FROM te_events
WHERE (venueID LIKE '%$venuename%'
OR catID LIKE '%$catdesc%'
OR eventPrice LIKE '%$Price%'
OR eventTitle LIKE '%$EventT%')
;
To get values from the form submitted with method POST we use $_POST to access form data and not $_REQUEST:
$venuename = $_POST['venueName']; //this is an integer
$catdesc = $_POST['catdesc']; //this is a string
$Price = $_POST['S_price'];
$EventT = $_POST['S_EventT'];
That was about your problem - now some important notes:
Do not use mysql extension as it's deprecated. Read this official documentation.
Use mysqli and prevent SQL injections by using prepared queries and parameters like in official documentation again.
Since you are matching on any fields surrounded by wildcards, if any of the fields are blank, then the MySQL query will match all rows.
Also, you need to prevent MySQL injection. Otherwise, your MySQL table will eventually be hacked.
By the way, the code eventPrice LIKE '%Price%' is invalid and is missing a dollar sign.
Lastly, the mysql extension has been deprecated. I would recommend using mysqli instead as it is fairly similar.

Can't display data from my database

I am trying to allow users to select restrictions from my database by using 3 drop down boxes. I have set them up and I have connected to my database. However, once the user hits the submit button, I can't get data to be displayed in a table. Here is my code:
<?php
require_once 'connection.php';
?>
<form action="stats.php" method ="post">
<input type="hidden" name="submitted" value="true" />
<fieldset>
<legend>
Specify Date, Month, and County
</legend>
<p>
<label for="year">
Please select a year
</label>
<select name= 'year'>
<?php
$query = "select distinct year from unemployed";
$result = $conn->query($query);
while($row = $result->fetch_object()) {
echo "<option value='".$row->year."'>".$row->year."</option>";
}
?>
</select>
</p>
<p>
<label for="month">
Please select a month
<label>
<select name= 'month'>
<?php
$query = "select distinct month from unemployed";
$result = $conn->query($query);
while($row = $result->fetch_object()) {
echo "<option value='".$row->month."'>".$row->month."</option>";
}
?>
</select>
</p>
<p>
<label for="location">
Please specify a location
</label>
<select name='select'>
<?php
$query = "select * from unemployed";
$result = $conn->query($query);
while ($finfo = $result->fetch_field()) {
echo "<option value='".$finfo->name."'>".$finfo->name."</option>";
}
?>
</select>
</p>
<input type ="submit" />
</fieldset>
</form>
<?php
if (isset($_POST['submitted'])) {
include('connection.php');
$gYear = $_POST["year"];
$gMonth = $_POST["month"];
$gSelect = $_POST["select"];
$query = "select $gSelect from unemployed where year='$gYear' and month='$gMonth'";
$result = $conn->query($query) or die('error getting data');
echo"<table>";
echo "<tr><th>Year</th><th>Time</th><th>$gSelect</th></tr>";
while ($row = $result->fetch_object()){
echo "<tr><td>";
echo $row['Year'];
echo "</td><td>";
echo $row['Month'];
echo "</td><td>";
echo $row['$gSelect'];
echo "</td></tr>";
}
echo "</table";
} // end of main if statement
?>
I can't get the data to be displayed in a table at all. I have tried multiple ways, but I am still getting errors. To ensure that I am connected to my database, I used var_dump($row) to make sure, and that worked okay. So that is not the problem. Does anyone have any idea what is wrong with my code?
When you retrieve the data from your result set you're fetching it as an object:
while ($row = $result->fetch_object()){
But when you come to display it, you refer to it as an array:
echo "<tr><td>";
echo $row['Year']; // array syntax.
You should be using object syntax:
echo "<tr><td>";
echo $row->Year; // object syntax.
If you check your error logs you should see a lot of messages to this effect.

Delete button after every post (php, sql)

I need some help with PHP and SQL. Im doing a website where you can post notes in different subjects (Work, Home, School, and so on). After every note that being selected from my database I want a button that can delete that specific post when it's not needed anymore. I can make it delete but is deletes wrong note, always the one above or below. I don't know whats wrong with my code? Please help me.
<?php
$query = "SELECT * FROM notes WHERE subject='Work' order by id desc";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$subject = $row['subject'];
$date = $row['date'];
$note = $row['note'];
print "<p><strong>$subject</strong> ($id), $date </p>";
print "<p> $note </p>";
?>
//delete button starts here here
<form id="delete" method="post" action="">
<input type="submit" name="delete" value="Delete!"/>
<?php
if(isset($_POST['delete'])){
$query = "DELETE FROM notes WHERE id=$id";
$result = mysql_query($query);
}
?>
</form>
<?php
}
?>
And when I press delete I get this:
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/mirho663/www-pub/webbpage/menu2.php on line 40
What does that mean and how do I fix it?
I updated your script below, try it if it works.
<?php
if(isset($_POST['delete'])){
$id = $_POST['delete_rec_id'];
$query = "DELETE FROM notes WHERE id=$id";
$result = mysql_query($query);
}
$query = "SELECT * FROM notes WHERE subject='Work' order by id desc";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$subject = $row['subject'];
$date = $row['date'];
$note = $row['note'];
print "<p><strong>$subject</strong> ($id), $date </p>";
print "<p> $note </p>";
?>
//delete button starts here here
<form id="delete" method="post" action="">
<input type="hidden" name="delete_rec_id" value="<?php print $id; ?>"/>
<input type="submit" name="delete" value="Delete!"/>
</form>
<?php
}
?>

Categories