MySQL search enquiry error - php

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.

Related

How do I run multiple SQL Queries using "if(isset($_POST['Submit'])){"

Trying to make a CRUD, everything works except my Update function. I feel like the problem is in the second sql query. When I click on submit it just refreshes and the change is gone. Can anyone show me how to find what I need to change/show me what to change?
<head>
<title>Update</title>
</head>
<body>
</form>
<?php
require_once('dbconnect.php');
$id = $_GET['id'];
$sql = "SELECT * FROM dealers where ID=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<form action="" method="post">';
echo "Company: <input type=\"text\" name=\"CName\" value=\"".$row['CName']."\"></input>";
echo "<br>";
echo "Contact: <input type=\"text\" name=\"Contact\" value=\"".$row['Contact']."\"></input>";
echo "<br>";
echo "City: <input type=\"text\" name=\"City\" value=\"".$row['City']."\"></input>";
echo "<br>";
echo "<input type=\"Submit\" = \"Submit\" type = \"Submit\" id = \"Submit\" value = \"Submit\">";
echo "</form>";
}
echo "</table>";
} else {
echo "0 results";
}
if(isset($_POST['Submit'])){
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where ID=$id";
$result = $conn->query($sql);
}
$conn->close();
?>
Instead of building a form inside PHP, just break with ending PHP tag inside your while loop and write your HTML in a clean way then start PHP again. So you don't make any mistake.
Also you've to submit your $id from your form too.
Try this
<?php
require_once('dbconnect.php');
$id = $_GET['id'];
$sql = "SELECT * FROM dealers where ID=$id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<form action="" method="post">
<input type="hidden" name="id" value="<?= $id ?>" />
Company: <input type="text" name="CName" value="<?= $row['CName'] ?>" />
<br>
Contact: <input type="text" name="Contact" value="<?= $row['Contact'] ?>" />
<br>
City: <input type="text" name="City" value="<?= $row['City'] ?>" />
<br>
<input type="Submit" name="Submit" id="Submit" value="Submit" />
</form>
<?php
} // end while loop
echo "</table>";
}
else {
echo "0 results";
}
Note: You are passing undefined variables into your update query. As you are submitting your form you must have to define those variables before you use them.
if (isset($_POST['Submit'])) {
$CName = $_POST['CName'];
$Contact = $_POST['Contact'];
$City = $_POST['City'];
$id = $_POST['id'];
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where ID=$id";
$result = $conn->query($sql);
}
$conn->close();
that loop? ID primary key or not?
maybe u need create more key in table dealer like as_id
<input type="hidden" name="idform" value="$as_id">
in statment
if($_POST){
$idf = $_POST['idform'];
if(!empty($idf)){
$sql = "UPDATE dealers SET CName='$CName', Contact='$Contact', City='$City' where as_id=$idf";
$result = $conn->query($sql);
}
$conn->close();
}

More than one htmlspecialchars string in PHP MySQL

I have a table in MySQL where there is a row with this data.
id = 187
friendly name = i don't like mustard
filetype = exe
This first block of code below works perfectly, and echos text i don't like mustard into an HTML form. Similarly, if I change $row['friendlyname'] to $row['filetype'], text exe is echoed. All good, no issues yet.
<?php
$con = mysqli_connect('domain','user','pass','db');
$sql = "select * from installers where id=187";
$result = mysqli_query($con,$sql);
while($row=mysqli_fetch_array($result))
$friendlyname = htmlspecialchars(" ".$row['friendlyname']." ",ENT_QUOTES);
$con->close();
?>
<input type='text' value='<?php echo $friendlyname; ?>'>
The problem I'm having is if I try to echo both $row['friendlyname'] and $row['filetype'], only the variable that is listed first will be echoed. For example, in the below code, $row['friendlyname'] is listed before $row['filetype']. In this example, only $row['friendlyname'] (i don't like mustard) will be echoed. Similarly, if $row['filetype'] is listed before $row['friendlyname'], then only $row['filetype'] (exe) is echoed, and the second other HTML input form is empty.
<?php
$con = mysqli_connect('domain','user','pass','db');
$sql = "select * from installers where id=187";
$result = mysqli_query($con,$sql);
while($row=mysqli_fetch_array($result))
$friendlyname = htmlspecialchars(" ".$row['friendlyname']." ",ENT_QUOTES);
$filetype= htmlspecialchars(" ".$row['filetype']." ",ENT_QUOTES);
$con->close();
?>
<input type='text' value='<?php echo $friendlyname; ?>'>
<input type='text' value='<?php echo $filetype; ?>'>
Note 1: It doesn't matter the order of the input type forms. I ruled that out as the issue.
Note 2: If I were to replace $row['friendlyname'] and $row['filetype'] with the text I'm trying to echo, then it work (the below code). So, this definitely appears to be something with these $row variables.
<?php
$con = mysqli_connect('domain','user','pass','db');
$sql = "select * from installers where id=187";
$result = mysqli_query($con,$sql);
while($row=mysqli_fetch_array($result))
$friendlyname = i don't like mustard;
$filetype= exe;
$con->close();
?>
<input type='text' value='<?php echo $friendlyname; ?>'>
<input type='text' value='<?php echo $filetype; ?>'>
You have not added brackets into while loop so only first record is populated.
This block:
while($row=mysqli_fetch_array($result))
$friendlyname = htmlspecialchars(" ".$row['friendlyname']." ",ENT_QUOTES);
$filetype= htmlspecialchars(" ".$row['filetype']." ",ENT_QUOTES);
Should be:
while($row=mysqli_fetch_array($result)){
$friendlyname = htmlspecialchars(" ".$row['friendlyname']." ",ENT_QUOTES);
$filetype= htmlspecialchars(" ".$row['filetype']." ",ENT_QUOTES);
}

Displaying query results after submitting a PHP form

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));

PHP: Query was empty when searching

I need a little help for my problem...
Scene: I was trying to search something in my database but the result is "Query was empty" but the one I'm trying to search is already in my database. I'm trying to search the "Atrium Hotel"
Here's my screenshot of my Database:
Here's my screenshot of my result Page:
And Lastly here's my code:
<input type='submit' name='search' value='Search Building' onClick="this.form.action='search_bldg.php'; this.form.submit()">
<input type="text" id="idSearch"name="searchBldg" size="40" value="<?php echo $_POST['searchBldg']; ?>">
<fieldset width= "50px">
<legend>BUILDING/S</legend>
<?php
$search = $_POST["searchBldg"];
$data = mysql_query("SELECT * FROM tbldata WHERE fldBldgName LIKE '%$search%'");
$result = mysql_query($data) or die(mysql_error());
while($row = mysql_fetch_array( $result ))
{
echo $row['fldBldgName'];
}
?>
</fieldset>
I was wondering what is the problem in my query...
Thanks in advance...
You are executing your query twice (Line #7 and #8). That may be the problem. Try something like this:
<input type='submit' name='search' value='Search Building' onClick="this.form.action='search_bldg.php'; this.form.submit()">
<input type="text" id="idSearch"name="searchBldg" size="40" value="<?php echo $_POST['searchBldg']; ?>">
<fieldset width= "50px">
<legend>BUILDING/S</legend>
<?php
$search = $_POST["searchBldg"];
$query= "SELECT * FROM tbldata WHERE fldBldgName LIKE '%$search%'"; //Your sql
$result = mysql_query($query) or die(mysql_error()); //execute your query
while($row = mysql_fetch_array( $result ))
{
echo $row['fldBldgName'];
}
?>
</fieldset>
P.S. use mysqli_* or PDO instead of mysql_* since it is deprecated as of PHP 5.4
You should use mysqli or PDO since mysql_* is depreciated.
Try the below code: It's using mysqli . It should be working...
<?php
$search = $_POST["searchBldg"];
//connecting to db...mysqli_connect("example.com","peter","abc123","my_db")
$con=mysqli_connect(host,username,password,dbname);
//searching...
$query= "SELECT * FROM tbldata WHERE fldBldgName LIKE '%$search%'";
//execute the query
$result = mysqli_query($query) or die(mysqli_error());
while($row = mysqli_fetch_array( $result ))
{
echo $row['fldBldgName'];
}
mysqli_close($con);
?>
There are some issues in your code that I'll demonstrate by commenting your code:
<input type='submit' name='search' value='Search Building' action='search_bldg.php' onClick="this.form.submit();"> <!-- setting action-attribute directly in form-tag, no need to use js for that -->
<input type="text" id="idSearch" name="searchBldg" size="40" value="<?php echo $_POST['searchBldg']; ?>"> <!-- added a space between id="search" and name-attribute -->
<fieldset width= "50px">
<legend>BUILDING/S</legend>
<?php
$search = $_POST["searchBldg"];
$data = "SELECT * FROM tbldata WHERE fldBldgName LIKE '%$search%'"; //mysql_query is removed, because the actual query is executed below
$result = mysql_query($data) or die(mysql_error());
while($row = mysql_fetch_assoc( $result )) //mysql_fetch_array doesn't return associative arrays, therefore it's replaced with mysql_fetch_assoc
{
echo $row['fldBldgName'];
}
?>
</fieldset>
You should of course sanitize data (so not unwanted data gets inserted into db) and use something else besides mysql_* as stated in previous answers.
Another issue (which is not really a problem) is the name of elements, column-names etc. searchBldg is very similar to searchB1dg and it might be easy to do typing-errors which might be hard to find.

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.

Categories