PHP 7 and MySQL. I want to take a set of labels stored in the database and individually place each label in its own session variable so I can use them as tab labels in my application.
I can retrieve the data and echo it but the corresponding session variables all show a not set status.
<?php
require_once('dbconnect.inc.php');
$_SESSION['histopic'] = "dash";
$numnames = 100;
for ($i = 1; $i <= $numnames; $i++) {
$stmt = $pdo->prepare('SELECT hislabelsName FROM hislabels WHERE hislabelsID = ?');
$temp = $i;
$stmt->execute(array($temp));
$result = $stmt->fetchALL();
foreach ($result as $row) {
$_SESSION['hislabelsName$i'] = $row["hislabelsName"];
}
echo $_SESSION['hislabelsName$i'] . "<br>";
echo $_SESSION['hislabelsName5'] . "<br>";
}
echo $_SESSION['hislabelsName5']; produces an undefined index error.
How do I fix this?
TIA.
You have to use double quotes like this:
$_SESSION["hislabelsName$i"] = $row["hislabelsName"];
You also do it like this:
$_SESSION["historylabelsName][$i] = $row["hislabelsName"];
Then to echo either:
echo $_SESSION["hislabelsName5"] or echo $_SESSION["hislabelsName][5];
Related
$result = mysqli_query($con, "SELECT * FROM users");
$usersArray=[];
tableArrayPushData($result, $usersArray);
function tableArrayPushData($result, $tableArray){
while ($row = $result->fetch_assoc()) {
$str = '';
foreach ($row as $value) {
$str = $str.$value.'|';
}
$newStr = rtrim($str, "| ");
array_push($tableArray,$newStr);
}
}
for ($i=0; $i<count($usersArray); $i++){//array is always empty at this point
echo "Ok";
echo "<br>";
}
I don't understand why, but usersArray is empty despite the fact that I added data there.
The MySQL table has rows with data, so it can't be empty.
You should use the & operator to allow the function to access the outer variable, like this:
function tableArrayPushData($result, &$tableArray) {}
Or use return.
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.
function table($sql,$border)
{
$con = mysqli_connect("localhost","root","","dbit36");
$resource = mysqli_query($con,$sql);
echo"<table border=0>";
for($i = 0; $i < mysqli_num_fields($resource); $i++)
{
echo "<td style='border:".$border."1px dotted;'><b><font color='990099'size='10'>".mysql_field_name( $resource, $i )."</b></font></td>";
}
echo "</tr>";
while($row = mysqli_fetch_array($resource))
{
echo "<tr>";
for($i = 0; $i < mysqli_num_fields($resource); $i++)
{
echo "<td style='border:".$border."px ridge;'>".$row[$i]."</td>";
}
echo "</tr>";
}
echo "</table>";
}
I know that using mysql function are deprecated in php 5.5+ versions thats why my question is there any mysqli function that can get the name of the specified field in a result?
By using mysqli_fetch_assoc instead of mysqli_fetch_array
Then you can select any field in the table you're fetching by typing $row['field_name']
Reference: http://php.net/manual/en/mysqli-result.fetch-assoc.php
mysqli_fetch_fields is required function to get name of fields.
http://php.net/manual/en/mysqli-result.fetch-fields.php
Try the below one. This is an example, apply your required logic.
$resource = mysqli_query($con,$sql);
while ($fn = mysqli_fetch_field($resource))
{
echo $fn->name; //echo clumn name
echo $fn->table; //tanle name etc
}
Use foreach inside while loop if you really required it.
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.