Learning PHP and having an issue that I can't figure out. I have read that PHP only has scope for functions, so I'm not sure why my switch statement isn't changing the value of variables.
Goal: to change the mysql SELECT statement based on user selection of drop-down.
Form:
<form action="contacts_show.php" method="POST">
<select name="grade" id="grade">
<option value="all">All Levels</option>
<option value="elementary">Elementary</option>
<option value="middle">Middle</option>
<option value="senior">Senior</option>
<input type="submit" name="browse" id="browse" value="Browse" />
</form>
PHP (edited to shorten code):
$levelSelected = $_POST['grade'];
if ($levelSelected == "all") {
$querySelect = "SELECT * FROM teachers ORDER BY school ASC";
} else {
$querySelect = "SELECT * FROM teachers WHERE school LIKE %$levelSelected% ORDER BY school ASC";
}
$query = $querySelect;
$result = mysqli_query($connection, $query);
confirm_query($result);
the confirm_query function, if needed:
function confirm_query($result_set) {
if (!$result_set) {
die("Database query failed.");
}
}
When "All Levels" from drop-down is selected, code runs as expected. When any other option is selected, my confirm_query function states that the query fails.
I'm not sure why the variable's values are not switching.
To elaborate on my comment:
Change LIKE %elementary% to => LIKE '%elementary%' and do the same for the others.
You need to wrap the pattern match in quotes, and as per the manual:
http://dev.mysql.com/doc/refman/5.0/en/string-comparison-functions.html#operator_like
mysql> SELECT 'David!' LIKE '%D%v%';
mysql> SELECT 10 LIKE '1%';
You're also not checking for DB errors.
Add or die(mysqli_error($connection)) to mysqli_query()
If that still doesn't work, then it's also a scope issue.
Pass the connection to your function, do not make it global.
Related
Perhaps there may be an easier way to do this however, I need the project to select a patient from the drop down menu. Then when the dropdown menu has got a value, the text field needs to take the NHS number from that drop down menu (array) so that it can be posted elsewhere.
<select name="patient" class="textbox" required>
<option value="">Select a patient</option>
<?php
include 'dbconnection.php';
$sql = "SELECT * FROM clients ORDER by firstname ASC";
$result = mysqli_query($conn, $sql);
$result = $conn-> query($sql);
while($row=mysqli_fetch_array($result))
{
?>
<option value="<?php echo $row["firstname"]." ".$row["lastname"]; ?>">
<?php echo $row["firstname"]." ".$row["lastname"] .", ".$row["addressl1"].", ".$row["addressl2"].", ".$row["county"].", ".$row["postcode"].", ".$row["nhsnum"]; ?></option>
<?php
$nhs = $row['nhsnum'];
}
?>
</select>
<?php
$sql = "SELECT * FROM clients WHERE nhsnum = $nhs ";
$result = mysqli_query($conn, $sql);
$result = $conn-> query($sql);
while($row=mysqli_fetch_array($result))
{
?>
<input type="text" placeholder="NHS number" readonly value=" <?php echo $row["nhsnum"]; ?>">
<?php
}
?>
As you may see, I have created dummy variables of $nhs however its a static variable and doesnt change upon user selection from the drop down list. Can anyone explain how I can merge the two together.
DB setup
i think you should declare the $nhs outside the while loop
Use AJAX, as already suggested, or a form submit button. Your second query should be where your AJAX or submitted form goes. Use $_GET or $_POST, if you are using get or post method, to intercept the option value. Assign that value to your $nhs, then use as you have.
Set the option value to the $nhs value you want, not the person’s name. Example using $_POST
if(isset($_POST['patient'])){
$nhs=$_POST['patient'];
}else{
// whatever code you want to handle a non-submitted value.
}
Add additional code to prevent SQL injection.
I have a search box which a user can search their favorite cases. I have ordered the search results by date, but I want to make it optional for a user and they can choose it by themselves:
$orders = array("date","price"); //field names
$key = array_search($_GET['sort'],$orders)); // see if we have such a name
$orderby = $orders[$key]; //if not, first one will be set automatically. smart enuf :)
$quer = "SELECT*FROM ".$db_table." WHERE
`case`=
'apartment'
AND `field`=
'sell'
ORDER BY
$orderby";
$query=mysqli_query($connect,$quer)
or die(mysqli_error());
?>
<?php while($row = mysqli_fetch_array($query)):
echo "price ";
echo "address ";
//to simplify the code I do not write the rest
?>
<?php endwhile;?>
For example, order by date or price or other things. How can I do it?
Users can get values from dropdownlist:
<select>
<option value="date">order by date</option>
<option value="price">order by price</option>
</select>
Here one example of have you can get this by allowing user to choose order by what and even in whether ASC/DESC (this is also immune to MySQL injections because of set code values). You can remove checkbox if not needed but then don't forget to remove that part in query too:
if (!empty($_POST['dropdownOption']))
{
$orderBy = ($_POST['orderValue'] == "date") ? "date" : "price";
$orderType = (!empty($_POST['orderType'])) ? "DESC" : "ASC";
$quer = "SELECT * FROM TABLE WHERE `case` = 'apartment' AND `field` = 'sell' ORDER BY ".$orderBy." ".$orderType."";
$query = mysqli_query($connect, $quer) or die(mysqli_error());
}
?>
<form method="post" action="">
<select name="orderValue">
<option value="date">order by date</option>
<option value="price">order by price</option>
</select><br>
<input type="checkbox" name="orderType" value="1">In descending order?</input><br>
<input type="submit" name="dropdownOption" value="Apply">
</form>
Note that I gave this as a form (because I'm not informed how your website looks like and I don't know if you're Ajax or something else. If you're Ajax, then you need to make small changes, actually). With the help of CSS, you can achieve this as if it is just a select menu.
Using the MVC Framework, I have made some code that is meant to add information to the Database.
In Index.php (views)
<form method="post" action="<?php echo URL;?>note/updatetopic">
<select>
<option value="1">Coasts</option>
<option value="2">Energy Demand</option>
</select>
<input type="submit" name="topic_selection" value="Choose" />
</form>
The Code above is meant to post information about what a user would like to revise.
In note.php (controllers)
public function updatetopic() {
if (isset($_POST['topic_selection'])) {
$note_model = $this->loadModel('Note');
$note_model->updatetopic($_POST['topic_selection']);
}
header('location: ' . URL . 'note');
}
The Code above is meant to get information from the code in index.php and forward it onto the note_model where it runs a function.
In note_model.php (models)
public function updatetopic($topic_selection)
{
$topic_selection = strip_tags($topic_selection);
$sql = "INSERT INTO users (topic_revising) VALUES (:topicselected) WHERE user_id=:user_id";
$query = $this->db->prepare($sql);
$query->execute(array(':topicselected' => $topic_selection, ':user_id' => $_SESSION['user_id']));
$count = $query->rowCount();
if ($count == 1) {
return true;
} else {
$_SESSION["feedback_negative"][] = TOPIC_UPDATE_FAILED;
}
// default return
return false;
}
This is meant to validate the submitted information and insert it into the database but it outputs:
$_SESSION["feedback_negative"][] = TOPIC_UPDATE_FAILED;
Can someone please help me and tell me what im doing wrong? Thanks.
You are not choosing any name for your select tag:
try like this:
<select name="topic">
<option value="1">Coasts</option>
<option value="2">Energy Demand</option>
</select>
And now get the the value of yuor drop down list:
if (isset($_POST['topic'])) {
$note_model = $this->loadModel('Note');
$note_model->updatetopic($_POST['topic']);
// $_POST['topic'] == 1 or 2 depends upon selection
}
you can change it like:
<select name="topic">
<option value="coasts">Coasts</option>
<option value="Energy_Demand">Energy Demand</option>
</select>
now u'll get the real value of selected list item and can move further....
Your SQL query will not work as you have tagged mysql which does not support this kind of syntax:
INSERT INTO users (topic_revising) VALUES (:topicselected) WHERE user_id=:user_id
Basically there is no WHERE in MySQL (MySQL Insert Where query)
You should check for duplicated either in select query, or if there are unique keys - use ON DUPLICATE KEY. Also take a look at the linked topic
I have searched quite a bit on here about this topic. But I could not find a solution for my problem. I'd appreciate it a lot if you could help me, this is for a school project I am working on.
I have a database with a table ("Main_table") and columns including "sector" and "sub_sector". I want to have two select boxes, first one will load all the records from database in "sector" column and the second one will load all the records from database in "sub_sector" column depending on the selection value of the first select box. (For example: If I select "plastics" on the first select box, then second select box should be updated with sub_sector values where sector value is equal to "plastics").
I have managed to load the options values from database for the first select box but when I click on any selection, it does not load any option to the second select box. You can find the codes below. I did not put "sector_options.php" below, as it seems to work just fine.
index.html shown below:
<script>
$(document).ready(function() {
$('#filter_sector')
.load('/php/sector_options.php'); //This part works fine - uploads options to the first select box
$('#filter_sector').change(function() {
$('#filter_subsector').load('/php/subsector_options.php?filter_sector=' + $("#filter_sector").val()
} //This part does not work - no options on the second select box
);
});
</script>
<body>
<div id="sectors"><p>Sector:</p>
<select id="filter_sector" name="select_sector" multiple="multiple" size="5"> </select>
</div>
<div id="subsectors"><p>Sub Sector:</p>
<select id="filter_subsector" name="select_subsector" multiple="multiple" size="5"> <option value="" data-filter-type="" selected="selected">
-- Make a choice --</option>
</select>
</div>
</body>
</html>
sector_options.php shown below:
<?php
$link = mysqli_connect("*******", "*******","******","********") or die (mysql_error());
$query = "SELECT sector FROM Main_table ";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_assoc($result)) {
$options .= "<option value=\"".$row['sector']."\">".$row['sector']."</option>\n ";
}
echo $options;
?>
subsector_options.php shown below:
<?php
$link = mysqli_connect("********", "*****,"*******", "********") or die (mysql_error());
$Sectors = $_REQUEST['filter_sector'];
$query = "SELECT sub_sector FROM Main_table WHERE sector='$Sectors'";
$result = mysqli_query($link, $query);
while($row = mysqli_fetch_assoc($result)) {$options .= "<option value=\"".$row['sub_sector']."\">".$row['sub_sector']."</option>\n ";
}
echo $options;
?>
For completeness, the solutions were:
Check how AJAX operations are doing using a browser network monitor
Load AJAX fetcher scripts in a browser tag - in many cases they will render quite happily there, allowing them to be more easily debugged
AJAX scripts that return HTML for injection should only return that HTML, and not a full HTML document.
I have a drop down menu that I use to you choose from and this results in a value given to the next page. I would like to use this value to determine where to select from. So the possible values are car and toys. So I would like to let the user use the drop down menu to choose car which results in the database selecting from car to find the item.. If the user chooses toys I would have them select from toys in order to find the item. When I attempt to use this code I just get an error. If I delete '%item%' the error is gone. Any help would be loved. Thanks.
Submitting
<form action="search.php" method="post">
<select>
<option value>Choose A Item</option>
<option value="car" name="item">Car</option>
<option value="toys" name="item">Toys</option>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
Searching
$term = $_POST['term'];
$item = $_POST['item'];
$query = mysql_query("select * from '%$item%' where Items like '%$term%'");
if(mysql_num_rows($query) <= 0)
{
echo "<center>No results. Please try another item.</center>";
} else {
while ($row = mysql_fetch_array($query)) {
echo "<p2>";
echo $row['Items'], ' - Location ' .$row['Loc'];
echo '<br/><br/>';
echo "</p2>";
}
}
?>
1.) - don't use mysql_query - its an outdated library and your query as written above is subject to SQL injection - the most common compromise on the internet.
2.) don't use like '%...%' as this can't be indexed and will be horribly slow on any medium size table or greater. try to at least remove the first % to allow indexing.
http://php.net/manual/en/book.pdo.php
I think your query should be changed into: $query = mysql_query("select * from '$item' where Items like '%$term%'");