Search in between two different dates [duplicate] - php

This question already has answers here:
How do I query between two dates using MySQL?
(12 answers)
Closed 5 years ago.
I am trying out a search function. But instead of searching from a specific date, I am trying to search from a range of date so that it only displays data I want.
<form action ="searchreceipt.php" method ="post">
<input name="start" type="date" size="30" required />
<input name="end" type="date" size="30" required />
<input type="submit" value="Search"/>
</form>
<?php
$output = '';
if(isset($_POST['search'])) {
$search = $_POST['search'];
$search = preg_replace("#[^0-9a-z]i#","", $search);
$mysqli = new mysqli(spf, dbuser, dbpw, db);
$query = $mysqli->query("SELECT * FROM submission WHERE date BETWEEN 'start' AND 'end'") or die ("Could not search");
while ($row = $query->fetch_array(MYSQLI_ASSOC)) {
$officer_id = $row ['officer_id'];
$sbranch_no = $row ['sbranch_no'];
$carno = $row ['carno'];
$cost = $row ['cost'];
$area = $row ['area'];
$receipt = $row ['receipt'];
echo "<table border='1' style='width:50%'>";
echo "<td>";
echo "<b>Receipt ID: <a href ='transactiondetail.php?receipt=$receipt'>$receipt</b></a>";
echo "<br><br>";
echo "Used By: $officer_id";
echo "<br><br>";
echo "Officer Branch No: $sbranch_no";
echo "<br><br>";
echo "Cost: $cost";
echo "<br><br>";
echo "Area travelled: $area";
echo "<br><br>";
echo "</td>";
}
echo "</table>";
}
?>

You need to execute query like this
$startDate="2017-07-23";
$endDate="2018-01-01";
$query = $mysqli->query("SELECT * FROM submission
WHERE date BETWEEN '".$startDate."' AND '".$endDate."'")
;

Your query must be (ie.select * from table between lowerdate and upperdate):
Here lowerdate is 2017-12-26 10:37:45 and upper date is 2017-12-27 09:38:37
SELECT * FROM `table_name` WHERE (field_name BETWEEN '2017-12-26 10:37:45' AND '2017-12-27 09:38:37')
This will must work.

You needed to get parameter from header by using $_POST.
Try this below.
For more, you can refer here
$start = $_POST['start'];
$end = $_POST['end'];
$query = $mysqli->query("SELECT * FROM submission WHERE date BETWEEN '$start' AND '$end'") or die ("Could not search");

Related

How here the the guest_post() work, The displaying issue in output - image attached and mentioned in the end of the code

My Issue:
<?php //sqltest.php
//Part 01 - The first part of the code will establish connection with DB using mysqli method
require_once 'login.php';
$conn = new mysqli($hn,$un,$pw,$db);
if ($conn->connect_error) die ($conn->connect_error);
// Part - 02 - Here is the method to delete some data using query by taking input and later checking using isset
if (isset($_POST['delete']) && isset ($_POST['isbn'])){
$isbn = get_post($conn,'isbn');
$query ="DELETE FROM classics WHERE isbn = '$isbn'";
$result = $conn->query($query);
if (!$result) echo "DELETE failed: $query<br>". $conn->error . "<br><br>";
}
//Part 04 - Here is the method to insert some data using query by taking input by get_post method-(see the last code) and checking using isset
if (isset($_POST['author']) &&
isset($_POST['title']) &&
isset($_POST['category']) &&
isset($_POST['year']) &&
isset($_POST['isbn'])){
$author = get_post($conn,'author');
$title = get_post($conn,'title');
$category = get_post($conn,'category');
$year = get_post($conn,'year');
$isbn = get_post($conn,'isbn');
$query = "INSERT INTO classics VALUES" . "('$author','$title','$category','$year','$isbn')";
$result = $conn->query($query);
if (!$result) echo "INSERT failed: . $query<br> ". $conn->error. "<br><br>";
}
//Part - 05 - FORM handler
echo <<<_END
<form action="sqltest.php"
method="post">
<pre>
Author <input type = "text" name ="author">
Title <input type = "text" name = "title">
Category <input type = "text" name = "category">
Year <input type = "text" name = "year">
ISBN <input type = "text" name = "isbn">
<input type = "submit" value = "ADD RECORD">
</pre>
</form>
_END;
// Part - 06 -A new query for showing the whole classics table from DB
$query = "SELECT * FROM classics";
$result = $conn->query($query);
if(!$result) die ("Database access failed: ". $conn->error);
$rows = $result->num_rows;
for ($j=0; $j<$rows; ++$j){
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
// Part - 07 The following html code will take the iput for deleting any entry using isbn - refers to 1st part of the code
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<form action = "sqltest.php" method = "post">
<input type ="hidden" name = "delete" value = "yes">
<input type = "hiddden" name = "isbn" value = "$row[4]">
<input type="submit" value = "DELETE RECORD">
</form>
_END;
}
$result->close();
$conn->close();
//Part 08 - actually the code begins from here
function get_post($conn,$var)
{
return $conn->real_eascape_string($_POST[$var]);
//to avoid special charecter
}
?>
/** The code is working very fine. Except two thing: 1. In part 7 of the code i mentioned the isbn number to be keep hidden and only show the delete button. But in output it is showing both number and button. 2. The boxes with the record fields are not set according which is not looking good as expected - i used pre but still it's showing broken output.**/
For #1, you have a typo in hiddden (correct one should be hidden).
For #2, learn how to use css to style the form. Also learn how to use html label tag.
Some people suggests to use table for formatting which is not a best practice and should be avoid.
In general, HTML should only contain information about your content, and CSS take care of the presentation of the content. This is called Separation of Concerns.
The isbn is displayed because you have a spelling issue. You wrote hidden with 3 d‘s in part 7. hope this helps :)
<?php //sqltest.php
//Part 01 - The first part of the code will establish connection with DB using mysqli method
require_once 'login.php';
$conn = new mysqli($hn,$un,$pw,$db);
if ($conn->connect_error) die ($conn->connect_error);
// Part - 02 - Here is the method to delete some data using query by taking input and later checking using isset
if (isset($_POST['delete']) && isset ($_POST['isbn'])){
$isbn = get_post($conn,'isbn');
$query ="DELETE FROM classics WHERE isbn = '$isbn'";
$result = $conn->query($query);
if (!$result) echo "DELETE failed: $query<br>". $conn->error . "<br><br>";
}
//Part 04 - Here is the method to insert some data using query by taking input by get_post method-(see the last code) and checking using isset
if (isset($_POST['author']) &&
isset($_POST['title']) &&
isset($_POST['category']) &&
isset($_POST['year']) &&
isset($_POST['isbn'])){
$author = get_post($conn,'author');
$title = get_post($conn,'title');
$category = get_post($conn,'category');
$year = get_post($conn,'year');
$isbn = get_post($conn,'isbn');
$query = "INSERT INTO classics VALUES" . "('$author','$title','$category','$year','$isbn')";
$result = $conn->query($query);
if (!$result) echo "INSERT failed: . $query<br> ". $conn->error. "<br><br>";
}
//Part - 05 - FORM handler
echo <<<_END
<form action="sqltest.php"
method="post">
<pre>
Author <input type = "text" name ="author">
Title <input type = "text" name = "title">
Category <input type = "text" name = "category">
Year <input type = "text" name = "year">
ISBN <input type = "text" name = "isbn">
<input type = "submit" value = "ADD RECORD">
</pre>
</form>
_END;
// Part - 06 -A new query for showing the whole classics table from DB
$query = "SELECT * FROM classics";
$result = $conn->query($query);
if(!$result) die ("Database access failed: ". $conn->error);
$rows = $result->num_rows;
for ($j=0; $j<$rows; ++$j){
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
// Part - 07 The following html code will take the iput for deleting any entry using isbn - refers to 1st part of the code
echo <<<_END
<pre>
Author $row[0]
Title $row[1]
Category $row[2]
Year $row[3]
ISBN $row[4]
</pre>
<form action = "sqltest.php" method = "post">
<input type ="hidden" name = "delete" value = "yes">
<input type = "hidden" name = "isbn" value = "$row[4]">
<input type="submit" value = "DELETE RECORD">
</form>
_END;
}
$result->close();
$conn->close();
//Part 08 - actually the code begins from here
function get_post($conn,$var)
{
return $conn->real_escape_string($_POST[$var]);
//to avoid special charecter
}
?>

PHP passing Array

I have two php page.
In the first I have looping checkbox array :
<td><input type="checkbox" name="cek[]" value=" <?php echo "$kodeinventarisit" ?>"></td>`
Then i submit form from page one to page two :
<?php
include 'koneksi.php';
$cek = $_POST['cek'];
$jumlah_dipilih = count($cek);
for($x=0;$x<$jumlah_dipilih;$x++){
$jojo = $cek[$x];
$coba = "select * from msstok where kodeinventarisit = '$jojo' ";
$cobaquery = mysql_query($coba);
$hasil = mysql_fetch_array($cobaquery);
$jenis = $hasil['jenis'];
?>
<input name="kode" type="text" id="license" value="<?php echo htmlentities($jenis) ; ?>" readonly="readonly" />
<?php
echo "$jojo";
}
?>
The problem is in the sql query return nothing, I try echo "$jojo" and it's print the value but in the text field is empty..
Does anyone have suggestions on how to fix this?
Thank You Very Much
1
What you are doing is bad.
Load your data before your loop and loop every result to print them.
2
Protect your sql request from injection.
Connect
$db = new mysqli("","root","","");
Prepare your request
$sql = "select * from msstok where kodeinventarisit = ? ";
$res = $db->prepare($sql);
$res->bind_param("sssd",$jojo);
Get results
$res->execute();
Documentation : http://php.net/manual/fr/book.mysql.php
If you want to pass the array you need to check if arrive in you second page.
<pre>
print_r($_POST['cek']);
</pre>
Now, if arrive here, you can read the values like this:
<?php
// If is array(), then you can go to loop
if(is_array($_POST['cek']))
{
// Run the loop
foreach($_POST['cek'] as $value)
{
// Show values per line
echo $value. "<br/>";
}
}
?>
You can read only 1 value of your array
<?php echo $_POST['cek'][0]; ?>
<?php echo $_POST['cek'][1]; ?>
<?php echo $_POST['cek'][2]; ?>
Conclusion
You can't pass array to SQL in query. If you want to use it, this is the only way with implode.
$coba = "SELECT * FROM msstok WHERE kodeinventarisit IN (".implode(',', $jojo).")";
$records = mysql_query($coba, $connection);
while ($row = mysql_fetch_array($records)) {
echo "Name: " . $rows['name'] . "<br />"; // replace the name for column you want
}

Form not displaying in PHP [duplicate]

This question already has answers here:
Can I mix MySQL APIs in PHP?
(4 answers)
Closed 3 years ago.
So I have a page using PHP and a MySQL query. What I'm wanting to do is create basically an "edit" page that takes data from my database and uses it to show the values in various inputs. The user can then change the data in the input which will then update the corresponding MySQL table row. However, for whatever reason the page is NOT displaying the form, but rolling over to the else statement. I can verify the $_SESSION['weaponName'] is working, because it will echo the correct thing. Any ideas on why the form will not show up for me?
edit.php
<?php
session_start();
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$weaponName = $_SESSION['weaponName'];
$query = mysqli_query($con, "SELECT * FROM weapons limit 1");
if(mysqli_num_rows($query)>=1){
while($row = mysqli_fetch_array($query)) {
$creator= $row['creator'];
$weaponCategory= $row['weaponCategory'];
$weaponSubCategory= $row['weaponSubCategory'];
$costAmount= $row['costAmount'];
$costType= $row['costType'];
$damageS= $row['damageS'];
$damageM= $row['damageM'];
$critical= $row['critical'];
$rangeIncrement= $row['rangeIncrement'];
$weight= $row['weight'];
$weaponType= $row['weaponType'];
$masterwork= $row['masterwork'];
$attributes= $row['attributes'];
$specialAbilities= $row['specialAbilities'];
$additionalInfo= $row['additionalInfo'];
}
?>
<form action="weaponEditUpdate.php" method="post">
<input type="hidden" name="weaponName" value="<?php echo $weaponName;?>">
Weapon Name: <input type="text" name="weaponName" value="<?php echo $weaponName;?>">
<br>
Weapon Category: <select name="weaponCategory">
<?php while ($row = mysqli_fetch_array($query)) {
echo "<option value='" . $row['weaponCategory'] ."'>" . $row['weaponCategory'] ."</option>";
} ?>
</select>
<input type="Submit" value="Change">
</form>
<?php
}else{
echo 'No entry found. Go back';
}
?>
As requested by OP (from comment conversations)
Instead of
if(mysqli_num_rows($query)>=1){
use
if(mysqli_num_rows($query) >0){
You're mixing functions
mysqli_connect("localhost","username","password","db_name");
Won't work with
mysql_query("SELECT * FROM weapons limit 1");
Try
$query = mysqli_query($con, "SELECT * FROM weapons limit 1");
And then
if($query->num_rows >= 1)
change this
$query = mysql_query("SELECT * FROM weapons limit 1");
to
$query = mysqli_query("SELECT * FROM weapons limit 1");
BUT omg all your code is mysql while you connected by mysqli !! .
You connect with mysqli, which is fine. THEN, you attempt to run queries via mysql. Those are two separate extensions. You can't mix them as they won't "communicate" with one another. Stick to mysqli.

How do I extract variables from dynamic array and create an update query?

I have a form that is dynamically created based off multiple mysql tables. This form sends to an external page for processing.
this means that my $_POST data will always be different. I need to extract the post array, strip it down and create a query.
here's the print_r of the Posted array:
Array ( [userid] => 1 [modid1] => on [fid1] => on [fid3] => on [fid5] => on [fid7] => on [fid8] => on [modid3] => on )
as you can see I have three parts to this userid, modid, and fid. the catch is, the only way I could pass the id's I need is to name the fields that. So each modid and fid are rows in the db. the number after that is the id that needs updating, and of course "on" is from the check box.
so end result would be something like:
to give a better idea here's how I would write the query normally
for modid1:
UPDATE table SET var = var WHERE modid = 1
for fid1
UPDATE table SET var = var WHERE fid = 1
heres the code that generated this array:
<form id="ajaxsubmit" method="post" action="modules/users/updaterights.php">
<?php
$modsql = mysql_query("SELECT * FROM modules")or die("Mod failed " .mysql_error());
while($row = mysql_fetch_array($modsql))
{
echo '<div class="rights">';
echo "<ul>";
$userid = safe($_POST['user']);
$id = $row['id'];
$sql = mysql_query("SELECT * FROM modpermissions WHERE userid = '$userid' AND modid = '$id'")or die("Mod died " .mysql_error());
$sql2 = mysql_fetch_array($sql);
$modper = $sql2['modpermission'];
if($modper == 1){
echo '<li><input type="checkbox" name="modid'.$row["id"].'" checked> <b>'.$row["name"].'</b></li>';
}
if($modper == 0){
echo '<li><input type="checkbox" name="modid'.$row["id"].'"> <b>'.$row["name"].'</b></li>';
}
if($row['features'] == 1)
{
echo "<ul>";
$sql = mysql_query("SELECT * FROM features WHERE modid = '$id'")or die("Features loop failed " .mysql_error());
while($row2 = mysql_fetch_array($sql))
{
$userid2 = safe($_POST['user']);
$id2 = $row2['id'];
$sql3 = mysql_query("SELECT * FROM fpermissions WHERE userid = '$userid2' AND fid = '$id2'")or die("features died " .mysql_error());
$sql4 = mysql_fetch_array($sql3);
$fper = $sql4['fpermission'];
if($fper == 1){
echo '<li><input type="checkbox" name="fid'.$row2["id"].'" checked> '.$row2['feature'].'</li>';
}
if($fper == 0){
echo '<li><input type="checkbox" name="fid'.$row2["id"].'"> '.$row2['feature'].'</li>';
}
}
echo "</ul>";
}
echo "</ul>";
echo '</div>';
}
?>
<p><input type="submit" id="submit" value="Submit" class="button"> <input type="reset" class="reset" value="Reset Form"> </p>
</form>
its a mess I know, im learning. If someone can understand my question and point me in the right direction to accomplish what Im attempting I would be grateful.
First thing to do is to store the old value as well as having the check box (using a hidden field).
I would also suggest as a minimum using a fixed character as a delimeter in your field names so you can explode the field name to easy get the part that is the id.
Also consider using joins rather than looping around one result, and for each one doing another query.
Your output script would look something like this:-
<form id="ajaxsubmit" method="post" action="modules/users/updaterights.php">
<?php
$userid = safe($_POST['user']);
$modsql = mysql_query("SELECT modules.id, modules.features, modules.name, modpermissions.modpermission
FROM modules
LEFT OUTER JOIN modpermissions
ON modules.id = modpermissions.modid
AND modpermissions.userid = '$userid'")or die("Mod failed " .mysql_error());
$PrevModuleId = 0;
while($row = mysql_fetch_array($modsql))
{
if ($PrevModuleId != $row['id'])
{
if ($PrevModuleId != 0)
{
echo "</ul>";
echo '</div>';
}
echo '<div class="rights">';
echo "<ul>";
$PrevModuleId = $row['id'];
}
echo '<li><input type="checkbox" name="modid_'.$row["id"].'" '.(($row['modpermission'] == 1) ? "checked='checked'" : "").'><input type="hidden" name="modid_old_'.$row["id"].'" value="'.$row['modpermission'].'"> <b>'.$row["name"].'</b></li>';
if($row['features'] == 1)
{
echo "<ul>";
$sql = mysql_query("SELECT features.id, features.feature, fpermissions.fpermission
FROM features
INNER JOIN fpermissions
ON features.id = fpermissions.fid
AND fpermissions.userid = $userid
WHERE modid = '$id'")or die("Features loop failed " .mysql_error());
while($row2 = mysql_fetch_array($sql))
{
echo '<li><input type="checkbox" name="fid_'.$row2["id"].'" '.(($row2['fpermission'] == 1) ? "checked='checked'" : "").'><input type="hidden" name="fid_old_'.$row2["id"].'" value="'.$row2['fpermission'].'"> '.$row2['feature'].'</li>';
}
echo "</ul>";
}
}
if ($PrevModuleId != 0)
{
echo "</ul>";
echo '</div>';
}
?>
<p><input type="submit" id="submit" value="Submit" class="button"> <input type="reset" class="reset" value="Reset Form"> </p>
</form>
You can then loop through each entry on the $_POST array, explode the key based on the _ character, check when the values have changed and if needs be do an update Or possibly you can use an INSERT instead, but using ON DUPLICATE KEY update type syntax (this way you can update many rows with different values easily).
Note you also need to put the userid value somewhere in your form (probably as another hidden field) so you have the value to process with the updates.

Cant SELECT decimal Value

I know this question might sound simple to you, as if it case sensitive issue, However it is not. My problem is that when I try to grab a Decimal value(10,2) it returns 0.00 but the rest of the rows it selected are fine. Here is my code:
This grabs the rows, most of them work and ALL of them are properly typed with Caps in the right places:
$query = "SELECT * FROM invoice WHERE id='$id'";
$result = mysql_query($query) or die("Couldn't execute query");
while ($row = mysql_fetch_array($result)) {
$DateCreated = $row['DateOfCreation'];
$id = $row['id'];
$Description = $row['Description'];
$ProductCode = $row['ProductCode'];
$VatRate = $row['VatRate'];
$PriceExVat = $row['PriceExVat'];
$Status = $row['Status'];
}
This outputs the variable:
<input type="text" name="priceExVat" size="10" id="priceExVat" value="<? echo $PriceExVat; ?>"/>
I would guess that the PHP server has short tags disabled. Try replacing
<? echo $PriceExVat; ?>
with
<?php echo $PriceExVat; ?>

Categories