Notice : Undefined variable when concatenating - php

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>';
// ...

Related

Search bar not functioning properly

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.

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];
}

Requiring Fields in Safari 5.1

As stated here, the required attribute in HTML5 doesn't work in Safari. I have PHP that checks if the required fields are filled out. When the user submits the form (a contact-us type form), the action="" is set to the same page, so that the PHP runs. It sends the email with the information and redirects to the home page (which I tell users at the bottom of the page).
However, I heard about people being able to change the HTML of the page and not require fields. While the form is just a contact form and there's no reason for anyone to go through the trouble of modifying the code, I'm relatively new to web development and programming, and I'd like to know how to prevent this kind of stuff if I was to work on projects in the future where I'd need this much security.
So, anyway, the PHP successfully does not send the email if the required information isn't filled out, but if it isn't filled out, it redirects to the home page anyway. How would I use PHP to stay on the same page after the required information isn't there? I know I can use JavaScript, and I probably will in addition to PHP, but since they can have that turned off, it's not totally secure. Again, I know that my situation doesn't require this much security, but it's good practice for a beginner in my opinion. Here's what I have so far:
<?php
if (isset($_POST['email']) && isset($_POST['address']) && isset($_POST['floors'])) {
$name = $_POST['name'];
$lotSize = $_POST['lotSize'];
$lotSize2 = $_POST['lotSize2'];
$age = $_POST['age'];
$taxes = $_POST['taxes'];
$notes = $_POST['notes'];
$email = $_POST['email'];
$address = $_POST['address'];
$floors = $_POST['floors'];
$bedrooms = $_POST['bedrooms'];
$bathroomsFull = $_POST['bathroomsFull'];
$bathroomsHalf = $_POST['bathroomsHalf'];
if (isset($_POST['basement'])) {
$basement = "Yes";
} else {
$basement = "No";
}
if (!(empty($email) && empty($address) && empty($floors) && is_numeric($floors))) {
if ((strlen($name) < 101) && (strlen($email) < 255) && (strlen($address) < 51) && (strlen($lotSize) < 8) && (strlen($floors) < 4) && (strlen($age) < 4) && (strlen($taxes) < 8) && (strlen($notes) < 481)) {
$message = "You have received information about a listing!<hr/><br/>
<table style='border:1px solid black;padding:3px'>
<tr style='padding:5px'><td><strong>Name:</strong></td><td>" . $name . "</td></tr>
<tr style='padding:5px'><td><strong>Email:</strong></td><td>" . $email . "</td></tr>
<tr style='padding:5px'><td><strong>Address:</strong></td><td>" . $address . "</td></tr>
<tr style='padding:5px'><td><strong>Lot size:</strong></td><td>" . $lotSize . " × " . $lotSize2 . " sq. ft. (" . ($lotSize*$lotSize2) . " sq. ft.)</td></tr>
<tr style='padding:5px'><td><strong>Floors:</strong></td><td>" . $floors . "</td></tr>
<tr style='padding:5px'><td><strong>Bedrooms:</strong></td><td>" . $bedrooms . "</td></tr>
<tr style='padding:5px'><td><strong>Full Baths:</strong></td><td>" . $bathroomsFull . "</td></tr>
<tr style='padding:5px'><td><strong>Half Baths:</strong></td><td>" . $bathroomsHalf . "</td></tr>
<tr style='padding:5px'><td><strong>House Age:</strong></td><td>" . $age . " years</td></tr>
<tr style='padding:5px'><td><strong>Taxes:</strong></td><td>$" . $taxes . " / Yr.</td></tr>
<tr style='padding:5px'><td><strong>Basement:</strong></td><td>" . $basement . "</td></tr>
<tr style='padding:5px'><td><strong>Notes:</strong></td><td>" . $notes . "</td></tr>";
mail("****#****", "Listing Inquiry", $message, "Content-Type: text/html; charset=ISO-8859-1\r\n");
header('Location: sellRedirect.php');
}
}
}
?>
Thanks!
To check if the field has been sent, you should use isset() function.
For example:
if(isset($_POST['name'])) {
// The field has been sent
} else {
die('Something is wrong!');
}

Categories