Get Data From a Query With Several Cases - php

I have a search field with 3 fields (2 field for date range and 1 field for person). I would like if I select the person, then the data based on this person to appear on the screen. Same as I am using the while loop below.
When I select the date range, only the data for this date range to appear on the screen. I am able to do that using the following query.
$startDate = $_POST['startDate'];
$endDate = $_POST['endDate'];
$employer = $_POST['employer'];
$sql = "
SELECT *
FROM jobs
WHERE employer_id = '$employer'
OR (endDate BETWEEN '$startDate' AND '$endDate')
";
$res = mysqli_query($db, $sql) or die(mysqli_error($db));
I would also want if I select both the date range and the person field, then I would like the data for both of them to appear on the screen with the while loop shown below.
I want this to be achieved using the query above, but I do not have a solution.
Then, I extract all data in a while cycle:
while($row = mysqli_fetch_assoc($res))
{
$firstname = $row['firstname'];
$lastname = $row['lastname'];
$title = $row['job_title'];
$date = $row['endDate'];
}

Related

Allowing a user to insert/post in database just once per day everyday

enter image description here
i have a database that has a table name as post and inside it i have a column named as date its data type is current time stamp, so i want each of my user to login to their account and click on a task once a day, and if they have already clicked for that day the insert query will work on the database just like they have inserted a data for that day and i dont want any insert to work for that particular user again if they have already inserted/posted for that day
here are my codes av tried but not working, please help
$status = "";
$date = "";
// POST
if (isset($_POST['pst'])) {
// receive all input values from the form
$status= mysqli_real_escape_string($db, $_POST['status']);
$date = mysqli_real_escape_string($db, $_POST['date']);
//the date here is the old date ie the last post the user has posted maybe yesterday so am using it to check for todays date
//Fetch user ID
$xyttq = $_SESSION['email'];
$sql = "SELECT id FROM users where email = '$xyttq'";
$result = mysqli_query($db, $sql);
// fetch the resulting rows as an array
$pizaq = mysqli_fetch_all($result, MYSQLI_ASSOC);
foreach($pizaq as $pizq){
// echo ($pizq['id']);
$uidbq = ($pizq['id']);
}
// free the $result from memory
mysqli_free_result($result);
// first check the database to make sure
// a user does not already exist with the same username and/or email
$user_check_query = "SELECT * FROM posts WHERE date ='$date' LIMIT 1";
$result = mysqli_query($db, $user_check_query);
$user = mysqli_fetch_assoc($result);
// if user exists am checking the database if the user has posted for that day
if ($user['date'] === $date) {
array_push($errors, "Already exists");
}
// Finally INSERT user if there are no errors in the form
else{
$query = "INSERT INTO posts (userid, status)
VALUES('$uidbq', '$status')";
$results = mysqli_query($db, $query);
}
}
It depends on what you store in your date column. If you store the time of post, then the time can vary and you need to check for the date range. You can check whether there are user's posts between today and tomorrow.
$today = strtotime('today');
$tomorrow = strtotime('tomorrow');
$sql = "SELECT count(*) AS no
FROM posts
WHERE userid = $uidbq
AND date > $today
AND date < $tomorrow";
Then you retrieve no from the query and check whether no is 0 or not.
This table prohibits the insertion of a user more than once per calendar day:
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,user_id INT NOT NULL
,datetime_created TIMESTAMP NOT NULL
,date_created DATE NOT NULL
,UNIQUE(user_id,date_created)
);

how can i display all of the results from my table where the column (date and time) has the the same date and time

You see in my table in the column (date and time) : i have multipes same result date and time.
how can i display all of the results from my table where the column (date and time) has the the same date and time.
how can i count in every table the result of the column price that has the same date and time.
This is my php code:
<tabl>
<?php
function connectDb($username,$password,$hostname,$dbname)
{
$conn=mysql_connect("$hostname","$username","$password") or die(mysql_error());
$db=mysql_select_db("$dbname",$conn) or die(mysql_error());
}
connectDb('root','root','localhost','vetemenstdb');
// end connect db
// start display result
function select()
{
$tableName = 'venteJour';
$query = "SELECT * FROM $tableName";
$sql = mysql_query($query);
while($row = mysql_fetch_assoc($sql))
{
$id = $row['id'];
$Name = $row['nomDuProduit'];
$price = $row['PrixVenteFinal'];
$quantity = $row['QuantityVendue'];
$dateAndTime = $row['dateAndTime'];
echo"
<tr>
<td>$id</td>
<td>$Name</td>
<td>$price</td>
<td>$quantity</td>
<td>$dateAndTime</td>
</tr>";
}
}
select();
//end display result
?>
</table>
What do you mean has the same date and time?
Select DISTINCT dateAndTime from tablename
After doing the same queries in other tables you simply
if ($dateAndTime1 != $dateAndTime2)
return false;
or you could use
array_intersect($array1, $array2)
if you don't want to sort arrays but just want to check equality regardless of value order use http://php.net/manual/en/function.array-intersect.php
Updated:
select dateandtime, count(*) as c from table
group by dateandtime having c > 1

How to pass month and year in url

I am displaying a list of months and years from the database like this into a drop-down menu:
$stmt = $link->prepare("SELECT `b_date` FROM `summary` GROUP BY YEAR(`b_date`), MONTH(`b_date`)");
$stmt->execute();
$result = $stmt->get_result();
$numRows = $result->num_rows;
if($numRows > 0) {
while($row = $result->fetch_assoc()) {
$month = date('F Y', strtotime($row['b_date']));
echo "<option value='{$month}'>{$month}</option>";
}
}
When the user clicks on a choice, it redirects to another page like:
mypage.com/results.php?date=
The problem is that I don't know what to set the value as. In the current code the url produced looks like:
php?date=April%202017
That obviously isn't ideal. And the point is that on the results page I need to show results for the month that was selected. So, I need that query string to query the database.
You can put to select value something like 05-2017:
while($row = $result->fetch_assoc()) {
$month = date('m-Y', strtotime($row['b_date']));
echo "<option value='{$month}'>{$month}</option>";
}
And then get it with DateTime object:
$date = DateTime::createFromFormat('m-Y', $_GET['date']);
And then you can format this object to any format you want:
$formated_date = $date->format('Y-m-d');
You can chose another format, but I think you understand my idea.
UPD. To execute all record on this month try to use this code:
$date = DateTime::createFromFormat('m-Y', $_GET['date']);
$stmt = $link->prepare("SELECT * FROM `summary` WHERE YEAR(`b_date`) = :year AND MONTH(`b_date`) = :month");
$stmt->bindParam(':month', $date->format('m'));
$stmt->bindParam(':year', $date->format('Y'));
$stmt->execute();
$result = $stmt->get_result();
I think its working but maybe need to fix.
Change like this (use urlencode()):-
$month = date('m-Y', strtotime($row['b_date']));
echo "<option value='".urlencode($month)."'>{$month}</option>";
Now on next page check $_GET['date'] and see it's coming proper or not?
if it come proper in format like m-Y then split it with - and now you get month and year separately. Use them in your query or wherever you want.
Query need to be like something:-
$_GET['date'] = '04-2017';
$date_array = explode('-',$_GET['date']);
$month = $date_array[0];
$year = $date_array[1];
"SELECT * FROM summary WHERE MONTH(<you date column name>) = $month";
U can format data in select (postgres, mysql...)
SELECT TO_CHAR('MM-YYYY', b_date) AS formated_date FROM summary GROUP BY TO_CHAR('MM-YYYY', b_date

how can i get the sum of all the products in a certain month in mysql

i am trying to get all the sum of payments made in a specific month lets say from January - March in my website .
My table which is equipments has Money and Joined as columns but the Joined column has both date and time .
I want to use this approach if it is possible but this snippet is for sum of prize.
if (isset($_POST['moneyMade'])){
$moneyMade=0;
$query = "select SUM(Money) from users where Joined<='2016-11-01 00:00:00' and Joined>='2016-11-31 00:00:00'";
//if (!$query) { echo 'MySQL Error: ' . mysqli_error(); exit; }
//$query="select * from equipments ";
$result = mysqli_query($conn,$query);
while ($row = mysqli_fetch_assoc($result)){ /* Fetch a result row as an associative array */
/*while ($row = mysqli_result($result)){*/
$moneyMade +=$row['Money'];
}
echo "Money made for this month is ". $moneyMade;
}
How can i achieve this using php and some sql ?
Thank you.
Assuming that Prize is a numerical value, you could do something like the following.
$month = 'January';
$month_start = strtotime("first day of {$month}");
$month_end = strtotime("last day of {$month}");
$query = "SELECT SUM(`Prize`) FROM `equipments` WHERE UNIX_TIMESTAMP(`Joined`) >= {$month_start} AND UNIX_TIMESTAMP(`Joined`) <= {$month_end}";

How to display table data by today's date?

I have a database called gameschedules and a table called dec1212. Inside of this table are the columns date (YYYY-MM-DD), division, field, time, team1, and team2 in that order.
I already have the data displaying on my page but I need to restrict it to only showing rows in my database that have a date that is equal to the current date. So if there are 10 rows and only 5 of them have today's date in the date column, only those should show. Here is my current query code and I know it is wrong but if someone can help me correct it that would be great:
Current code:
//specifies that it is getting data from the table and limited num rows
$result = mysql_query("SELECT * FROM `dec1212` LIMIT 0, 10 ") or die(mysql_error());
This is what I tried to do to restrict data by date:
//set variable to current date with same format as date column
$myDate = date('Y-m-d');
//pull only rows that match the current date
$result = mysql_query("SELECT * FROM 'dec1212' WHERE date = $myDate()") or die(mysql_error());
I know that my code is incorrect so this is why I am asking for help.
Try this just a signal line query
$result = mysql_query('SELECT * FROM dec1212 WHERE DATE(CONVERT_TZ(date,"+00:00","-8.00")) = DATE(CONVERT_TZ(UTC_TIMESTAMP(),"+00:00","-8.00"))') or die(mysql_error());**
$myDate = date('Y-m-d');
//pull only rows that match the current date
$result = mysql_query("SELECT * FROM `dec1212` WHERE date = '$myDate'") or die(mysql_error());
Try this
$result = mysql_query("SELECT * FROM `dec1212` WHERE `date` = CURDATE()") or die(mysql_error());
Try This
//set variable to current date with same format as date column
$myDate = date('Y-m-d');
//pull only rows that match the current date
$result = mysql_query("SELECT * FROM 'dec1212' WHERE date = $myDate") or die(mysql_error());
You are using variable not the function so just change like this
$myDate = date('Y-m-d');
$result = mysql_query("SELECT * FROM 'dec1212' WHERE date = '$myDate'") or die(mysql_error());
Make sure your date field in database containing the only date, not time
$result = mysql_query("SELECT * FROM 'dec1212'
WHERE `date`= '$myDate'") or die(mysql_error());
if your date field containing datetime datatype then use:
$result = mysql_query("SELECT * FROM 'dec1212'
WHERE `date`= date('$myDate')") or die(mysql_error());
Let the database do the work,
SELECT * FROM `dec1212` WHERE DATE(date) = DATE(NOW())
Note that $myDate is a variable, not a function. Thus, your code would be :
//set variable to current date with same format as date column
$myDate = date('Y-m-d');
//pull only rows that match the current date
$result = mysql_query("SELECT * FROM `dec1212` WHERE date = '$myDate'") or die(mysql_error());
Table name or field name should be wrapped with carat `, not single quote ' or you may omit it.
If you want to use MySQL NOW(), you need to consider time zone conversion as Raj Mohan mentioned.

Categories