Removing String from date comming from Oracle12c db - php

So i need a list of dates comming from database for my app. The thing is i just need the time not date but im unable to remove its string.
ive used this in my other tables but for some reason its not working with this api im using php.
substr($row['DATEFROMTABLE'], 9 , strlen(($row["DATEFROMTABLE"]))-0)
SELECT TO_CHAR( VISIT_DATE, 'DD-MON-YY HH24:MI:SS') AS DATEFROMTABLE
FROM tablename t
LEFT JOIN anothertable d ON t.column=d.column
WHERE t.anothercolumn IS NULL AND t.somedate >= TO_DATE('23-JUL-2019 00:00:00', 'DD-MON-YYYY HH24:MI:SS')
AND t.somedate <= TO_DATE('23-JUL-2019 23:59:59', 'DD-MON-YYYY HH24:MI:SS') AND t.column='somedata here'
ORDER BY VISIT_DATE
$stmt = $conn->prepare($query);
$stmt->execute();
$row=$stmt->fetchAll(PDO::FETCH_ASSOC);
$products = array();
$newarr=count($row);
for($k=0;$k<$newarr;$k++)
{
substr($row[$k], 2 , strlen($row[$k])-8);
array_push($products,$row[$k]);
}
echo json_encode($products);
[
{
"DATEFROMTABLE": "23-JUL-19 11:30:00"
},
{
"DATEFROMTABLE": "23-JUL-19 11:45:00"
},
{
"DATEFROMTABLE": "23-JUL-19 12:00:00"
},
{
"DATEFROMTABLE": "23-JUL-19 12:15:00"
},
{
"DATEFROMTABLE": "23-JUL-19 12:30:00"
},
{
"DATEFROMTABLE": "23-JUL-19 12:45:00"
}
]
i need to remove date from this result
this is the result i get in postman

You can do it by editing your SQL like the following:
SELECT TO_CHAR( VISIT_DATE, 'HH24:MI:SS') AS DATEFROMTABLE
...

Related

WHERE clause in the query doesn't work properly in CodeIgniter 3

I'm using CodeIgniter 3 for a project and wrote below function in the controller to pass some data to the view. It queries a table in the database to get blood types as labels and get the count of rows for each blood type where "isAvailable = 1". Then those data is passed into a view to render a chart. But as you can see those counts are wrong. It counts the rows even if "isAvailable = 0". What is the issue of my code and how do I fix that?
Function in the controller.
public function bloodTypesChart()
{
$chartData = [];
$blood_types = $this->db->query("SELECT (BloodType) as blood_type FROM packets WHERE (isAvailable) = '1' GROUP BY blood_type")->result_array();
foreach($blood_types as $bt)
{
$record = $this->db->query("SELECT COUNT(PacketID) as count FROM packets WHERE BloodType = '{$bt['blood_type']}'")->result_array();
foreach($record as $row) {
$chartData['label'][] = $bt['blood_type'];
$chartData['data'][] = $row['count'];
}
}
$chartData['chart_data'] = json_encode($chartData);
$this->load->view('insight',$chartData);
}
View
<script>
new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
labels: <?= json_encode($label)?>,
datasets: [
{
label: "Donations",
backgroundColor: ["#3e95cd", "#8e5ea2","#3cba9f","#e8c3b9","#c45850"],
data: <?= json_encode($data)?>
}
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Donations'
}
}
});
</script>
You have this way too complicated, avoid using php loops to get data which you can get by a simple query.
just use this mysql query, counting the isAvailable rows, when true (1):
$sql=" SELECT BloodType as blood_type, COUNT(PacketID) as mycount
FROM packets
WHERE isAvailable = 1
GROUP BY blood_type
";
note: I've changed the alias count to mycount, since count is a reserved word.
your function would look so:
public function bloodTypesChart()
{
$sql=" SELECT BloodType as blood_type, COUNT(PacketID) as mycount
FROM packets
WHERE isAvailable = 1
GROUP BY blood_type
";
$chartData = [];
$blood_types = $this->db->query($sql)->result_array();
foreach($blood_types as $row)
{
$chartData['label'][] = $row['blood_type'];
$chartData['data'][] = $row['mycount'];
}
$chartData['chart_data'] = json_encode($chartData);
$this->load->view('insight',$chartData);
}
here is a sql-fiddle executing the query using a simplified version of your database
In your query because you have encapsulated only the field name in parenthesis, WHERE (isAvailable) = '1' evaluates to WHERE there is a field labeled isAvailable - which is true for every row in the table. Remove the parenthesis and it should work fine
$blood_types = $this->db->query("SELECT (BloodType) as blood_type FROM packets WHERE isAvailable = '1' GROUP BY blood_type")->result_array();

Placing a json array inside the first array?

How would I make the $query_ppimage results a sub array from the first users query? At the moment, the output is outputting a user, then a profile image, under the user, rather than inside the users array. Therefore they aren't linked.
How would I do such a thing?
Here is my code:
$query_user = "SELECT *,'user' AS type FROM users WHERE username LIKE '".$query."' OR firstname LIKE '".$query."' OR lastname LIKE '".$query."'";
$quser = $conn->query($query_user);
$rows = array();
while($user = mysqli_fetch_assoc($quser)) {
$query_ppimage = "SELECT id, post_id, relation, userID, file_format FROM media WHERE userID = '".$user['id']."' AND relation = 'profile_picture' UNION ALL SELECT -1 id, '55529055162cf' post_id, 'profile_picture' relation, '0' userID, 'jpg' file_format ORDER BY id DESC";
$qppimg = $conn->query($query_ppimage);
while($ppimg = mysqli_fetch_assoc($qppimg)) {
$rows[] = $ppimg;
$rows[] = $user;
}
}
Here is how the array is returned:
[
{
"id": "117",
"post_id": "1",
"relation": "profile_picture",
"userID": "3",
"file_format": "jpg"
},
{
"id": "3",
"email": "casper#socialnetwk.com",
"type": "user"
},
]
How it should look, or something similar. I don't think I named the sub array correctly, but it needs a name ppimage
[
{
"id": "3",
"email": "casper#socialnetwk.com",
"type": "user"
ppimage: {
"id": "117",
"post_id": "1",
"relation": "profile_picture",
"userID": "3",
"file_format": "jpg"
}
},
]
You are adding to $rows twice and appending two separate elements. Try building your array element first and then adding it into the $rows array. Something like this:
$newrow = $user;
$newrow['ppimage'] = $ppimg;
$rows[] = $newrow;
Using JOIN, you could limit this to one single query. Having a query inside a loop is never a good idea, and you should avoid it if you can. Furthermore, you should use prepared statements in order to protect against SQL injection.
The code below uses a JOIN, so that you just get one query - and structures the array as shown in the example. This is hard-coded, as its easier to control what goes where, since we now use a JOIN, the data is all fetched at once (and not in separate variables).
$row = array();
$stmt = $conn->prepare("SELECT m.id, m.post_id, m.relation, m.file_format, u.id, u.email, 'user' as type
FROM media m
JOIN users u ON u.id=m.userID
WHERE m.relation = 'profile_picture'
AND (username LIKE ?
OR firstname LIKE ?
OR lastname LIKE ?)
ORDER BY m.id DESC");
$stmt->bind_param("sss", $query, $query, $query);
$stmt->execute();
$stmt->bind_result($mediaID, $postID, $relation, $file_format, $userID, $user_email, $type);
while ($stmt->fetch()) { // If you just expect one row, use LIMIT in the query, and remove the loop here
$row[] = array('id' => $userID,
'email' => $user_email,
'type' => $type,
'ppimage' => array('id' => $mediaID,
'post_id' => $postID,
'relation' => $relation,
'userID' => $userID,
'file_format' => $file_format)
);
}
$stmt->close();
How can I prevent SQL injection in PHP?
MySQL JOIN

how to make array of array by looping result from a query

I have a survey about games, and I have one table for the games data, and another for people's answers.
I want to output an array in Json format for answers with each of the 3 favorite games name and their year in an array of array.
expected output
[
{
"id": "1",
"username": "userX",
"g1": {"name": "game1", "year": "1991"},
"g2": {"name": "game2", "year": "1992"},
"g3": {"name": "game3", "year": "1993"},
}
]
what i've tried
$sql = "SELECT * FROM tbAnswers AS answer INNER JOIN tbgames AS game ON answer.g1 = game.id";
try {
$db = new db();
$db = $db->connect();
$stmt = $db->prepare($sql);
$stmt->execute();
$answer = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
if(empty($answer)) {
$response->getBody()->write
('
{
"error":
{
"status":"400",
"message":"Invalid Request"
}
}');
} else {
$response->getBody()->write(json_encode($answer));
}
} catch(PDOException $e) {
$response->getBody()->write
('
{
"error":
{
"message":'. $e->getMessage() .'
}
}');
}
the current output
[
{
"id": "1",
"username": "userX",
"name": "game1",
"year": "1991"
}
]
I think i should do a foreach somewhere in else to go through each game and echo the result of it based on the id from answers, but i am not sure how to apply it
where to place to foreach
how to select and get the results based on each game id
how to do it in json format
i'm sure it's not how i am doing it, this is how i am trying to echo the data in else
echo"[";
echo"\n{";
echo"\n";
echo '"id:"'.' "'.$answer[0]->id.'",';
echo"\n";
echo"}\n";
echo"]";
here are my tables structure
tbGames
id , name , year
1 , 'game1' , '1991'
2 , 'game2' , '1992'
3 , 'game3' , '1993'
4 , 'game4' , '1994'
tbAnswers
id , name , g1 , g2 , g3
1 , userX , 1 , 2 , 3
2 , userY , 3 , 1 , 4
3 , userZ , 1 , 1 , 2
4 , userW , 2 , 3 , 4
Using this query:
$sql = "SELECT answer.id a_id, answer.name a_name, game1.id g1_id, game1.name g1_name, game1.year g1_year, game2.id g2_id, game2.name g2_name, game2.year g2_year, game3.id g3_id, game3.name g3_name, game3.year g3_year FROM tbAnswers AS answer INNER JOIN tbgames AS game1 ON answer.g1 = game1.id INNER JOIN tbgames AS game2 ON answer.g2 = game2.id INNER JOIN tbgames AS game3 ON answer.g3 = game3.id";
you should change your else statement content to:
} else {
foreach($answer as $value) {
$array_resp[]=[
'id' => $value->a_id,
'username' => $value->a_name,
'g1' => ['name'=>$value->g1_name, 'year'=>$value->g1_year],
'g2' => ['name'=>$value->g2_name, 'year'=>$value->g2_year],
'g3' => ['name'=>$value->g3_name, 'year'=>$value->g3_year],
];
}
$response->getBody()->write(json_encode($array_resp));
}

How to combine multiples sum and dates from mysql

Im trying to generate data for a graph but everytime i attempt to do it it basically just gives me 1 sum. For the graph i need the date and the value.
This is my current code:
$chart_data = "";
$earnings_query = mysql_query("SELECT SUM(R.rate) as ratess,R.date FROM reports R WHERE R.pid = '$publisher_id' AND R.status = '2'");
if (mysql_num_rows($earnings_query) > 0)
{
while ($row = mysql_fetch_array($earnings_query))
{
$date = date("m/d/Y",strtotime($row['date']));
$chart_data.= '{"date": "'.$date.'", "value": '.$earnings_total['tot'].'},';
}
}
echo $chart_data;
the output is {"date": "12/31/1969", "value": }, but i should be getting daily data all the way back from June 6.
Thanks to all the comments below, the code below solves my problem.
$earnings_query = mysql_query("SELECT SUM(R.rate) as ratess, R.date FROM reports R WHERE R.pid = '$publisher_id' AND R.status = '2' GROUP BY date(R.date)");
if (mysql_num_rows($earnings_query) > 0)
{
while ($row = mysql_fetch_array($earnings_query))
{
$date = date("m/d/Y",strtotime($row['date']));
$chart_data.= '{"date": "'.$date.'", "value": '.$row['ratess'].'},';
}
}
echo $chart_data;
You need a group by clause:
SELECT SUM(R.rate) as ratess, R.date
FROM reports R
WHERE R.pid = '$publisher_id' AND R.status = '2'
GROUP BY R.date;
Without the group by, your query is an aggregation query that runs over the entire set of data. The result (without a group by) is always going to be one row.
If your column called date has a time component, then you might want to use the date() function:
SELECT SUM(R.rate) as ratess, date(R.date) as date
FROM reports R
WHERE R.pid = '$publisher_id' AND R.status = '2'
GROUP BY date(R.date);
Add a GROUP BY date to your SQL command.
SELECT SUM(R.rate) as ratess, R.date
FROM reports R
WHERE R.pid = '$publisher_id' AND R.status = '2'
GROUP BY R.date
This will sum for each date in the range, whereas you were summing for all dates and then selecting the first date. If the date field isn't just a date, but also includes time information, you'll want to use DATE(R.date) instead.

mongo db group-order

i want to mongodb query this sql query's:
select x,y,message,foo from messege where x=1 and y=1 group by x,y order by _id DESC
but with :
MongoCollection::group
can anyone help me?
For this
select a,b,sum(c) csum from coll where active=1 group by a,b
The respective is
db.coll.group(
{key: { a:true, b:true },
cond: { active:1 },
reduce: function(obj,prev) { prev.csum += obj.c; },
initial: { csum: 0 }
});
You cannot sort the results you get from group, you can use sort for find like this for desc -1 , 1 for asc : .sort({"_id":-1}) desc
check this http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Group

Categories