Skips the first repeated Value and fetch the 2nd Value - PHP - php

PHP and MYSQLi
I am trying to get the below output: for a Project ID (PJ006)
I put the "date" column in Descending order first and then i want to skip all the Repeated value of the first value (Skip all entries of EM207) and display the immedate 2nd value (Output expected: EM206). This output is needed against the for a Project ID (PJ006)
Database:
SL No. Badge ID Date ProjectID
1 EM207 2015-05-12 00:00:00 PJ006
2 EM207 2015-05-11 00:00:00 PJ006
3 EM207 2015-05-09 00:00:00 PJ006
4 EM207 2015-05-09 00:00:00 PJ001
5 EM206 2015-05-08 00:00:00 PJ001
6 EM206 2015-09-05 00:00:00 PJ006
7 EM206 2015-09-03 00:00:00 PJ006
8 EM205 2015-09-01 00:00:00 PJ006
Expected output: For Project ID: PJ006,
Badge ID: EM206
PHP Code for: Using the First Badge ID (EM207), fetch the data of the Project ID PJ006 and display
$mysqli=mysqli_connect('serverIP','username','password','databasename');
//This data i passed by Ajax
$someID = trim($_POST["storedValue"]);
//This query puts the date column in Desending Order
$query2 ="SELECT * FROM scores1 WHERE ProjectID='$someID' order by ScoreDate desc limit 1";
$result = mysqli_query($mysqli,$query2)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
while($row=mysqli_fetch_array($result))
{
//the output is displayed here
echo $row[1];
}
What modification is required in the above code "to skip all the Repeated value of the first value (Skip all entries of EM207) and display the immediate 2nd value (Output expected: EM206)". This output is needed against the for a Project ID (PJ006)

$query2 ="SELECT * FROM scores1 WHERE ProjectID='$someID' order by ScoreDate desc limit 1";
$result = mysqli_query($mysqli,$query2)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
$badgeid=0; $proid=0;
while($row= $database->fetch_array($result))
{
if($badgeid!=$row['batchid'] || $proid!=$row['proid']; ){
echo "$badgeid and $proid "
$b=$row['batchid'];
$p=$row['proid'];
}
}

In this answer i am thanking Mr.Thamaraiselvam for helping me with the exact required output. Thanks You.
The Solution which worked:
$mysqli=mysqli_connect('serverIP','username','password','databasename');
$query2 ="SELECT * FROM scores1 where ProjectID='12345' ORDER BY ScoreDate DESC";
$result = mysqli_query($mysqli,$query2)or die(mysqli_error());
$num_row = mysqli_num_rows($result);
$badgeid=0; $proid=0 ; $date=0;
$flag=0;
while($row=mysqli_fetch_array($result))
{
if($badgeid!=$row['BadgeID'] || $proid!=$row['ProjectID'] ){
if($flag==2){
echo "$badgeid and $date<br>";
}
$flag++;
$badgeid =$row['BadgeID'];
$proid =$row['ProjectID'];
$date =$row['ScoreDate'];
}
}
?>

Okay, as discussed, what you're actually after is the most recent badge id for a particular project - the fact that this is the second entry is a bit of a red herring and may not hold true in other scenarios.
I'd use a subquery to find the most recent entries for each project:
select
badgeId,
projectId
from
scores1,
(
select
max(date) as max,
projectId
from
scores1
group by
projectId
) as sub
where
scores1.date = sub.max
and scores1.projectId = sub.projectId
You can then add a check for whichever project id you're interested in. Don't forget to add some indexes for better performance.

Related

how to convert multiple row data into array and subtract it from another array?

I am fetching multiple rows from my data base like,
$query = "SELECT * FROM student_info where district = '".$admdistrict."' AND user_status = 'approved' ORDER BY id DESC";
$result = mysql_query($query) or die(mysql_error());
$delete = mysql_fetch_array($resultt);
$std_delete_array = explode(',', $delete['id']);
the value of id in database is like 4,5,6 in different rows but it is giving only first value 4.
Another array I am fetching is,
$query="SELECT * FROM events where id='$district'";
$showdata=mysql_query($query) or die(mysql_error());
$user=mysql_fetch_array($showdata);
$std_fulllist_array = explode(',', $user['std_list']);
the value in database is 4,5,6,8. But in single coloumn, so it is giving proper output. now I want to subtract $std_delete_array from $std_fulllist_array.
I am using following code,
$values = array_diff($std_fulllist_array, $std_delete_array);
which is only subtracting first value of $std_delete array.
strucutre of table student_info is
id ! name ! District
4 a panipat
5 b panipat
6 c panipat
strucutre of table events is
id ! district ! std_list
1 panipat 4,5,6
2 karnal 4,7,8
3 chandigarh 5,6,7
You are saying the value of id in database is like 4,5,6 in different rows
that means your table is look like
id district
-- ---------
4 abc
5 def
6 geh
8 ijk
so your first query is fetching multiple records.
EDIT
So your query would be
$ret_ = array();
$query = "SELECT * FROM student_info where district = '".$admdistrict."' AND user_status = 'approved' ORDER BY id DESC";
$result = mysql_query($query) or die(mysql_error());
if (mysql_num_rows($result) > 0) {
// output data of each row
while($row = mysql_fetch_array($result)) {
echo $row['id'];
$ret_[] = $row;
}
}
print_r($ret_);

FetchAll(PDO::FETCH_ASSOC) nothing is being returned [duplicate]

This question already has an answer here:
how to properly use while loop in PDO fetchAll
(1 answer)
Closed 5 years ago.
i use this function to call my database
function get_prescriptionWith_4($ID){
$sql = "SELECT prescriptions FROM tblprescriptions WHERE `ID`='$ID'";
$query = $this->dbh->prepare($sql);
$query->execute();
$row = $query->fetchAll(PDO::FETCH_ASSOC));
return #$row;
}
my database table looks like this..
ID | prescription
1 | Med (gen) 20 -- #20/1X per day --morning--for 30 days/,
1 | test (test) 23 -- #343/1X per day --morning and noon-- 120 days23/,
samp (rere) 44 -- #34/1X per day --morning-- 7 days44/,
1 | asd (asd) 22 -- #222/3X per day --morning noon and evening--30 days/,
qw (wq) 44 -- #222/3X per day --morning noon and evening--60 days/,
1233 (123) 21 -- #123213/1X per day --morning--- 60 days/,
what i wanted to achieve is to load all prescription with the same id and since row prescription have multiple data inside it i use explode to separate the data with , when i tried to use Fetch(PDO::FETCH_ASSOC) i only returns the first prescription i think that using fetchAll might be better to fetch all data from my database..
$pres_array3=$patient->get_prescriptionWith_4($ID);
$new_array3=explode(',',$pres_array3,-1);
but when i use echo $new_array3 to check nothing is being return if it is on fetchAll
1) Your prepared statement is wrong/misused
$sql = "SELECT prescriptions FROM tblprescriptions WHERE `ID` = :id";
$query = $this->dbh->prepare($sql);
$query->execute([':id' => $ID]);
2) $query->fetchAll(PDO::FETCH_ASSOC) returns array, so $row['prescriptions'] does not exist and it would throw warning of undefined index prescriptions. A correct version would be
if($row = $query->fetch(PDO::FETCH_ASSOC)){
so since fetchAll(PDO:ASSOC) gives me nothing...i use this approach instead..
$prescriptions = array();
while($row = $query->fetch(PDO::FETCH_ASSOC)){
$prescriptions[] = $row;
}
return $prescriptions;
and then
$pres_array3=$patient->get_prescriptionWith_4($patientID);
<?php
foreach ($pres_array3 as $key => $value) {
$prescription = $value['prescriptions'];
$new_array3=explode(',',$prescription,-1);
foreach($new_array3 as $value) {
?>
<input type="text" value="<?php echo $value?>" />
<?php } } ?>
the reason why i use multiple loop is because on the 1st loop i get all the array data and then explode it to separate the data then loop again since the explode return array not the element..

How to combine array rows and make it variable

I'm using this w3schools way to get data from the database:
$sql = "SELECT num_of_reservations FROM table WHERE date = '$date";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
echo $row["num_of_reservations"];
}
I have database which looks like this:
id - date - num_of_reservations - name
1 - 2017-02-02 - 3 - somebody
2 - 2017-02-02 - 5 - somebody
3 - 2017-02-02 - 7 - somebody
This works fine if I want to echo rows from the database, but now I need to make form which allows you to make reservation only if there is less than 15 reservations already at the same day. Problem in my current design is that every num_of_reservations row is going to different Array (because of while loop I quess) and I need to make them to + (3+5+7) so I can compare, is the num_of_reservations <=15 If it is I display ticket buying screen and if it's not I tell to pick another day.
You can use another query to get the sum of all reservations:
$sql = "SELECT SUM(num_of_reservations) AS sum_of_reservations FROM table WHERE date = '$date'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
if ($row['sum_of_reservations'] <= 15) {
//display ticket buying screen.
} else {
//tell to pick another day.
}

MYSQL-PHP Get value of a specific cell(field) and use it in PHP IF statement

im hoping anyone can help with this issue. Heads up im in the process of learning both PHP and MySQL so please bear with me. I have the following table:
ID whid securitybatch radionumber userbatch status dateofentry
1 AAA 123456 1 5555555 Available 11/10/2016 9:20
2 BBB 123456 7 1234567 Available 11/10/2016 16:50
3 BBB 123456 6 6666666 Deployed 11/11/2016 7:43
4 XXX 123456 3 2222222 Deployed 11/11/2016 19:52
5 XXX 123456 4 1234567 Deployed 11/11/2016 20:03
6 AAA 123456 6 1111116 Deployed 11/11/2016 21:43
7 XXX 123456 2 2222222 Deployed 11/11/2016 21:52
Im trying the get the highlighted value and use it in an IF statement, the issue is my specific requirements.
The user 1234567 has two entries on the table and eventually a lot more, i want to get the value of the status column of the latest dated entry for that user, being the one that is selected, if that makes sense...ive been trying and researching but its beating me up...
$query = "SELECT status FROM radiodata WHERE userbatch='$user' AND MAX(dateofentry)";
$result = mysqli_query($dbc, $query);
So i would love to get the value 'Deployed' a string i suppose and use it as follows:
if($result === 'Deployed') {
echo 'Not returned';
} else {
echo 'Returned';
}
Thanks in advance, any ideas/solutions are welcome.
Cheers
That query in it's current form is invalid and will lead to a syntax error.
$query = "SELECT status FROM radiodata WHERE userbatch='$user' ORDER BY dateofentry DESC LIMIT 1";
$result = mysqli_query($dbc, $query);
You really shouldn't be using string concatenation like this, but let's leave that aside for now. This query will now return you a single row result.
Having done that you still can't compare it to deployed in that manner
$row = mysqli_fetch_array($result);
if ($row['status'] == 'Deployed') {
}
You can order the query by your dateofentry
just add
ORDER BY dateofentry DESC LIMIT 1
to the end of your query and it'll sort it by that column and then the LIMIT will only get you the one result
You can do as follows:
$query = "SELECT status FROM radiodata WHERE userbatch='$user' ORDER BY
dateofentry DESC LIMIT 1";
$result = mysqli_query($dbc, $query);
$row = mysqli_fetch_row($result);
if($row[0] == 'Deployed') {
echo 'Not returned';
} else {
echo 'Returned';
}

How to "shift" query result one row further

Let's say I have something like this:
$sql = $con->query("SELECT * FROM Content ORDER BY Time DESC LIMIT 2");
while ($row = $sql->fetch()) {
echo $row['title'];
}
So this grabs the 2 latest entries in a table and then echoes the designated column. How can I take the 2nd and 3rd most recent entries from my table ignoring the first one?
Right now I'm thinking about setting the limit to 3 and somehow skipping the first result and grabbing the 2 remaining.
Try this :
LIMIT 1,2
1 => offset : From where to start(First one will be 0)
2 => number of records
$sql = $con->query("SELECT * FROM Content ORDER BY Time DESC LIMIT 1,2");
while ($row = $sql->fetch()) {
echo $row['title'];
}

Categories