Creating An Array Without Duplicates From A MySQL Result in PHP - php

I am trying to do a select statement from my MySQL DB in PHP using PDO. I successfully create an array with the query results. But then, I want to filter out duplicate entries with the same date, thus creating an array of dates.
function grabUsefulDates() {
$sql = "SELECT DATETIME, pointcount FROM `fjbarrett`";
$sql_array = dbSelect($sql);
$datesarray = array();
$i = 0;
while($i < count($sql_array)) {
if (count($datesarray) == 0) {
$datesarray[] = datetimeConvertToDate($sql_array[$i]['DATETIME']);
echo "rollone";
} else {
foreach ($datesarray as $f => $date) {
if ($date !== datetimeConvertToDate($sql_array[$i]['DATETIME'])) {
echo $date;
echo " " . datetimeConvertToDate($sql_array[$i]['DATETIME']);
echo "<br>";
$datesarray[] = datetimeConvertToDate($sql_array[$i]['DATETIME']);
}
}
}
$i++;
}
var_dump($datesarray);
}
This code will not run, but when I remove the "add to array" line within the foreach loop, it will run. Any suggestions?

Simply use this query :
SELECT DISTINCT DATETIME, pointcount FROM `fjbarrett`;

Related

How to display data from database MSSQL using foreach/for loop in SQLSRV PHP [duplicate]

This question already has answers here:
How to use foreach get data from the database table --
(3 answers)
Closed 3 years ago.
I'd like to display each rows in a specific column from my db_table. Found below is the code:
$get_sname = sqlsrv_query($conn, "SELECT [columnName] FROM [db_table] inner join [db_table2] on [col_fkey] = [col_pkey] WHERE userName = '$user'",array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
$rdr_sname = sqlsrv_fetch_array($get_sname, SQLSRV_FETCH_ASSOC);
$str = $rdr_sname['[columnName]'];
$rows = sqlsrv_num_rows($get_sname);
if($rows == false){
echo "\nerror\n";
}else{
$a = array($str);
for($i = 0;`$i < $rows;` $i++){
foreach($a as $b){
echo implode($a)."</br>";
}
}
This loop
$a = array($str);
for($i = 0;$i < $rows; $i++){
foreach($a as $b){
echo implode($a)."</br>";
}
}
returns the rows from my db in this format:
rowName
rowName
rowName
what I would like it to return is something like:
rowName1
rowName2
rowName3
I really appreciate all the help I can get on this. Thanks.
Explanations:
You need to make some corrections in your code:
Use parameterized statements to prevent SQL injections. Function sqlsrv_query() does both statement preparation and statement execution and can be used to execute parameterized queries.
The code in the question fetches only the first row in the result set, because sqlsrv_fecth_array() is executed only once. You need to execute sqlsrv_fetch_array() in a loop to fetch the data from all rows.
Example:
You may try with the following code:
<?php
// Statements
$sql = "
SELECT [columnName]
FROM [db_table]
inner join [db_table2] on [col_fkey] = [col_pkey]
WHERE userName = ?
";
$get_sname = sqlsrv_query($conn, $sql, array($user), array("Scrollable" => SQLSRV_CURSOR_KEYSET));
if ($get_sname === false){
echo print_r( sqlsrv_errors());
echo "<br>";
exit;
}
// Results
$rows = sqlsrv_num_rows($get_sname);
if ($rows === false) {
echo "Error"."<br>";
} else {
while ($rdr_sname = sqlsrv_fetch_array($get_sname, SQLSRV_FETCH_ASSOC)) {
echo $rdr_sname['columnName']."<br>";
}
}
// End
sqlsrv_free_stmt($get_sname);
?>
Use this code,
first declare the $count variable. like
$count = 0;
$a = array($str);
for($i = 0;$i < $rows; $i++){
foreach($a as $b){
echo implode($a).$count."</br>";
$count++;
}
}
In case somebody lands here looking for answers, here is the code that's fully working.
$get_store = sqlsrv_query($conn, "SELECT [columnName] FROM [db_table] inner join [db_table2] on [col_fKey] = [col_pKey] where userName = '{$user}'");
if($rows == false){
echo "\nerror\n";
}
else{
$sname = array();
while($storename = sqlsrv_fetch_array($get_store, SQLSRV_FETCH_ASSOC))
{
$sname[] = $storename;
}
foreach($sname as $storename){
echo $storename['storeName'];
}

PHP Query error stdClass Object ( [Id] => )

I'm executing this query on PHP:
$query = 'SELECT email__c, firstname__c FROM user__c';
$result = $mySforceConnection->query($query);
for($i = 0; $i < count($result->records); $i++) {
print_r($result->records[$i])."<br/>\n";
echo("<span>done</span><br/>\n");
}
I just have 2 elements in my database and the output is:
done
done
How I can print the values?
Salesforce returns an array of objects, try something like this instead:
$i=0;
foreach ($response->records as $record) {
$i++;
echo "\n".$i.": \n";
print_r($record);
echo "THE ID IS: ".$record->Id."\n";
}
Another point to remember with salesforce query results is if the field is empty they won't even return it in the object, so you may need to do something like this:
if (isset($record->Name)) { echo "The name is $record->Name\n"; } else { echo "name is blank\n"; }

json_encode returning the next rows values - PHP PDO SQL HighCharts

When trying to use json_encode from arrays in foreach() the data moves in to the next values, for example:
I have this table which is coming from the same query + php:
when using json_encode to try and fit this tables data in to highcharts, my outcome is like this:
[{"name":"User1","data":[0,2,0,0]},{"name":"User2","data":[0,2,0,0,2,0,2,4]}]
So it's moving User1's data in to User2's
My desired outcome would be:
[{"name":"User1","data":[0,2,0,0]},{"name":"User2","data":[2,0,2,4]}]
This is my code:
$uniqueHours = array();
$series = array();
$data = array();
foreach ($pdo->query("SELECT DATEPART(HOUR, AL.EndDateTime) AS 'EndHour'
FROM ActivityLog AL
WHERE
".$where."
ORDER BY AL.EndDateTime, 'EndHour' DESC") as $row)
{
if ( in_array($row['EndHour'], $uniqueHours) ) {
continue;
}
$uniqueHours[] = $row['EndHour'];
}
$ODsql = "SELECT * FROM Users";
foreach ($pdo->query($ODsql) as $row)
{
echo '<tr>';
$SCardNumber = $row['CardNumber'];
$SEmployeeName = $row['Username'];
echo '<td>'.$SEmployeeName.'</td>';
$chartValues = "";
foreach($uniqueHours as $hour)
{
$countSQL= $pdo->prepare("SELECT DISTINCT(COUNT(AL.TerminalNumber)) AS TOTALS
FROM ActivityLog AL, WavePick WP
WHERE AL.TransactionType = 'SPK' AND WP.PickedQty > 0
AND DATEPART(HOUR, AL.EndDateTime) = ".$hour."
AND AL.StartDateTime >= '".$StartDate." 00:00:00.000' AND AL.EndDateTime <= '".$StartDate." 23:59:59.000'
AND AL.OrderNumber = WP.OrderNumber
AND AL.CardNumber = '".$SCardNumber."'
");
$countSQL->execute();
$result = $countSQL->fetch(PDO::FETCH_OBJ);
$row_count = $result->TOTALS;
$totals[] = $result->TOTALS;
echo '<td>'.$row_count.'</td>';
}
echo '</tr>';
$series['name'] = $SEmployeeName;
$series['data'] = $totals;
array_push($data,$series);
}
I haven't actually put this in to the chart yet because the data is invalid.
I am using this to return the outcome:
echo "<div class='well'>";
print json_encode($results, JSON_NUMERIC_CHECK);
echo "</div>";
How can I make this data show only for each user it is linked to?
Before this loop:
foreach($uniqueHours as $hour)
empty $total array with
$total=array();
foreach($uniqueHours as $hour)

php array_intersect not functioning correctly

I currently have 2 arrays where i would like to compare dates in. here are how my arrays are structured:
$bholidays = array('05-05-2014','26-05-2014');
$userdaysoff = array('23-05-2014','24-05-2014','25-05-2014', '26-05-2014');
The aim is to detect whether or not a value from $userdaysoff exists in the $bholidays array.
The above works great and detects that 26-05-2014 exists in both arrays, but if the $userdaysoff array looks like this:
$userdaysoff = array('26-05-2014','27-05-2014','28-05-2014', '29-05-2014');
Then the duplicate date 26-05-2014 is not detected.
Is there any reason why this would be occuring?
here is how i run my code:
$results = array_intersect($bholidays, $userdaysoff);
if($results){
foreach($results as $result){
echo 'yes';
}
} else {
echo 'no';
}
Could you not quite simply use in_array?
$bholidays = array('05-05-2014','26-05-2014');
$userdaysoff = array('23-05-2014','24-05-2014','25-05-2014', '26-05-2014');
$count = count($userdaysoff);
for($i = 0; $i == $count; $i++) {
if(in_array($userdaysoff[$i], $bholidays)) {
echo $userdaysoff[$i] . " is in array.";
}
}
$bholidays = array('05-05-2014','26-05-2014');
$userdaysoff = array('26-05-2014','27-05-2014','28-05-2014', '29-05-2014');
$results = array_intersect($bholidays, $userdaysoff);
if($results)
{
foreach($results as $result)
{
echo 'yes';
}
}
else
{
echo 'no';
}
Run this code and check it works fine..
The output is yes.

For each PHP multi dimension array returns 1 character

For some reason the both code upon killing the query var returns:
SELECT client_fname FROM client WHERE c=:l AND f=:n
Instead of:
SELECT client_fname FROM client WHERE client_id=:id AND client_id=:fname
Notice that only the first character of the column name strings is output.
Where am I going wrong? :S
PHP 5.4, will be using PDO SQL.
public function getField($_field, $_id, $_type) {
$_args = array(
array($_type.'_id', 'id'),
array($_type.'_fname', 'fname')
);
//var_dump($_args);
echo $this->dbSelect($_type.'_'.$_field, $_type, $_args);
}
protected function dbSelect($_select, $_from, $_args) {
$i = 0; //var_dump($_args);
$query = 'SELECT '.$_select.' FROM '.$_from.' WHERE ';
foreach ($_args as $_where) {
if($i == 0) {
$query .= $_where[$i][0] .'=:'. $_where[$i][1];
} else {
$query .= ' AND '.$_where[$i][0] .'=:'. $_where[$i][1];
}
$i++;
}
die($query);
}
$_args was a 2D array. However, your foreach is using $_where as its iteration variable. $_where is itself a one-dimensional array, so you don't need $i here at all. Instead just use $_where[0]
$_where[0] should refer to the column, and $_where[1] refers to its bound placeholder. $i is unrelated to the contents of $_where.
foreach ($_args as $_where) {
if($i == 0) {
$query .= $_where[0] .'=:'. $_where[1];
} else {
$query .= ' AND '.$_where[0] .'=:'. $_where[1];
}
$i++;
}
Otherwise, you are getting the result of an array key access of a string. For example:
$str = "Hello world";
echo $str[0];
// "H"

Categories