Birt date and filter parameters [duplicate] - mysql

I've gotten the basics down, where I've created two files, the search form where a user inputs search parameters, and the results file that cranks out inputted items. For the sake of simplicity, we'll designate the search form file as search.php and the results page as results.php.
search.php
<?php
if (!empty($_POST['id']) && isset($_POST['id'])) {
header("Location: ?m=search.results&id=".$_POST['id']."");
} elseif (!empty($_POST['major']) && isset($_POST['major'])) {
header("Location: ?m=search.results&major=".$_POST['major']."");
} elseif (!empty($_POST['college']) && isset($_POST['major'])) {
header("Location: ?m=search.results&college=".$_POST['college']."");
} elseif (!empty($_POST['name']) && isset($_POST['name'])) {
header("Location: ?m=search.results&name=".$_POST['name']."");
} elseif (!empty($_POST['id']) && !empty($_POST['college']) && !empty($_POST['major'])
&& isset($_POST['submit']) && !empty($_POST['name'])) {
echo "<div class='alert alert-danger'>No students found. Please try different parameters.</div>";
}
?>
<h4>Search</h4>
<form method="POST">
<table width="100%">
<tr><td>ID:</td><td> <input type="text" name="id" class="form-control"></textarea></td></tr>
<tr><td>Name:</td><td> <input type="text" name="name" class="form-control"></textarea></td></tr>
<tr><td>Major:</td><td><select name="major" class="form-control"><option></option><?php echo majorSelect(); ?></select></td></tr>
<tr><td>College:</td><td><select name="college" class="form-control"><option></option><?php echo collegeSelect(); ?></select></td></tr>
<tr><td colspan="2"><input type="submit" name="submit" value="Search" class="btn btn-lrg btn-primary" style="margin-top:10px;"></td></tr>
</table>
</form>
results.php
<!-- Begin Search Parameters -->
<?php
if (isset($_GET['id'])) {
$students = $db->query("SELECT * FROM `user_details` a, `user` b WHERE a.uid = b.id AND a.uid = '".$_GET['id']."'");
while ($student = $students->fetch()) {
echo '
<tr>
<td>'.$student['uid'].'</td>
<td>'.$student['name'].'</td>
<td>'.$student['major'].'</td>
<td>'.$student['college'].'</td>
<td>View</td>
</tr>';
}
} elseif (isset($_GET['major'])) {
$students = $db->query("SELECT * FROM `user_details` a, `user` b WHERE a.uid = b.id AND a.major = '".$_GET['major']."'");
while ($student = $students->fetch()) {
echo '
<tr>
<td>'.$student['uid'].'</td>
<td>'.$student['name'].'</td>
<td>'.$student['major'].'</td>
<td>'.$student['college'].'</td>
<td>View</td>
</tr>';
}
} elseif (isset($_GET['college'])) {
$students = $db->query("SELECT * FROM `user_details` a, `user` b WHERE a.uid = b.id AND a.college = '".$_GET['college']."'");
while ($student = $students->fetch()) {
echo '
<tr>
<td>'.$student['uid'].'</td>
<td>'.$student['name'].'</td>
<td>'.$student['major'].'</td>
<td>'.$student['college'].'</td>
<td>View</td>
</tr>';
}
} elseif (isset($_GET['name'])) {
$name = $_GET['name'];
$students = $db->query("SELECT * FROM `user_details` a, `user` b WHERE a.uid = b.id AND b.name LIKE '%". $name . "%'");
while ($student = $students->fetch()) {
echo '
<tr>
<td>'.$student['uid'].'</td>
<td>'.$student['name'].'</td>
<td>'.$student['major'].'</td>
<td>'.$student['college'].'</td>
<td>View</td>
</tr>';
}
}
So, essentially I would like to rewrite the above whereas a user can input one or more parameters, and the desired result is returned (e.g. both name and college - &name=x&college=y OR all items if need be).

This is easiest to do when using PDO, not mysqli, as your database API.
Build the WHERE clause dynamically. My recommended approach is to push each condition onto an array, and then use implode() to concatenate all the conditions, connecting them with AND or OR as is your preference.
$wheres = array();
$params = array();
if (!empty($_GET['id'])) {
$wheres[] = 'a.uid = :uid';
$params[':uid'] = $_GET['id'];
}
if (!empty($_GET['major'])) {
$wheres[] = 'a.major = :major';
$params[':major'] = $_GET['major'];
}
if (!empty($_GET['name'])) {
$wheres[] = 'b.name LIKE :name';
$params[':name'] = '%'.$_GET['name'].'%';
}
// And so on for all parameters
$sql = "SELECT *
FROM user_details AS a
JOIN user AS b ON a.uid = b.id";
if (!empty($wheres)) {
$sql .= " WHERE " . implode(' AND ', $wheres);
}
$stmt = $db->prepare($sql);
$stmt->execute($params);
Then display the results as in your original code.
while ($student = $stmt->fetch()) {
...
}

If you aren't going to change anything in the database - you are just selecting - go ahead and use GET instead of POST. The advantage of this is that it is going to allow you to save the URL as your search string. You can also refresh the search without getting the resubmit post alert. You just want to make sure that you parameterize your values before you send them to the database. I would normally send those values through sanitize functions, such as a regex that makes sure you only have letters if you expect letters, or a numbers if you expected numbers.
On the same page (all search): (I am just going to outline this for you.)
<form action="<?= $_SERVER["REQUEST_URI"]; ?>" method="GET">
<input name="major" value="<?= $_GET["major"]; ?>" />
<select name="college">
<option value="1" <?PHP if( $_GET["college"] == 1 ) echo 'selected="true"'; ?>>Business</option>
</select>
</form>
<?PHP
if( ! empty( $_GET ) ){
if (isset($_GET['major'])) {
$wheres[] = 'a.major = :major';
$params[':major'] = $_GET['major'];
}
if (isset($_GET['name'])) {
$wheres[] = 'b.name LIKE :name';
$params[':name'] = '%'.$_GET['name'].'%';
}
// And so on for all parameters
$sql = "SELECT *
FROM user_details AS a
JOIN user AS b ON a.uid = b.id";
if (!empty($wheres)) {
$sql .= " WHERE " . implode(' AND ', $wheres);
}
$stmt = $db->prepare($sql);
$stmt->execute($params);
}
?>
Now you can display your data.
edit: I wrote the other half of the answer, and then he wrote the 2nd half, so I just incorporated it...
Also, the next level of sophistication in this would be to take the PHP out of the search file and to put it into another file. When you press the search button in your form, you'd use AJAX to call the PHP elements. Then the PHP file would return the results via Ajax. You could return either the HTML preformatted, or JSON and let something like JQuery display it for you.

Related

How to display certain columns from a table using HTML listbox and SQL code?

Good day, I have the following request: A table with 2 columns: Country and Capital. The table contains every country with every capital from the world. There is a listbox where I can select the country and it will display only the capital from that country.
I created with HTML a listbox which let me to choose a Country:
< select> <br>
< option Country = "Brasil"> Brasil < /option> <br>
< option Country = "... "> .. < /option> <br>
< /select> </br>
How can i display a capital using a country from that HTML listbox? I was thinking to create an option for every capital, but then i'd need over 120 if-cases. (In SQL)
You can generate the select form:
<?php
$req = $pdo->query('SELECT * FROM table');
$rep = $req->fetchAll(); ?>
<select>
foreach($rep as $row) { ?>
<option value="<?= $row['country'] ?>"><?= $row['country'] ?></option>
<? } ?>
</select>
<?php foreach($rep as $row) {
<input style="display:none" id="<?= $row['country'] ?>" value="<?= $row['capital'] ?>" />
<?php } ?>
So you will have the select with all country, and an input for each Capital with their Country as id, so you can display it with javascript: (jQuery example)
<script>
$('select').change(function() {
$('input:visible').toggle();
$('input[id='+$(this).val()+']').toggle();
});
</script>
You can fetch the countries and ther capitals from the database using the following code in php
//This is where you put the fetched data
$entries = Array();
//Make new connection
$connection = new mysqli("127.0.0.1", "username", "password", "databasename");
//Create prepared statement
$statement = $connection->prepare("SELECT `country`, `capital` FROM `table`");
$statement->bind_result($country, $capital);
//Put the fetched data in the result array
while($statement->fetch()) {
$entry = Array();
$entry['country'] = $country;
$entry['capital'] = $capital;
$entries[] = $entry;
}
//Close the statement and connection
$statement->close();
$connection->close();
Next, you make the HTML select objects. It's important that the order of countries remains the same as the order of the capitals.
<!-- Country selection -->
<select id="select-country">
<?php $i = 0;
foreach ($entries as $c) { ?>
<option data-country="<?php echo $i++; ?>"><?php echo $c['country'] ?></option>
<?php } ?>
</select>
<!-- Capitals select -->
<select id="select-capital">
<?php $i = 0;
foreach ($entries as $c) { ?>
<option data-capital="<?php echo $i++ ?>"><?php echo $c['capital'] ?></option>
<?php } ?>
</select>
Finally, you add an event listener to the select with the id of select-country where you listen for the change event. Once called, you change the selected index of the second select to that of the first. That's why it's important that the order remains the same.
<script>
document.getElementById('select-country').addEventListener('change', function () {
document.getElementById('select-capital').getElementsByTagName('option')[this.selectedIndex].selected = true;
});
</script>

Query works when form action is to same page, not when it redirects to another

I have query that gets data from a form, when the submit button is pressed the data should be stored in a database. When the form's action is action="#" the data is inputted into the database. But when the action is action="otherPage.php" the data is not inserted into the database. Any help ?
Side Note: I know the queries need to be changed to counter SQL injection this is just for testing
Code:
if(isset($_POST['submit']))
{
$name = $_POST['fullName'];
$idNumber = $_POST['idNo'];
$cardNo = $_POST['cardNo'];
$_SESSION['fullName'] = $name;
$_SESSION['id'] = $idNumber;
$checkExists = "SELECT * FROM system.table WHERE idNumber = '$idNumber' ";
$resExists = mysqli_query($connection,$checkExists)
or die("Error in query: ". mysqli_error($connection));
if(mysqli_fetch_assoc($resExists) > 0)
{
$updateCard = "UPDATE system.table SET cardNo = '$cardNo' WHERE idNumber=$idNumber";
$resUpdate= mysqli_query($connection,$updateCard)
or die("Error in query: ". mysqli_error($connection));
}
if(mysqli_fetch_assoc($resExists) < 1)
{
$company = $_POST['company'];
$name = trim($name);
$last_name = (strpos($name, ' ') === false) ? '' : preg_replace('#.*\s([\w-]*)$#', '$1', $name);
$first_name = trim(preg_replace('#'.$last_name.'#', '', $name));
$insert = "INSERT INTO system.table (idNumber,name,surname,company,cardNo) VALUES
('$idNumber','$first_name','$last_name','$company','$cardNo')";
$resInsert = mysqli_query($connection,$insert)
or die("Error in query: ". mysqli_error($connection));
}
$connection->close();
}
I do not know if this is the corrext way to go around it, but it works. I included ob_start(); at the beginning of my code, left the action as
<form role="form" method="POST" action="#">
Then included
header('Location:otherPage.php');
so that the page automatically redirects to otherPage.php
If you have two files in the same folder, it should be working:
myFolder
- testForm.php
- testUpload.php
testForm.php:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post" action="testUpload.php">
<fieldset>
<legend>Form</legend>
<label>Name: </label>
<input type="text" name="name">
<input type="submit">
</fieldset>
</form>
</body>
</html>
testUpload.php:
<?php
print($_POST['name']);
exit;
Do you have any Redirection Statements in the config of your Web Server (e.g. Apache httpd.conf)?

Cannot submit form with the enter key

I hate to submit this question but I have been unable to find a solution for almost a week now.
<div class="scanform">
<form action="scanform.php" method="post" id="scanform">
<p> <label for="Order Number">Order Number:</label>
<input name="OrderNumber" id="OrderNumber" autofocus="" type="text"><span class="error">*<?php echo $ONErr;?>
</span></p>
<input name="submit" value="Submit" type="submit"></form>
</div>
The form works well when I click on the submit button but if I type in the text field and hit enter, the form just reloads.
I cannot figure out what I am doing wrong.
The PHP code:
<?php date_default_timezone_set('America/Toronto');
$ONErr = "";
if (isset($_POST['submit']))
{
$link = mysqli_connect("localhost", "username", "password", "ordertracking");
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
if (empty($_POST['OrderNumber'])) {
$ONErr = "OrderNumber is required";
} else {
$OrderNumber = mysqli_real_escape_string($link, $_POST['OrderNumber']);
// Attempt insert query execution
$query = "SELECT * FROM Orders WHERE OrderNumber LIKE '%$OrderNumber' ORDER BY TimeStamp DESC LIMIT 1";
$result = mysqli_query($link, $query) or trigger_error("Query Failed! SQL: $query - Error: ". mysqli_error($mysqli), E_USER_ERROR);
}
// Close connection
mysqli_close($link);
}
?>

Wordpress wpdb->query problems with importing data

My line of code below is supposed to update a NULL value field with (in this case) a pre-defined value. When i execute my wpdb query however the page gives a 500 error.
$wpdb->query( $wpdb->query( "UPDATE ziekbeter SET healthy= '1994-06-04' WHERE person = 5 AND sick IS NOT NULL AND healthy IS NULL") );
Can someone take a look at the line of code and possibly tell me whats wrong?
The code is being executed on a button click.
A screenshot of my wp table is added.
Person ID and the healthy date are going to be dynamic but for now im keeping it static.
profile.php
<?php
$user_ID = get_current_user_id();
echo $user_ID;
global $wpdb;
if ($wpdb->get_results( "SELECT * FROM ziekbeter WHERE person = $user_ID AND healthy IS NULL"))
{
$row = $wpdb->get_results( "SELECT * FROM ziekbeter WHERE person = $user_ID AND healthy IS NULL");
{
?>
<form action="<?php bloginfo('url'); ?>/wp-content/themes/stk/ziekbeter.php" method="post">
<input type="submit" name="submitBeter" value="Meld mij beter!">
</form>
<?php
}
}
elseif ($wpdb->get_results("SELECT healthy FROM ziekbeter WHERE person = $user_ID AND healthy IS NOT NULL"))
{
$row = $wpdb->get_results( "SELECT * FROM ziekbeter WHERE person = $user_ID AND healthy IS NOT NULL");
{
?>
<form action="<?php bloginfo('url'); ?>/wp-content/themes/stk/ziekbeter.php" method="post">
<input type="submit" name="submitZiek" value="Meld mij ziek!">
</form>
<?php
}
}
else {
?>
<form action="<?php bloginfo('url'); ?>/wp-content/themes/stk/ziekbeter.php" method="post">
<input type="submit" name="submitZiek" value="Meld mij ziek!">
</form>
<?php
}
?>
ziekbeter.php
if(isset($_POST['submitZiek']))
{
/* This function will come after i got the submitBeter working */
}
elseif(isset($_POST['submitBeter']))
{
$wpdb->query( $wpdb->query( "UPDATE ziekbeter SET healthy= '1994-06-04' WHERE person = 5 AND sick IS NOT NULL AND healthy IS NULL") );
echo "submitBeter wordt uitgevoerd";
}
Should i replace the wpdb-> query with an echo the code will execute properly and run the echo without any problems.
Try reworking the logic, something like:
profile.php
<?php
global $wpdb;
$user_ID = get_current_user_id();
echo $user_ID;
//First DB query
$row1 = $wpdb->get_results("SELECT * FROM ziekbeter WHERE person = $user_ID AND healthy IS NULL");
//Second DB query
$row2 = $wpdb->get_results("SELECT healthy FROM ziekbeter WHERE person = $user_ID AND healthy IS NOT NULL");
// I.e. greater than zero draw the HTML form
if (count($row1)>0) {
?>
<form action="<?php esc_url(bloginfo('url')); ?>/wp-content/themes/stk/ziekbeter.php" method="post">
<input type="submit" name="submitBeter" value="Meld mij beter!">
</form>
<?php
}
// Second DB query draw different HTML form
if (count($row2)>0) {
?>
<form action="<?php esc_url(bloginfo('url')); ?>/wp-content/themes/stk/ziekbeter.php" method="post">
<input type="submit" name="submitZiek" value="Meld mij ziek!">
</form>
<?php
}
// Draw third HTML form otherwise
if (!$row1 || !$row2) {
?>
<form action="<?php esc_url(bloginfo('url')); ?>/wp-content/themes/stk/ziekbeter.php" method="post">
<input type="submit" name="submitZiek" value="Meld mij ziek!">
</form>
<?php
}
?>
Now, the other file, do not forget to globalize the $wpdb variable:
ziekbeter.php (EDITED):
<?php
global $wpdb;
if(isset($_POST['submitZiek'])) {
/* This function will come after i got the submitBeter working */
}
if(isset($_POST['submitBeter'])) {
$result = $wpdb->query( "UPDATE ziekbeter SET healthy= '1994-06-04' WHERE person = 5 AND sick IS NOT NULL AND healthy IS NULL");
/*Or, use the native WordPress function:
$result = $wpdb->update( $table, $data, $where, $format = null, $where_format = null ); */
if ($result) echo "submitBeter wordt uitgevoerd";
}
?>
If you're trying to access those files directly, i.e. http://example.com/wp-content/themes/stk/profile.php and http://example.com/wp-content/themes/stk/ziekbeter.php, then you need to include WordPress:
<?php
require_once '../../../wp-load.php';
// rest of profile.php
<?php
require_once '../../../wp-load.php';
// rest of ziekbeter.php

CodeIgniter Search Database based on an undefined number of fields?

long time searcher here first time asker.
I am using codeigniter to create a system where a user can use a series of fields in a form to search for a result. None of the fields are required but instead can be used to condense the results. I have it working in straight php which is below but after some serious searching i cannot wrap my head around how to get the functionality working in CodeIgniter. I am new to the software too. Any advice would be much appreciated.
Index.php
<form action="site/searchcharacter.php" method="post" class="form" id="searchForm">
<legend>Search AnimeDB</legend>
<select name="gender"><option>None</option><option>Male</option><option>Female</option></select>
<select name="approx_age"><option>None</option><option>Baby</option><option>Todler</option><option>Child</option><option>Teen</option><option>Adult</option><option>Senior</option></select>
<input type="text" name="hair_colour" class="input-small" placeholder="Hair Colour">
<select name="hair_length"><option>None</option><option>Hair Above Ears</option><option>Hair Below Ears</option><option>Hair Below Shoulders</option><option>Hair Below Waist</option></select>
<input type="text" name="eye_colour" class="ut-small" placeholder="Eye Colour">
<select name="ear_type"><option>None</option><option>Human Ears</option><option>Cat Ears</option><option>Dog Ears</option><option>Horns</option><option>Other</option></select>
<input type="text" name="weapons" class="input-small" placeholder="Weapons">
<div class="form-actions">
<button class="btn btn-primary" id="submit_button" type="submit">Search</button>
</div>
</form>
searchcharacter.php
$query = "SELECT * FROM characters WHERE 1=1";
if ($gender != "None") {
if (!empty($gender)) {
$query = $query . " AND gender='$gender'";
}
}
if ($age != "None") {
if(!empty($age)) {
$query = $query . " AND approx_age='$age'";
}
}
if(!empty($hairColour)) {
$query = $query . " AND hair_colour='$hairColour'";
}
if ($hairLength != "None") {
if(!empty($hairLength)) {
$query = $query . " AND hair_length='$hairLength'";
}
}
if(!empty($eyeColour)) {
$query = $query . " AND eye_colour='$eyeColour'";
}
if ($earType != "None") {
if(!empty($earType)) {
$query = $query . " AND ear_type='$earType'";
}
}
if(!empty($weapons)) {
$query = $query . " AND weapons='$weapons'";
}
//Prepare and Exec
$STH = $DBH->query($query);
I'll start you off with Active Records -
if ($gender != "None" && !empty($gender))
{
$this->db->where('gender', $gender);
}
You can then repeat this for your other checks since multiple wheres are added as chained ANDs.
Then you call $query_result = $this->db->get('characters');