how to edit a record from MySQL database - php

this is my first post!
First off, I have my code which outputs a table on index.php. At the end I have an edit link which takes me to the edit.php page:
if ($result->num_rows > 0) {
echo "<p><table><tr><th>ID</th><th>Film Name</th><th>Producer</th><th>Year Published</th><th>Stock</th><th>Price</th><th>Function</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["ID"]."</td><td>".$row["FilmName"]."</td><td>".$row["Producer"]."</td><td>".$row['YearPublished']."</td><td>".$row['Stock']."</td><td>".$row['Price']."</td><td>"."Edit / Delete"."</td></tr></p>";
}
echo "</table>";
edit.php (first there is the form):
$query = "SELECT * FROM ProductManagement WHERE ID=" . $_GET["ID"] . ";"; // Place required query in a variable
$result = mysqli_query($connection, $query); // Execute query
if ($result == false) { // If query failed
echo "<p>Getting product details failed.</p>";
} else { // Query was successful
$productDetails = mysqli_fetch_array($result, MYSQLI_ASSOC); // Get results (only 1 row
// is required, and only 1 is returned due to using a primary key (id in this case) to
// get the results)
if (empty($productDetails)) { // If getting product details failed
echo "<p>No product details found.</p>"; // Display error message
}
}
?>
<form id="updateForm" name="updateForm" action="<?php echo "?mode=update&ID=" . $productDetails["ID"]; ?>" method="post">
<div>
<label for="updateFormProductCostPrice">ID</label>
<input id="updateFormProductCostPrice" name="ID" type="text" readonly
value="<?php echo $productDetails["ID"]; ?>">
</div>
<div>
<label for="updateFormProductName">Film Name</label>
<input id="updateFormProductName" name="FilmName" type="text" value="<?php echo $productDetails["FilmName"]; ?>">
</div>
<div>
<label for="updateFormProductDescription">Producer</label>
<textarea rows="4" cols="50" id="Producer"
name="productDescription"><?php echo $productDetails["Producer"]; ?></textarea>
</div>
<div>
<label for="updateFormProductPrice">Year Produced</label>
<input id="updateFormProductPrice" name="YearProduced" type="text"
value="<?php echo $productDetails["YearProduced"]; ?>">
</div>
<div>
<label for="updateFormProductStock">Stock:</label>
<input id="updateFormProductStock" name="Stock" type="text"
value="<?php echo $productDetails["Stock"]; ?>">
</div>
<div>
<label for="updateFormProductEan">Price:(&#163)</label>
<input id="updateFormProductEan" name="Price" type="text"
value="<?php echo $productDetails["Price"]; ?>">
</div>
<div>
<input id="updateSubmit" name="updateSubmit" value="Update product" type="submit">
</div>
</form>
</body>
Then there is the php code to update the record (edit.php continued):
if (((!empty($_GET["mode"])) && (!empty($_GET["id"]))) && ($_GET["mode"] == "update")) { // If update
echo "<h1>Update product</h1>";
if (isset($_POST["updateSubmit"])) { // If update form submitted
// Check all parts of the form have a value
if ((!empty($_POST["ID"])) && (!empty($_POST["FilmName"]))
&& (!empty($_POST["Producer"])) && (!empty($_POST["YearProduced"]))
&& (!empty($_POST["Stock"])) && (!empty($_POST["Price"]))) {
// Create and run update query to update product details
$query = "UPDATE products "
. "SET FilmName = '" . $_POST["FilmName"] . "', "
. "Producer = '" . $_POST["Producer"] . "', "
. "YearProduced = '" . $_POST["YearProduced"] . "', "
. "Stock = " . $_POST["Stock"] . ", "
. "Price = '" . $_POST["Price"] . "' "
. "WHERE id=" . $_GET['ID'] . ";";
$result = mysqli_query($connection, $query);
if ($result == false) { // If query failed - Updating product details failed (the update statement failed)
// Show error message
echo "<p>Updating failed.</p>";
} else{ // Updating product details was sucessful (the update statement worked)
// Show success message
echo "<p>Updated</p>";
}
}
}
}
I do apologise that there is a lot of code here. Basically when I click edit in the table on the home page, I would expect it to load up the data for the respective row selected so I can update it.
Currently, when I click the 'edit' link, it loads the edit page and it has the blank fields and says "getting product details failed". It would be great if it can retrieve the data for the respective row selected. Can someone help please? Thanks!

In edit.php file $_GET["ID"] is empty because there is no ID value in your link so query returns no results.
Also in your last file you have $_GET["id"] which is different from the value you use ($_GET["ID"]).
Try this:
echo "
<tr>
<td>".$row["ID"]."</td>
<td>".$row["FilmName"]."</td>
<td>".$row["Producer"]."</td>
<td>".$row['YearPublished']."</td>
<td>".$row['Stock']."</td>
<td>".$row['Price']."</td>
<td>Edit
<td>Delete
</tr>";
Also you are SQL Injection vulnerable. You can combine mysqli with prepared statements to avoid this.

Related

Value not saving after form is submitted

I've created a mysql table with two columns. One is ID and other is Heading. I have a textarea on which I run UPDATE code and whenever someone submits a form its being updated in the datebase column under heading. And that works fine but I want to show the last inputted submit inside my textarea.
My code is showing the last inputted value but when I reset the page it all turns out blank and its not showing anymore. I looked out in datebase and the heading is still there so I don't know why its dissapearing from the front end.
My page:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
So for example if I type Aleksa, after submit it will get url like edit.php?heading=Aleksa&submit=Submit. And then when I delete url just to edit.php, the value is missing.
You can test the page here: https://www.easybewussterschaffen.com/admin/edit.php
This is happening, because it's always trying to insert the heading when you refresh the page. You should check to see if the request is GET or the request is POST, and only insert it if they're submitting the form.
Update your form method, specify it to POST, and specifically check the method or check for the existance of $_POST['submit'] as shown below:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
// Use one of the 2 if statements:
if ($_SERVER['REQUEST_METHOD'] === 'POST') { // Trying to insert a new heading
if (isset($_POST['submit'])) { // Alternative
$heading = mysqli_real_escape_string($link, $_REQUEST['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="POST">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
Alternatively, if you still wish to make a GET request, you should check to make sure that the heading is set:
<?php
$title = 'Admin Panel - Edit';
include '../config.php';
if (isset($_GET['submit'])) {
$heading = mysqli_real_escape_string($link, $_GET['heading']);
$sql = "UPDATE content SET heading='$heading' WHERE id = 1 ";
if(mysqli_query($link, $sql) == false){
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
$value=mysqli_query($link, "SELECT heading FROM content WHERE id = 1");
$currentText = mysqli_fetch_row($value);
?>
<form action="edit.php" method="GET">
<?php echo $currentText[0]; ?>
<input type="text" name="heading" id="heading" value='<?php echo $currentText[0]; ?>' />
<input type="submit" value="Submit" name="submit" />
</form>
I did it like this, is this good tho? Its working
<?php
$sql = "SELECT * FROM content";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
echo '';
while($row = mysqli_fetch_array($result)){
echo $row['heading'];
}
// Free result set
mysqli_free_result($result);
} else{
echo "No records matching your query were found.";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
?>

How to associate query with changing variable in PHP

I'm in need of a bit help. I'm trying to find out how to associate a specific query (deletion of a record) with not the id of a record, but the record with which another query (selection of a record) is echoed out.
This line of code totally works when the id is specified, but again I need it for the record that gets called, where the id can skip numbers if I delete a record.
$querytwo = "DELETE FROM `paginas` WHERE id = 5";
I've got a table in my phpmyadmin database with columns 'id', 'pagetitle', 'toevoeging' (addition in Dutch) , 'message'. First one is an INT, rest are varchars/text.
This may be a stupid question, I'm sorry for that. I'm still new to PHP, and to programming in general.
Here is the code. I've commented on lines code to clarify. Thanks you!.
<?php
if (isset($_SESSION['email'])) //if the admin is active, forms can be written out.
{
echo '</nav>
<br><br> <div class="inlogscript">
<form action="verstuurd.php" method="post">
<input type="text" placeholder="Titel" method="POST" name="pagetitle" /><br><br>
<input type="text" placeholder="Toevoeging" method="POST" name="toevoeging" /><br><br>
<textarea class="pure-input-1-2" placeholder="Wat is er nieuws?" name="message"></textarea><br>
<input type="submit" value="Bevestigen" />
</form></div>';
}
?>
<div class="mainContent">
<?php
include_once("config.php"); //this is the database connection
$query = "SELECT * FROM paginas "; //selects from the table called paginas
$result = mysqli_query($mysqli, $query);
while($row = mysqli_fetch_assoc($result))
{
$pagetitle = $row['pagetitle'];
$toevoeging = $row['toevoeging'];
$message = $row['message'];
echo '<article class="topcontent">' . '<div class="mct">' . '<h2>' . "$pagetitle" .'</h2>' . '</div>' . "<br>" .
'<p class="post-info">'. "$toevoeging" . '</p>' . '<p class="post-text">' . '<br>'. "$message" . '</p>' .'</article>' . '<div class="deleteknop">' . '<form method="post">
<input name="delete" type="submit" value="Delete Now!">
</form>' . '</div>' ;
} //This long echo will call variables $pagetitle, $toevoeging and &message along with divs so they automatically CSS styled,
//along with a Delete button per echo that has the 3 variables
$querytwo = "DELETE FROM `paginas` WHERE id = 5";
if (isset($_POST['delete'])) //Deletes the query if 'delete' button is clicked
{
$resulttwo = $mysqli->query($querytwo);
}
?>
</div>
</div>
Also here is the Insert INTO query of the records. Thanks again!
$sql = "INSERT INTO paginas (pagetitle,toevoeging, message)
VALUES ('$_POST[pagetitle]','$_POST[toevoeging]','$_POST[message]')";
//the insertion into the table of the database
if ($MySQLi_CON->query($sql) === TRUE) {
echo "";
} else {
echo "Error: ". $sql . "" . $MySQLi_CON->error;
}
This won't be sufficient but, to begin with your echo :
echo '<article class="topcontent">
<div class="mct">
<h2>' . $pagetitle .'</h2>
</div><br>
<p class="post-info">'. $toevoeging . '</p>
<p class="post-text"><br>'.$message.'</p>
</article>
<div class="deleteknop">
<form method="post">';
// you ll want to use $_POST["id"] array to delete :
echo '<input type="hidden" name="id" value="'.$row['id'].'">
<input name="delete" type="submit" value="Delete Now!">
</form>
</div>' ;

Database not updating correctly in PHP / MySQL [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 7 years ago.
I've got a database with a Users table which I'm trying to update.
Currently I have customers.php, which displays form fields with the user information so it can be updated.
This form points to edit_customer_processor.php , which takes the new values, puts them into a MYSQL query... and then despite the query working correctly when I query the DB via the PHPMyAdmin command line, the record doesn't update.
customers.php
<?php
session_start();
if(!$_SESSION["logged_in"]){
header("location:home.php");
die;
}
?>
<?php include 'header.html'; ?>
<div id='maincontent'>
<?php
if (isset($_GET["id"])){
$customer_id = $_GET["id"];
require_once('config.php');
$customer_query = "SELECT * FROM customer WHERE customer_id = $customer_id";
$customer_results = mysql_query($customer_query, $conn);
if (!$customer_results) {
die ("Error selecting car data: " .mysql_error());
}
else {
while ($row = mysql_fetch_array($customer_results)) {
echo "<h3>Edit Customer</h3>";
echo "<FORM method='post' action='edit_customer_processor.php'>";
echo '<p> Name: <input type="text" name="name" size = "40" value=' . $row[name] . '></p>';
echo '<p> Address: <input type="text" name ="address" size="40" value=' . $row[address] . '></p>';
echo '<p> Email: <input type="text" name="email" value=' . $row[email] . '></p>';
echo '<p> Phone: <input type ="text" name="phone" size="20" value=' . $row[phone] . '></p>';
echo '<input type ="hidden" name="customer_id" value="' . $row[customer_id] . '">';
echo '<input type ="hidden" name="formtype" value="edit_customer">';
echo '<input type="submit" name="submit" value= "Update">';
echo '</form>';
}
}
} else {
// If there isn't an ID, display the New Customer form and all customers below, with links
// to their edit pages.
echo "<h3>Enter new customer information and submit.</h3>";
echo "<FORM method='post' action='new_customer_processor.php'>";
echo '<p> Name: <input type="text" name="name" size = "40"></p>';
echo '<p> Address: <input type="text" name ="address" size="40"></p>';
echo '<p> Email: <input type="text" name="email"></p>';
echo '<p> Phone: <input type ="text" name="phone" size="20"></p>';
echo '<input type ="hidden" name="formtype" value="new_customer">';
echo '<input type="submit" name="submit" value= "Submit">';
echo '<input type ="reset" name="reset" value ="Reset">';
echo '</form>';
require_once('config.php');
echo "<h3>Current Customers</h3>";
$query = "SELECT * FROM customer";
$results = mysql_query($query, $conn);
if (!$results) {
die ("Error selecting customer data: " .mysql_error());
}
else {
// In the absence of an ID, all customers will be displayed down
// the bottom of the page
while ($row = mysql_fetch_array($results)) {
echo "<a href=customers.php?id=";
echo $row[customer_id];
echo "><p> $row[name] </p></a>";
echo "<p> $row[address] </p>";
echo "<p> $row[phone] </p>";
echo "<p> $row[email] </p>";
}
}
}
?>
Back to Customers Page
</div>
<?php include 'footer.html' ?>
edit_customer_processor.php
<?php include 'header.html' ?>
<div id="maincontent">
<?php
// Pulling in hidden customer ID from post value
$mysqli = new mysqli( 'localhost', 'root', 'root', 'w_c_a' );
// Check our connection
if ( $mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_errno . ': ' . $mysqli->connect_error );
}
// Insert our data
$sql = mysql_query("UPDATE customer
SET name = '".mysql_real_escape_string($_POST['name'])."',
address = '".mysql_real_escape_string($_POST['address'])."',
phone = '".mysql_real_escape_string($_POST['phone'])."',
email = '".mysql_real_escape_string($_POST['email'])."'
WHERE customer_id='".mysql_real_escape_string($_POST['customer_id'])."'");
$update = $mysqli->query($sql);
echo "Customer updated: ";
echo "<a href=customers.php?id=" . $_POST['customer_id'] . ">";
echo "Back to Edit Customer</a>";
?>
</div>
<?php include 'footer.html' ?>
And when I echo the MYSQL query, I get:
UPDATE customer SET name = 'Kellyassdsa', address = 'ads', phone = '0260123123', email = 'asdasd' WHERE customer_id='1'
Which works when I put it in PHPMyAdmin.
I know it'll be some boneheaded little mistake, but I've been trying to get this work for ages now. Any ideas?
Maybe your program just can't connect to your MySQL database.
$customer_results = mysql_query($customer_query, $conn);
I can't see where you gave a value to the var $conn.
If the problem is connection problem then we might need your database info like the name of your table in PhpMyAdmin.
your problem is...
$sql = mysql_query(..);
$update = $mysqli->query($sql);
it should be
$sql = 'UPDATE ...';
$update = $mysqli->query($sql);
i think problem occurs due to line break. pleas make a query in single line without line break.
$sql = mysql_query("UPDATE customer SET name = '".mysql_real_escape_string($_POST['name'])."',address = '".mysql_real_escape_string($_POST['address'])."', phone = '".mysql_real_escape_string($_POST['phone'])."', email = '".mysql_real_escape_string($_POST['email'])."' WHERE customer_id='".mysql_real_escape_string($_POST['customer_id'])."'");
Hope this helps..

Error in updating a mysql table

here I'm trying to display the record of a member and trying to edit the details.
First, I'm fetching the details from a database into textboxes, then, when I should hit the submit button..it should update the entry which is updated and should keep the original value of the textbox which is not updated.
Here's the code :-
The first one is of editmember.php
<?php
session_start();
include 'dbconnector.php';
$receivedusername=$_REQUEST['username'];
$parentusername=$_SESSION['username'];
$_SESSION['cusername']=$receivedusername;
//check session
if((isset($_SESSION['logged'])) && ($_SESSION['logged']==1))
{
//now map the user to it's parent account
$query="select * from master_member where parentusername = '" . $parentusername . "' and currentusername = '" . $receivedusername . "'";
$result=mysql_query($query,$db) or die (mysql_error($db));
if(mysql_num_rows($result) > 0)
{
$row=mysql_fetch_assoc($result);
//account mapped, green signal to proceed
?>
<form action="memberaction.php?action=edit" method="post">
<table>
<tr>
<td>Username : <input type="text" name="usrnm" value="<?php echo ($row['currentusername']); ?>" /></td>
</tr>
<tr>
<td>Email : <input type="text" name="eml" value="<?php echo ($row['currentemail']); ?>" /></td>
</tr>
<tr>
<td><input type="submit" name="submit" value="submit"></td>
</tr>
</table>
</form>
<?php
}
else
{
echo "You aren't authorized to perform this task, redirecting.";
header('refresh:2;URL=members.php');
exit();
}
}
else
{
header('Location:login.php');
exit();
}
?>
memberaction.php
case 'update':
$memberusername=$_SESSION['cusername'];//username of the member, whose account is to be edited.
$parentusername=$_SESSION['username'];//username of the parent.
//since the account is already matched to the parent account before, we do not need to do it again.
//get the field value
$usrnm=(isset($_POST['usrnm'])) ? $_POST['usrnm'] : '';
$eml=(isset($_POST['eml'])) ? $_POST['eml'] : '';
$query="update master_member set currentusername = '" . $usrnm . "' and currentemail = '" . $eml . "' where parentusername = '" . $parentusername . "' and currentusername = '" . $memberusername . "'";
$result=mysql_query($query,$db) or die (mysql_error($db));
if($result)
{
echo "updated";
header('refresh:2;URL=members.php');
exit();
}
else
{
echo "Errors";
}
break;
After I hit the submit button, it displays successfully updated, but no change takes place at the database.
What possible mistake I'm doing ?
My DB structure is like :-
http://sqlfiddle.com/#!2/969c54/2

php mysql based on user input form

I am having trouble using a checkbox to select one or multiple fields of data for PHP/AJAX to process and display. I have the PHP/AJAX working great on my <select>s but as soon as I try setting up the checkbox all hell breaks lose.
I also am very unsure on how to further prevent SQL injection on the site so if anyone could fill me in a little more about this I would GREATLY appreciate it! I read the link I was provided and just don't understand how bid_param or PDO works exactly.
The ajax script:
(I can't seem to insert the ajax/js so I'll leave a link to the live site)
Link to Agent search page
My php page that displays the data:
<div id="bodyA">
<h1>Find a Local OAHU Agent.</h1>
<!-- This is where the data is placed. -->
</div>
<div id="sideB">
<div class="sideHeader">
<em>Advanced Search</em>
</div>
<form class="formC">
<label for="last">Last Name</label><br />
<select id="last" name="Last_Name" onChange="showUser(this.value)">
<?php
include 'datalogin.php';
$result = mysqli_query($con, "SELECT DISTINCT Last_Name FROM `roster` ORDER BY Last_Name ASC;");
echo '<option value="">' . 'Select an Agent' .'</option>';
while ($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['Last_Name'].'">'.$row['Last_Name'].'</option>';
}
?>
</select>
<label for="company">Company</label><br />
<select id="company" name="users" onChange="showUser(this.value)">
<?php
include 'datalogin.php';
$result = mysqli_query($con, "SELECT DISTINCT Company FROM `roster` ORDER BY Company ASC;");
echo '<option value="">' . 'Select a Company' .'</option>';
while ($row = mysqli_fetch_array($result)) {
if ($row['Company'] == NULL) {
} else {
echo '<option value="'.$row['Company'].'">'.$row['Company'].'</option>';
}
}
?>
</select>
<label for="WorkCity">City</label><br />
<select id="WorkCity" name="WorkCity" onChange="showUser(this.value)" value="city">
<?php
include 'datalogin.php';
$result = mysqli_query($con, "SELECT DISTINCT WorkCity FROM `roster` ORDER BY WorkCity ASC;");
echo '<option value="">' . 'Select a City' .'</option>';
while ($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['WorkCity'].'">'.$row['WorkCity'].'</option>';
}
?>
</select>
<label for="WorkZipCode">Zip Code</label><br />
<select id="WorkZipCode" name="WorkZipCode" onChange="showUser(this.value)">
<?php
include 'datalogin.php';
$result = mysqli_query($con, "SELECT DISTINCT WorkZipCode FROM `roster` ORDER BY WorkZipCode + 0 ASC;");
echo '<option value="">' . 'Select a Zip Code' .'</option>';
while ($row = mysqli_fetch_array($result)) {
echo '<option value="'.$row['WorkZipCode'].'">'.$row['WorkZipCode'].'</option>';
}
?>
</select>
<label for="agent">Agent Expertise</label><br />
<label for="ancillary"><input type="checkbox" value="Ancillary" name="Ancillary[]" id="ancillary" />Ancillary</label><br />
<label for="smallgroup"><input type="checkbox" value="Smallgroup" name="Smallgroup[]" id="smallgroup" />Small Group</label><br />
<label for="largegroup"><input type="checkbox" value="LargeGroup" name="LargeGroup[]" id="largegroup" />Large Group</label><br />
<label for="medicare"><input type="checkbox" value="Medicare" name="Medicare[]" id="medicare" />Medicare</label><br />
<label for="longterm"><input type="checkbox" value="LongTerm" name="LongTerm[]" id="longterm" />Long Term Care</label><br />
<label for="individual"><input type="checkbox" value="Individual" name="Individual[]" id="individual" />Individual Plan</label><br />
<label for="tpa"><input type="checkbox" value="TPASelfInsured" name="TPASelfInsured[]" id="tpa" />TPA Self Insured</label><br />
<label for="ppaca"><input type="checkbox" value="CertifiedForPPACA" name="CertifiedForPPACA[]" id="ppaca" />Certified for PPACA</label><br />
</form>
</div>
My php page that pulls the info and places it into a container on the page:
$q = (isset($_GET['q'])) ? $_GET['q'] : false; // Returns results from user input
include 'datalogin.php'; // PHP File to login credentials
$sql="SELECT * FROM `roster` WHERE Company = '".$q."' OR Last_Name = '".$q."' OR WorkCity = '".$q."' OR WorkZipCode = '".$q."' ORDER BY Last_Name ASC";
$result = mysqli_query($con,$sql) // Connects to database or die("Error: ".mysqli_error($con));
echo "<h1>" . "Find a Local OAHU Agent." . "</h1>";
while ($row = mysqli_fetch_array($result)) { // Gets results from the database
echo "<div class='agentcon'>" . "<span class='agentn'>" . "<strong>".$row['First_Name'] . " " .$row['Last_Name'] . "</strong>" . "</span>" . "" . "<span class='email'>".$row['Email'] . "</span>" . "" ."<div class='floathr'></div>";
if ($row['Company'] == NULL) {
echo "<p>";
}
else {
echo "<p>" . "<strong>" .$row['Company'] . "</strong>" . "<br>";
}
echo $row['WorkAddress1'] . " " .$row['WorkCity'] . "," . " " .$row['WorkStateProvince'] . " " .$row['WorkZipCode'] . "<br>";
if ($row['Work_Phone'] !== NULL) {
echo "<strong>" . "Work" . " " . "</strong>" .$row['Work_Phone'] . "<br>";
}
if ($row['Fax'] !== NULL) {
echo "<strong>" . "Fax" . " " . "</strong>" .$row['Fax'] . "<br>";
}
echo "<strong>" . "Agent Expertise:" . "</strong>";
if ($row['Ancillary'] == 1) {
echo " " . "Ancillary" . "/";
}
if ($row['SmallGroup'] == 1) {
echo " " . "Small Group" . "/";
}
if ($row['IndividualPlans'] == 1) {
echo " " . "Individual Plans" . "/";
}
if ($row['LongTermCare'] == 1) {
echo " " . "Long Term Care" . "/";
}
if ($row['Medicare'] == 1) {
echo " " . "Medicare" . "/";
}
if ($row['LargeGroup'] == 1) {
echo " " . "LargeGroup" . "/";
}
if ($row['TPASelfInsured'] == 1) {
echo " " . "TPA Self Insured" . "/";
}
if ($row['CertifiedForPPACA'] == 1) {
echo " " . "Certified For PPACA";
}
echo "</p>" . "</div>";
}
mysqli_close($con);
?>
I appreciate any and all help on this topic! Any time I add the checkbox values to my php file it ends up displaying everyone in the database for all fields in the form.
I am also trying to prevent sql injection on this but how can a user do this if I don't have a field the user can input text into?
EDIT As of today I gave a try with using jQuery to activate the checkboxes and then call some AJAX.
Here is the script I wrote and it is pulling an agent, just not everyone that has that "expertise".
$('input').click(function() {
$.ajax({
url: "process.php",
data: { value: 1},
success: function (data) {
$('#bodyA').html(data);
}
});
});
Here's a quick example of something I recently worked on in which I needed to loop through multiple checkboxes and pass those values into a SQL statement. Although this example happens on a button click, hopefully its something along the lines of what you are trying to accomplish, or at least at start... :)
<?php
$array = array();
if (isset($_POST['medicare'])) {
foreach ($_POST['medicare'] as $value) {
array_push($array, $value);
}
}
// this will return the value of each selected checkbox, separating each with a comma
$result = implode(",", $array);
// if you want to loop through each individually (for example pass each into a SQL statement)
foreach ($_POST['medicare'] as $value) {
// Do your SQL here
// $value will be the value of each selected checkbox (Smallgroup, Largegroup, etc.)
$sql = "insert into tablename(fieldname) values ('$value')"; // just an example
}
?>
<input type="checkbox" name="medicare[]" id="smallgroup" value="Smallgroup" />
<label for="smallgroup">Small Group</label>
<br />
<input type="checkbox" name="medicare[]" id="largegroup" value="Largegroup" />
<label for="largegroup">Large Group</label>
<br />
<input type="checkbox" name="medicare[]" id="medicare" value="Medicare" />
<label for="medicare">Medicare</label>
<br />
<input type="checkbox" name="medicare[]" id="individualplan" value="IndividualPlan" />
<label for="individualplan">Individual Plan</label>
<br />
<input type="submit" value="Submit" id="btnSubmit" name="btnSubmit" />
UPDATE
Instead of setting one variable, try setting a variable for each select control and putting your SQL statement in a foreach loop. I just tested this with some dummy data and didn't have any issues with it.
<?php
$lastname = (isset($_GET['Last_Name'])) ? $_GET['Last_Name'] : false;
$users = (isset($_GET['users'])) ? $_GET['users'] : false;
$workCity = (isset($_GET['WorkCity'])) ? $_GET['WorkCity'] : false;
$WorkZipCode = (isset($_GET['WorkZipCode'])) ? $_GET['WorkZipCode'] : false;
foreach ($_GET['medicare'] as $value) {
//echo $value;
$sql="SELECT * FROM roster WHERE Company = '$users' OR Last_Name = '$lastname' OR WorkCity = '$workCity' OR WorkZipCode = '$WorkZipCode' OR Ancillary = '$value' ORDER BY Last_Name ASC";
}
...continue as you were...
?>
I DID IT!! Wohoo! I ended up just making a separate php page called expertise.php to process the checkboxs using jquery/ajax.
The jQuery that achieved this: (Thank god I went onto the jQuery website to look up functions!)
$('input').click(function() {
$.ajax({
url: "expertise.php",
data: { value: 1},
success: function (data) {
$('#bodyA').html(data);
}
});
});
The PHP page is the same as my process.php page except for the sql:
$sql="SELECT * FROM `roster` WHERE Ancillary = '1' AND SmallGroup = '1' AND CertifiedForPPACA = '1' ORDER BY Last_Name ASC";
If anyone would enlighten me more on making this better protected against sql injections, feel free to!
Agent Search Page
Well I at least got both parts of the search working but a new problem has arose :p
Now in the sql I can use AND or OR, with AND it pulls only agents that have everyone of those expertise and with OR it seems to pull everyone. Any ideas?

Categories