I tried doing this first:
$e = 0;
$objectsid = mysql_query("SELECT * FROM xw_char_items WHERE CharId = '$charid' AND ItemCat = 'object' ORDER BY SortOrder ASC");
while($obj = mysql_fetch_array($objectsid)) {
$e++;
if($e==9) break;
$objectsinfo = mysql_query("SELECT * FROM xw_objects WHERE ItemId = '{$obj["ItemId"]}'");
$object = mysql_fetch_array($objectsinfo);
echo "&charid$e={$char["Id"]}";
if($objectsid == end($obj)) {
echo "&intActiveObject=1";
echo "&intObjectsNum=$e";
}
}
Here it never detects the last one. I also tried this:
$e = 0;
$len = count($objectsid));
while($obj = mysql_fetch_array($objectsid)) {
$e++;
if($e==9) break;
$objectsinfo = mysql_query("SELECT * FROM xw_objects WHERE ItemId = '{$obj["ItemId"]}'");
$object = mysql_fetch_array($objectsinfo);
mysql_free_result($objectsinfo);
echo "&charid$e={$char["Id"]}";
if ($e == $len - 1) {
echo "&intActiveObject=1";
echo "&intObjectsNum=$e";
}
}
Here it detects every iteration as the last one.
Does anyone how to make it detect the last iteration?
The $objectsid variable is storing the mysql_result object not the array of your fetched rows. So even if you apply count($objectsid), you will not get the length of your fetched array.
So the right method is to use mysql_num_rows().
So Simply do this $len=mysql_num_rows($objectsid); and the rest will workout as you are expecting. :)
Related
I want to pull rows from the database, attach a value to those rows, then order those rows based on a value. The problem is that in trying to do this via the while loop I get an error:
"Parse error: syntax error, unexpected '=>' (T_DOUBLE_ARROW) in
C:\xampp\htdocs\productivitysuite\index.php on line 98"
My goal is to retrieve rows from a database and organize those rows based on a value I calculate in PHP php ($priority), then display certain values of those rows based on their priority. The problem is that I get this darn error and I don't know why, nor do I know where to look for help to resolve it! Hopefully SO can help diagnose this.
code:
<?php
$mysqli = mysqli_connect('127.0.0.1','root','', 'taskdb'); //open connection
//retrieve variables
$sql = "SELECT * FROM tasklist WHERE completion_flag = FALSE";
$sqldata = mysqli_query($mysqli,$sql) or die('error retrieving data');
//Display results
echo "<table>";
echo "<tr><th>Task</th><th>Type</th><th>Due Date</th>";
$counter = 0; //may need to make global, not sure
$results = array();
while($row = mysqli_fetch_array($sqldata, MYSQLI_ASSOC)){
//store each row as variables
if ($row['externalFlag'] == 1) {
$E = 1;
} else{
$E = 0.5;
}
//days until completion
$nowDate = date("m/d/Y");
$D = 1 / (date_diff($row['dueDate']- $nowDate));
//Activity category multiplier
if($row['taskType'] == "Daily"){
$C = 0.5;
} elseif($row['taskType'] == "Maintenance"){
$C = 0.2;
} elseif ($row['taskType'] == "School_Study") {
$C = 0.75;
} elseif ($row['taskType'] == "Personal_Project") {
$C = 0.80;
} elseif ($row['taskType'] == "Work_Project") {
$C = 0.65;
}
$U = ($C - (1 / $D))* $E; //urgency rating; SET PER ROW!
$I = $row['importance']; //Importance rating
$priority = $U + $I;
$results[] = ($row => $priority);
//The array
$priorityOutput = $priorityRow.$counter;
++$counter;
echo "<tr><td>";
echo $row['taskName'];
echo "</td><td>";
echo $row['taskType'];
echo "</td><td>";
echo $row['dueDate'];
echo "</td></tr>";
//Make the below its own loop where I output in order of decreasing UI value
}
//now we have an array of key => value pairs with rows tied to a priority.
//We need to organize the rows by the priority
arsort($results);
echo "</table>"
$mysqli->close(); //close connection
?>
This is a syntax error with your subarray declaration.
Change
$results[] = ($row => $priority);
To
$results[] = array($row => $priority);
Correction: $row is an array, that cannot be used as a key.
I think you might mean:
$results[]=array($row['taskName']=>$priority);
Or maybe:
$results[]=array($priority=>$row);
Depending on your preferred structure.
As an aside, I would replace your taskType conditional block with a lookup array as a matter of clean / more compact code which I believe is easier to maintain and read.
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)
I am trying to get specific data from a while loop and loop it x number of times.
I'm selecting this data:
$r=mysql_query("SELECT ac6, ac5, ac4, ac3, ac2, ac1, ac0 FROM advertisements WHERE token = '".$_GET['token']."'");
while ($adData = mysql_fetch_array($r, MYSQL_NUM))
{
$data = $adData;
$ac0 = $data['ac0'];
$ac1 = $data['ac0'];
print $ac0;
print $ac1;
}
This doesn't work. Nothing gets printed out.
What I want to do is to get ac6 to ac0 value for that specific advertisement (where token).
How can I do that?
Change your numeric fetch to an associative one, then add a foreach loop to process the result.
$r = mysql_query("SELECT ac6, ac5, ac4, ac3, ac2, ac1, ac0
FROM advertisements WHERE token = '" . $_GET['token'] . "'");
while ($adData = mysql_fetch_assoc($r))
{
foreach ($adData as $key => $value)
{
$nubmer = (int)substr($key, 2);
print $value; // or whatever you actually want to do
}
}
Also I hope you're validating $_GET['token'] against possible mischief in your code.
You can create an arrays to add the values from the result query
1st is to create an array:
$advert_AC0 = array();
$advert_AC1 = array();
$advert_AC2 = array();
$advert_AC3 = array();
$advert_AC4 = array();
$advert_AC5 = array();
$advert_AC6 = array();
Now, to add content to array
$r = mysql_query("SELECT ac6, ac5, ac4, ac3, ac2, ac1, ac0
FROM advertisements WHERE token = '" . $_GET['token'] . "'");
if(mysql_num_rows($r)){ //check 1st if there is num of rows from the result
while ($adData = mysql_fetch_assoc($r))
{
array_push($advert_AC0, $dData['ac0']);
array_push($advert_AC1, $dData['ac1']);
array_push($advert_AC2, $dData['ac2']);
array_push($advert_AC3, $dData['ac3']);
array_push($advert_AC4, $dData['ac4']);
array_push($advert_AC5, $dData['ac5']);
array_push($advert_AC6, $dData['ac6']);
}
}else{
echo "NO RESULT.";
}
to call for the array values, 1 by 1
$count_array = count($advert_AC0);
$i = $count_array;
while(1 <= $i){
echo "AC0: $advert_AC0[$i]<br>";
echo "AC1: $advert_AC1[$i]<br>";
echo "AC2: $advert_AC2[$i]<br>";
echo "AC3: $advert_AC3[$i]<br>";
echo "AC4: $advert_AC4[$i]<br>";
echo "AC5: $advert_AC5[$i]<br>";
echo "AC6: $advert_AC6[$i]<br>";
$i++;
}
I don't know if my answer solved your question, please comment if not.
Can't find quite the right answer so hope someone can help. Basically want to create an array and then return the results from a search e.g.
$tsql = "SELECT date, staffid, ID,status, eventid, auditid from maincalendar";
$params = array();
$options = array( "Scrollable" => SQLSRV_CURSOR_KEYSET );
$stmt = sqlsrv_query( $conn, $tsql , $params, $options);
$calarray=array();
while($row = sqlsrv_fetch_array($stmt)) {
$rowresult = array();
$rowresult["status"] = $row['status'];
$rowresult["eventid"] = $row['eventid'];
$rowresult["caldate"] = $row['date'];
$rowresult["staffid"] = $row['staffid'];
$rowresult["ID"] = $row['ID'];
$rowresult["auditid"] = $row['auditid'];
$calarray[] = $rowresult;
}
I would then like to search for values matching 'caldate' and 'staffid' and return the associated entry in $calarray
I suggest the following,
Fetch all data needed for the current month you are showing, using col BETWEEN x AND y
Add them to a array in PHP, with staffid and caldate as key
Something like so;
$calarray[$row['staffid'] . '-' . $row['date']][] = $row;
Not sure if a single staffid/date combination can have one or more events per day, if not you can remove the []
To check if we have information for a specific staffid/date combination, use isset
if (isset($calarray[$staffid . '-' . $mydate]) { ... }
Add indexes to the fields you're going to query, and then move the search to the sql query. You can also make simple filtering inside the loop. So you'll be populating several arrays instead of one, based on the search you need.
try this:
$matches = array();
$caldate = //your desired date;
$staffid = //your desired id;
foreach($calarray as $k => $v){
if(in_array($caldate, $v['caldate']) && in_array($staffid, $v['staffid'])){
$matches[] = $calarray[$k];
}
}
$matches should be and array with all the results you wanted.
also:
while($row = sqlsrv_fetch_array($stmt)) {
$rowresult = array();
$rowresult["status"] = $row['status'];
$rowresult["eventid"] = $row['eventid'];
$rowresult["caldate"] = $row['date'];
$rowresult["staffid"] = $row['staffid'];
$rowresult["ID"] = $row['ID'];
$rowresult["auditid"] = $row['auditid'];
$calarray[] = $rowresult;
}
can be shortened into:
while($row = sqlsrv_fetch_array($stmt)) {
$calarray[] = $row;
}
Maybe this code snipplet solves your problem.
I am not a PHP programmer, so no warrenty.
function searchInArray($array, $keyword) {
for($i=0;$i<array.length();$i++) {
if(stristr($array[$i], $keyword) === FALSE) {
return "Found ".$keyword." in array[".$i."]";
}
}
}
I have a while loop that loops through 3 results and echo's these out in a list. It will always be 3 results.
Here is my current PHP:
while($row = sqlsrv_fetch_array($res))
{
echo "<li>".$row['SessionValue']."</li>";
// prefer to store each value in its own variable
}
However I'd like to store the $row['SessionValue'] value in each loop in a new variable.
So....
first loop: $i0 = $row['SessionValue'];
second loop: $i1 = $row['SessionValue'];
third loop: $i2 = $row['SessionValue'];
How would I achieve this with PHP?
Many thanks for any pointers.
$lst_count = array();
while($row = sqlsrv_fetch_array($res))
$lst_count[] = $row["SessionValue"];
You just need another variable that gets incremented:
$count = 0;
while($row = sqlsrv_fetch_array($res))
{
${i.$count++} = $row['SessionValue'];
}
You can do this have SUM of all value:
$total = array();
while($row = sqlsrv_fetch_array($res))
{
$total[] = $row["SessionValue"]
} $sumAll = array_sum($total);