Search bar not functioning properly - php

My problem is when I enter a specific country name, for example: France, it'll output every data from my database instead of just France. I don't know where I've gone wrong and its probably something very simple but I don't even know how to attempt to fix it so I've come here to get some help
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$country = $_POST['country'];
$_SESSION['country'] = $country;
$sqlQuery = "SELECT * FROM campsites WHERE country LIKE '%$country%'";
$result = $campDataSet->fetchAllCamps($sqlQuery);
//var_dump($result);
if (count($result) > 0) {
echo'<div class="table-responsive">
<table class="table">
<thead id="table1Head">
<tr><td>Name</td>
<td>Address</td>
<td>Postcode</td>
<td>Country</td>
<td>Latitude</td>
<td>Longitude</td>
<td>email</td>
<td>Phone<td>
</thead>
<tbody>
</div>';
foreach ($result as $row) {
echo '<tr><td>' . $row->campsite_name . '</td> <td>' . $row->address . '</td> <td>' . $row->postcode . '</td> <td>' . $row->country. '</td> <td>' . $row->lattitude . '</td> <td>' . $row->longitude . '</td> <td>' . $row->email . '</td> <td>' . $row->phone_number . '</td></td></tr>';
}
echo "</tbody></table>";
} else {
print " 0 results";
}
}
my Database class
class campDataSet
{
public $dbHandle, $dbInstance;
public function __construct()
{
$this->db = new campData();
$this->conn = $this->db->getCampData();
}
public function fetchAllCamps()
{
//$sqlQuery = "SELECT campsites.id_campsite, campsites.campsite_name, campsites.address, campsites.postcode, campsites.country, campsites.lattitude, campsites.longitude, campsites.email, campsites.phone_number
// FROM sgb220_clientserver.campsites";
$sqlQuery = "SELECT * FROM sgb220_clientserver.campsites";
if ($data = $this->conn->prepare($sqlQuery)) {
$data->execute();
$dataSet = [];
while ($row = $data->fetch()) {
$dataSet[] = new DBdata($row);
}
} else {
echo "<script> alert(\"Could not prepare SQL statement\") </script>";
}
return $dataSet;
}

Your fetchAllCamps() method doesn't accept any arguments.
Instead of defining the $sqlQuery inside fetchAllCamps, use a parameter:
public function fetchAllCamps($sqlQuery) // <- This
{
if ($data = $this->conn->prepare($sqlQuery)) {
$data->execute();
$dataSet = [];
...
A warning about SQL Injection
Because you are inserting $_POST data directly into your query, the user is able to manipulate the sql and thus can extract/manipulate data however he wants to. Read up in SQL Injection and how to prevent it to keep your database safe from attackers.
This might be a good starting point: https://stackoverflow.com/a/601524/2232127

Your issue is that you are running a query that just gets all of the camps instead of only the ones in a certain country. Your fetchAllCamps() function does not accept any parameters.
It would probably be best to move your query into the fetchAllCamps() function, or make another function entirely if you need a function to give you all the camps instead o just ones in a certain country. Instead of passing in the query, just pass the $country variable. Build your query inside the function and run it.
This way you are separating all of your SQL from where you are building your HTML. This is more in line with modern programming standards.

Related

How to get postal code by address

I would like to get the postal code by enter address, I have tried google auto complete place search, But it gives wrong postal code for some places.
Give any idea to get the correct postal code by the given address?
Thank you,
Try below code this may be helps to you:
// Decode json
$decoded_json = json_decode(file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false'));
foreach($decoded_json->results as $results)
{
foreach($results->address_components as $address_components)
{
// Check types is set then get first element (may want to loop through this to be safe,
// rather than getting the first element all the time)
print_r($address_components);
if(isset($address_components->types) && $address_components->types[0] == 'postal_code')
{
// Do what you want with data here
echo $address_components->long_name;
}
}
}
Use below code it will help you.
<?php
$db = mysqli_connect("localhost","root","") or die("Could not connect");
mysqli_select_db($db, "search_db") or die("No database");
$textbox = "";
$out = "";
$title = "";
if (isset($_GET['search'])) {
$searchq = $_GET['search'];
$query = mysqli_query($db, "SELECT * FROM `pincodes_db` WHERE `pincode` LIKE '%$searchq%' OR `divisionname` LIKE '%$searchq%' OR `statename` LIKE '%$searchq%' OR `regionname` LIKE '%$searchq%' OR `officename` LIKE '%$searchq%' OR `circlename` LIKE '%$searchq%'" ) or die("Could not search");
$count = mysqli_num_rows($query);
if($count == 0){
$output = 'There was no records found';
}else{
while($row = mysqli_fetch_array($query)){
$pincode = $row['pincode'];
$officename = $row['officename'];
$Deliverystatus = $row['Deliverystatus'];
$divisionname = $row['divisionname'];
$Taluk = $row['Taluk'];
$RelatedHeadoffice = $row['RelatedHeadoffice'];
$RelatedSuboffice = $row['RelatedSuboffice'];
$circlename = $row['circlename'];
$regionname = $row['regionname'];
$contactno = $row['Telephone'];
$out .= '<div style="border-bottom:1px dotted green;">
<h2 style="font-size:18px;"><a href="search-indian-postal-code-in-map.php?postalcodeof='.$pincode.'"/><b><font color="green">Postal code of :</font></b><b><font color="green">'.$pincode.'</font></b> <b><font color="green">'.$officename.'</font></b> <b><font
color="green">'.$regionname.'</font>,</b> <b><font color="green">'.$circlename.'</font>,</b> <b><font color="green">'.$contactno.'</font></b></a></h2>
<table><tr><th>Description</th><th>Result</th></tr><tr>
<td>Pincode</td>
<td>' .$pincode.'</td></tr>
<td>Office Name</td>
<td>' .$officename. '</td></tr>
<td>Delivery system</td>
<td>' . $Deliverystatus. '</td></tr>
<td>Division Name</td>
<td>' . $divisionname. '</td></tr>
<td>Taluk</td>
<td>' . $Taluk. '</td></tr>
<td>Related Head Office</td>
<td>' . $RelatedHeadoffice. '</td></tr>
<td>Related Sub Office</td>
<td>' . $RelatedSuboffice. '</td></tr>
<td>Circle Name</td>
<td>' . $circlename. '</td></tr>
<td>Region</td>
<td>' . $regionname. '</td></tr>
<table/></div>';
}
}
}
?>
i have used same code for my website Please refer
http://www.myworkbook.in/indian-postal-code-search/indian-states.php

How to send 2 variables to a different page when user clicks on a link

I am wondering if anyone could help? I am trying to send 2 variables which I have extracted from a database to another page when the user clicks on a link. At the moment I can only send one. I know what I am doing below is wrong.....basically I want to send both uninum and groupid over to the other page.
for ($i = 0; $i < $count; $i++){
$q = "SELECT participants.sname, participants.uninum, groups.groupid FROM participants INNER JOIN groups ON participants.uninum =
groups.uninum WHERE groups.groupid ='".$groups[$i]."'";
$result = mysqli_query ($dbcon, $q); // Run the query.
if ($result) { // If it ran, display the records.
// Table header.
echo '<table>
<tr><td><b>Edit</b></td>
<td><b>Surnname</b></td>
<td><b>University ID</b></td>
<td><b>Group</b></td>
</tr>';
// Fetch and display the records:
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
echo '<tr>
<td>Edit</td>
<td>' . $row['sname'] . '</td>
<td>' . $row['uninum'] . '</td>
<td>' . $row['groupid'] . '</td>
</tr>';
}
echo '</table>'; // Close the table.
mysqli_free_result ($result); // Free up the resources.
echo "<br><br>";
} else { // If it did not run OK.
// Public message:
echo '<p class="error">The current users could not be retrieved. We apologize for any inconvenience.</p>';
// Debugging message:
echo '<p>' . mysqli_error($dbcon) . '<br><br>Query: ' . $q . '</p>';
}
}
You have used ? instead of & in your code.
<td>Edit</td>
Should be:
<td>Edit</td>
You can try this :
Edit

PHP and select in loop

I have a PHP page where its querying data from the database and putting it in a table. The first column is where I would like the user to assign a person to that row. I was able to do that successfully (the select in a loop) but now I'm having a problem when its getting pushed out to the other page.
Below is the first page:
$sql = "SELECT * FROM meetingDump WHERE Meeting_ID IN ($Series)";
$rs=odbc_exec($conn,$sql);
while($row = odbc_fetch_array($rs))
{
$ID = odbc_result($rs,"ID");
$Meeting_ID = odbc_result($rs,"Meeting_ID");
$Title = odbc_result($rs,"Title");
$StartTime = odbc_result($rs,"StartTime");
$EndTime = odbc_result($rs,"EndTime");
$Organizer = odbc_result($rs,"Organizer");
echo '<tr>
<td>';
{
$box1 = array();
$result1 = "SELECT FullName FROM User";
$rs1=odbc_exec($connu,$result1);
while($row = odbc_fetch_array($rs1)) { $box1[] = $row; }
}
/* Generate select box contents */
$AssignedTo = '<select name="AssignedTo[]" onchange="autoSubmit()">';
$AssignedTo .= '<option selected="selected">---< Select Engineer >---</option>';
if (!empty($box1)) {
foreach ($box1 as $k => $v) {
$AssignedTo .= '<option value="'.$v['FullName'].'">'.$v['FullName'].'</option>';
}
}
$AssignedTo .= '</select>';
/* Output */
echo $AssignedTo;
echo '
</td>
<input name="AssignedID[]" type="hidden" value="' . $ID . '" />
<td>' . $Meeting_ID . '</td>
<td>' . $Title . '</td>
<td>' . $StartTime . '</td>
<td>' . $EndTime . '</td>
<td>' . $Organizer . '</td>';
}
Now for the second page I currently have:
foreach($_POST['AssignedTo'] as $AssignedTo)
{
echo '<br>' . $AssignedTo;
}
That gets me all the selected names, which is perfect, but I'm trying to correlate the assignedTo field with the meeting_id field.
Any ideas?
UPDATE:
The comment from AeroX helped me figure it out!
$AssignedID = $_POST['AssignedID'];
$AssignedTo = $_POST['AssignedTo'];
foreach ($AssignedID as $Key => $value)
{
echo $AssignedID[$Key] .' '. $AssignedTo[$Key];
echo '<br>';
}
In your example, because of the way the POST variables $_POST['AssignedID'] and $_POST['AssignedTo'] will be populated you can just pull the Value from each Array where they both have matching Keys. This will then give you the related records.
Something like the below should work for you:
$AssignedID = $_POST['AssignedID'];
$AssignedTo = $_POST['AssignedTo'];
foreach(array_keys($AssignedID) as $Key)
{
echo $AssignedID[$Key];
echo $AssignedTo[$Key];
}

PHP/MySQL Table with Hyperlinks

I have 2 PHP forms. One displays a list of events and the other displays the results of each specific event. On the page with the list of events I would like it so that a hyperlink can be created to access each individual event's results.
For example, on the Events page I click on row 2's hyperlink which will then take me to the Results page that has the results for that specific event.
Any help would be appreciated as I am very, very new to PHP. If any extra details are needed, please feel free to ask.
Thanks.
Edit: Sorry I'll show you what the Events form looks like so far:
<?php
mysql_connect('localhost','root','');
mysql_select_db('clubresults') or die( "Unable to select database");
$sql = "SELECT *, DATE_FORMAT(EventDate, '%d/%m/%y') as newdate FROM Events";
$result = mysql_query ($sql);
?>
<table border = 1>
<tr>
<th>Event ID</th>
th>Event Name</th>
<th>Event Date</th>
<th>Location</th>
</tr>
<?php
while ($row = mysql_fetch_array($result))
{
echo "</td><td>" . $row['EventID'] . "</td><td>" . $row['EventName'] . "</td><td>" . $row['newdate'] . "</td><td>" . $row['Location'] . "</td><tr>";
}
echo "</table>";
mysql_close();
?>
You don't need two scripts, but just one:
events.php?list
events.php?event=1234
in there you only need to check for things:
$db = new Database(); # simplified
/* show event details if requested */
if (isset($_GET['event']) {
if ($event = $db->getEventByID($_GET['event'])) {
printf('<h2>Event: %s</h2>', htmlspecialchars($event->title));
# ...
}
}
/* show the list if requested (or show it always, whatever pleases you) */
if (isset($_GET['list']) {
echo '<table>';
foreach($db->getEventList() as $event) {
printf('<tr><td>%s</td></tr>'
, $event->ID, htmlspecialchars($event->title));
}
echo '</table>';
}
Edit: As I saw in your updated question, you should switch from those oldskool mysql_* functions to the class style I outlined in my example, because it is much simpler to use. Here is a code-example that is close to yours:
<?php
/**
* My First PDO Databaseclass
*/
class Database extends PDO
{
public function __construct()
{
$host = 'localhost';
$name = 'clubresults';
$user = 'root';
$pass = NULL;
parent::__construct("mysql:host=$host;dbname=$name", $user, $pass);
$this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
public function getEvents()
{
$sql = "SELECT *, DATE_FORMAT(EventDate, '%d/%m/%y') as newdate FROM Events";
return $this->query($sql, PDO::FETCH_OBJ );
}
public function getEventByID($id)
{
$sql = sprintf("SELECT * FROM Events WHERE EventID = %d;", $id);
return $this->query($sql)->fetchObject();
}
}
$db = new Database();
?>
<table border=1>
<tr>
<th>Event ID</th>
th>Event Name</th>
<th>Event Date</th>
<th>Location</th>
</tr>
<?php
foreach($db->getEvents() as $event)
{
echo "</td><td>" . $event->EventID . "</td><td>" . $event->EventName . "</td><td>" . $event->newdate . "</td><td>" . $event->Location . "</td><tr>";
}
?>
</table>

Notice : Undefined variable when concatenating

I have been making a script to display users and make changes to their admin privileges.
Here is the code:
while ($row= mysql_fetch_assoc($query)) {
$uname= $row['username'];
$fname= $row['first_name'];
$lname= $row['last_name'];
$email= $row['email'];
$admin= $row['admin'];
$insert .= '<tr>
<td>' .$uname. '</td>
<td>' .$fname. '</td>
<td>' .$lname. '</td>
<td>' .((isset($email)) ? $email:'No email set.'). '</td>
<td>'.(($admin == 'y') ? 'Admin':'User').'</td>
<td><input type="checkbox" name="' .$uname. '" value="'.(($admin == 'y')?'n':'y').'"/>'.(($admin == 'y')?'Make a user':'Make an admin user').'</tr>';
}
The $insert variable is then used later in the html to generate all the table rows with the user data.
The problem is that when I run the script this message appears
Notice: Undefined variable: insert in C:\wamp\www\...\user_edit.php on line 33
The script still works correctly though with only this message showing in the middle of the page.
When I take the . off from the $insert .= ' part the message disappears but the script only displays one user in the table.
Is there any reason why this may be happening? And is there a solution to my problem so I can have the script working and the message not showing up?
Just set the variable to an empty string before you use it. You can't use .= on a variable that does not exist yet:
$insert = "";
while($row= mysql_fetch_assoc($query)) {
// ...
$insert .= '<tr>';
// ...

Categories